cancel
Showing results for 
Search instead for 
Did you mean: 

Head's Up! These forums are read-only. All users and content have migrated. Please join us at community.neo4j.com.

Using match and exists to check if a relationship exists

Hi Team,

I'd like to check if a (User) node has a -[:relationship]-> with Group node. Should I just use MATCH or both MATCH and EXISTS to check if a relationship exists between to nodes with given unique ID.

Thanks,
Arun

1 ACCEPTED SOLUTION

In the case of using a 'match pattern', execution will require to determine all 'group' nodes attached to the 'user' node and capture them for output. In the case of using an 'exists' predicate, all that is required by the execution is to find the existence of just one relationships to a 'group' node. The search can stop after finding the first relationship to a 'group' node. The output is also simpler, as on the 'user' node will be returned, while in the 'match pattern' approach, a row for each 'group' node will be returned.

considering you are just interested in the existence of the relationship, and not the 'relationship' nor 'group' properties, the 'match/exists' approach meets your needs and seems more efficient.

View solution in original post

3 REPLIES 3

In the case of using a 'match pattern', execution will require to determine all 'group' nodes attached to the 'user' node and capture them for output. In the case of using an 'exists' predicate, all that is required by the execution is to find the existence of just one relationships to a 'group' node. The search can stop after finding the first relationship to a 'group' node. The output is also simpler, as on the 'user' node will be returned, while in the 'match pattern' approach, a row for each 'group' node will be returned.

considering you are just interested in the existence of the relationship, and not the 'relationship' nor 'group' properties, the 'match/exists' approach meets your needs and seems more efficient.

In the examples listed under the EXISTS() function MATCH is also used.

particularly the below statements matches all node

MATCH (n)
WHERE exists(n.name)
RETURN
  n.name AS name,
  exists((n)-[:MARRIED]->()) AS is_married

Wow! This is a perfect solution. However, it may be slow when we have many nodes and relationships. Should we add an index on relationships or nodes with the name to make it faster?