insalada
insalada

Reputation: 11

Query intersection of Paths in Neo4j using Cypher

Having this query working in Cypher (Neo4j):

MATCH p=(g:Node)-[:FOLLOWED_BY *2..2]->(g2:Node) 
WHERE g.group=10 AND g2.group=10 
RETURN p

which returns all possible paths belonging a specific group (group is just a property to classify nodes), I am struggling to get a query that returns the paths in common between both collection of paths. It would be something like this:

MATCH p=(g:Node)-[:FOLLOWED_BY *2..2]->(g2:Node) 
WHERE g.group=10 AND g2.group=10
MATCH p=(g3:Node)-[:FOLLOWED_BY *2..2]->(g4:Node) 
WHERE g3.group=15 AND g4.group=15 
RETURN INTERSECTION(path1, path2)

Of course I made that up. The goal is to get all the paths in common between both queries.

Upvotes: 1

Views: 423

Answers (1)

cybersam
cybersam

Reputation: 67019

The start/end nodes of your 2 MATCHes have different groups, so they can never find common paths.

Therefore, when you ask for "paths in common", I assume you actually want to find the shared middle nodes (between the 2 sets of 3-node paths). If so, this query should work:

MATCH p1=(g:Node)-[:FOLLOWED_BY *2]->(g2:Node) 
WHERE g.group=10 AND g2.group=10
WITH COLLECT(DISTINCT NODES(p1)[1]) AS middle1
MATCH p2=(g3:Node)-[:FOLLOWED_BY *2]->(g4:Node) 
WHERE g3.group=15 AND g4.group=15 AND NODES(p2)[1] IN middle1
RETURN DISTINCT NODES(p2)[1] AS common_middle_node;

Upvotes: 1

Related Questions