问题描述:

I have two users:

CREATE (a:user {id: 1})

CREATE (b:user {id: 2})

I want users to be able to follow each other:

MATCH (a:user {id: 1}), (b:user {id: 2})

CREATE (a)-[r:FOLLOWS]->(b)

But I also need to keep track of when that follow happened:

MATCH (a:user {id: 1}), (b:user {id: 2})

CREATE (a)-[r:FOLLOWS {t: 32409823}]->(b)

My issue is that I need create the :FOLLOWS relation if it does not already exist without making a query to check, then another query to create it. Ideally CREATE UNIQUE would solve this, which works just fine without any changing fields on the relation:

MATCH (a:user {id: 1}), (b:user {id: 2})

CREATE UNIQUE (a)-[r:FOLLOWS]->(b)

(THIS WORKS)

But when I include a timestamp on the relation, create unique will make a second relation because it has a different timestamp.

MATCH (a:user {id: 1}), (b:user {id: 2})

CREATE UNIQUE (a)-[r:FOLLOWS {t: 32409823}]->(b)

(THIS DOESN'T WORK)

The above creates a new relation every time because the timestamp is always changing. Is there any way I can check if any relation with the label :FOLLOWS exists and create the relation with fields if it doesn't?

网友答案:

MERGE and its ON CREATE clause should do what you want. MERGE will match on the :FOLLOWS relationship, and if it does not exist it will create it. ON CREATE is only performed if the MERGE operation created the relationship instead of matching on an existing one.

MATCH (a:user {id: 1}), (b:user {id: 2})
MERGE (a)-[r:FOLLOWS]->(b)
ON CREATE SET r.t = timestamp()
相关阅读:
Top