Match vs comma separated values


(Rcfro2) #1

Why do these two queries produce different results? I thought having the comma separated statements in the match clause were equivalent to using another match statement. And yet the former returns actors with Keanu Reeves in the mix while the latter does not. Is that coincidence?

match (k:Person{name:"Keanu Reeves"})- [:KNOWS] -(friends)
match (friends)-[:KNOWS]-(friendsOFfriends)
return distinct friendsOFfriends.name
limit 5

vs

match (k:Person{name:"Keanu Reeves"})- [:KNOWS] -(friends),
(friends)-[:KNOWS]-(friendsOFfriends)
return distinct friendsOFfriends.name
limit 5


(Andrew Bowman) #2

This is a consequence to the uniqueness of matching used within a single MATCH pattern. Cypher uses a type of uniqueness called 'RELATIONSHIP_PATH', meaning that within a single path, the same relationship will only ever be traversed once (this is useful for many things, notably to prevent infinite loops in traversal by taking the same relationships over and over). This uniqueness applies for the entire pattern in a single MATCH (or OPTIONAL MATCH), so it does apply to comma-separated parts of the pattern.

Since you're using two separate MATCHes in the first query, the :KNOWS relationship you traversed to get from k to friends can be reused to get from friends to friendsOFfriends, so Keanu Reeves is able to be returned in those results.

In the second query, since it's the same pattern being used (just comma-separated), that KNOWS relationships from k cannot be traversed again to get friendsOFfriends, so Keanu Reeves cannot be reached or returned in the results.


(Rcfro2) #3

Thank you @andrew.bowman. Do you mind showing me where this is in the documentation? I may have misread, so I would much appreciate being able to see it.


(Andrew Bowman) #4

Sure, this is described in the Uniqueness section of the docs, tucked away in the Cypher introduction section.