0
votes

I am trying to implement a liking mechanism to the the demo newsfeed shown here http://docs.neo4j.org/chunked/stable/cypher-cookbook-newsfeed.html

So basically when a user clicks like on a status update I want to link the user node to the status update node. However I want to search for the status update node through the author's node. Hence I use something like the following:

MATCH (n:user)-[:STATUSUPDATE]->(m)-[:NEXT*]->(o)
WHERE n.username = "pewpewlasers" AND (m.permalink = "acode" OR o.permalink = "acode")
MATCH (p:user)
WHERE id(p)=1,
CREATE (p)-[x:LIKED]->(o)
return x

Basically what I am trying to achieve is, finding a status update node through the author's node, and then looking for the update with a permalink code.

When found I want to connect the liker user's node to the status update through a LIKED relationship.

However, you probably already see the problems with this cypher.

This cypher requires that the permalink is one of the nodes that is connected with NEXT relationship, otherwise if the first node (connected by the STATUSUPDATE relationship) contains the permalink, it selects all status update nodes connected by the NEXT relationship. The user will thus end up liking all posts. What is probably required is like the following:

MATCH (n:user)-[:STATUSUPDATE]->(m)-[:NEXT*]->(o)
WHERE n.username = "pewpewlasers" AND m.permalink = "acode"
-- IF THE ABOVE GIVES AN OUTPUT THEN --
   MATCH (p:user)
   WHERE id(p)=1,
   CREATE (p)-[x:LIKED]->(m)
   return x
-- ELSE --
   MATCH (n:user)-[:STATUSUPDATE]->(m)-[:NEXT*]->(o)
   WHERE n.username = "pewpewlasers" AND o.permalink = "acode"
   MATCH (p:user)
   WHERE id(p)=1,
   CREATE (p)-[x:LIKED]->(o)
   return x
1

1 Answers

1
votes

Here's a way to get around your problem.

START p = node(1) // Do you really want to use node numbers?    
MATCH (n:user {username = 'pewpewlasers'})-[:STATUSUPDATE|:NEXT*]->(m {permalink : 'acode'})
CREATE (p)-[x:LIKED]->(m)

By using the '|' and multimatch in the relationship part of the MATCH clause, the 'm' node is able to match any part of the status update chain. If you really are going to use node numbers (the output of the 'id()' function) to get your liking user node, it's probably faster to do it as shown above.