pewpewlasers
pewpewlasers

Reputation: 3225

Neo4j cypher check if already liked before like

I have the following cypher that I use to like a status update

MATCH (n:user {username: "pewpewlasers"})-[k :STATUSUPDATE|:NEXT*]->(o {address: "234cgdsfg23"})
MATCH (p:user {username: "userThatLikedMyStatus"})
CREATE (p)-[x:LIKES]->(o)
return x

However, before liking the post I want to check if the user has already liked the post. Is it possible to check that in the same query? Basically, I want to check if MATCH (p:user {username: "userThatLikedMyStatus"})-[:LIKES]->(o) exists before the CREATE

EDIT: There is one important detail I forgot. I am sorry. I generally have timestamp info on the LIKES relationship. My query actually looks like this:

MATCH (n:user {username: "pewpewlasers"})-[k :STATUSUPDATE|:NEXT*]->(o {address: "234cgdsfg23"})
MATCH (p:user {username: "userThatLikedMyStatus"})
CREATE (p)-[x:LIKES {date: "TIMESTAMP"}]->(o)
return x

The TIMESTAMP value is based on the time the post was liked. Therefore this changes every time. Since this changes every time, MERGE is always creating a new relationship. Is there a way to get the MERGE to ignore CREATE if a LIKES exists regardless of the date parameter?

Upvotes: 1

Views: 38

Answers (1)

JohnMark13
JohnMark13

Reputation: 3739

If you do not want to do anything different when the relationship already exists then you can use Merge.

MATCH (n:user {username: "pewpewlasers"})-[k :STATUSUPDATE|:NEXT*]->(o {address: "234cgdsfg23"})
MATCH (p:user {username: "userThatLikedMyStatus"})
MERGE (p)-[x:LIKES]->(o)
return x

If x didn't exist, it now will. If x did exist, a new relationship will not be created and the existing one will be returned. The Merge command also has ON CREATE and ON MATCH semantics if you want to carry out any operations based on whether the relationship already existed or not.

Edit - Merge and set property

Sure. assuming that you only want to set the timestamp on the initial creation of the relationship then you can do this.

MATCH (n:user {username: "pewpewlasers"})-[k :STATUSUPDATE|:NEXT*]->(o {address: "234cgdsfg23"})
MATCH (p:user {username: "userThatLikedMyStatus"})
MERGE (p)-[x:LIKES]->(o)
ON CREATE SET x.date = timestamp()
return x

Because the Merge does not contain the date property any existing LIKES relationship (between p and o) would be matched and none created. Of course if none exist a new one will be created at which point you set the timestamp.

Upvotes: 2

Related Questions