user732456
user732456

Reputation: 2688

match a node that has direct links to all nodes in a set

When there is only 2 nodes in the set , it's relatively easy

MATCH (a:Article {id : "PMID:16009338"}),(c:Article {id: "PMID:21743479"}) 
WITH a, c 
MATCH (a)-[r]-(d)-[r1]-(c)
RETURN d

But a similar attempt with 3 nodes didn't work

MATCH (a:Article {id : "PMID:16009338"}),(c:Article {id: "PMID:21743479"}), (p:Article {id: "PMID:21741956"})  
WITH a, c, p
MATCH (a)-[r]-(d)-[r1]-(c)-[r2]-(d)-[r3]-(p) 
RETURN d

It looks for a different relation between c and d. r1 and r2. If I change r2 to r1 it says : Cannot use the same relationship variable 'r1' for multiple patterns.

Even If I make this to work it will be impossible for set of 4+ nodes.

==== Attempt with 3 nodes from different types which executes fast enough

MATCH (a:Article {id : "AID:16009338"}),(v:Video {id: "VID:21743479"}), (s:Song {id: "SID:21741956"})  
WITH a, v, s 
MATCH (a)-[]-(d) 
WITH d, v, s 
MATCH (v)-[]-(d) 
WITH d, s 
MATCH (s)-[]-(d) 
RETURN d

Upvotes: 2

Views: 68

Answers (2)

jacob.mccrumb
jacob.mccrumb

Reputation: 711

So you have X nodes that all need to connect to some other node D?

MATCH (a:Article {id : "AID:16009338"})--(d),(v:Video {id: "VID:21743479"})--(d), (s:Song {id: "SID:21741956"})--(d)
RETURN d

If you know the direction of the relations, add that in. And if you know the name of the relation, add that as well:

MATCH (a:Article {id : "AID:16009338"})-[:ART_TO_D]->(d),(v:Video {id: "VID:21743479"})-[:VID_TO_D]->(d), (s:Song {id: "SID:21741956"})-[:SONG_TO_D]->(d)
RETURN d

Upvotes: 0

Dave Bennett
Dave Bennett

Reputation: 11216

You could look for the common node against a list of articles and then make sure the number that matched afterwards was the same as the number you were matching against.

WITH ['PMID:16009338','PMID:21743479','PMID:21741956'] as articles
MATCH (d)--(a:Article)
WHERE a.id in articles
WITH articles, d, COLLECT(a) AS matched
WHERE size(articles) = size(matched)
RETURN d

Upvotes: 2

Related Questions