Renato Dinhani
Renato Dinhani

Reputation: 36666

How to return only nodes that matches all relationships in a Cypher query?

Supposing I have the following relationships, how can I return all nodes connected to 3, 4 and 5 (node 1), but ignore nodes that have some of them, but not all (nodes 2 and 3).

1--4
1--5
1--6

2--4

3--5
3--6

Upvotes: 0

Views: 476

Answers (2)

cybersam
cybersam

Reputation: 66947

I assume your question has a typo, and you meant to ask how to return all nodes that are connected to all of these nodes: 4, 5, and 6.

Here is a query that is explicitly just for 4, 5, and 6.

MATCH (n)--({id: 4}), (n)--({id: 5}), (n)--({id: 6})
RETURN n;

And here is a query that could be used for any list of ids (in this example: 7, 8, 9, 10):

WITH [7, 8, 9, 10] AS list
MATCH (n)--(x)
WITH list, LENGTH(list) AS lth, n, COLLECT(DISTINCT x.id) AS cx
WHERE (LENGTH(cx) >= lth) AND ALL (i IN list WHERE i IN cx)
RETURN n;

Upvotes: 1

Christophe Willemsen
Christophe Willemsen

Reputation: 20175

You can use the UNION clause : http://neo4j.com/docs/stable/query-union.html#union-combine-two-queries-and-remove-duplicates

MATCH (n:Label)
WHERE (n)--(n4)
AND (n)--(n5)
AND (n)--(n6)
RETURN distinct(n)
MATCH (n)
WHERE (n)--(n4)
OR (n)--(n5)
RETURN distinct(n)

Upvotes: 0

Related Questions