OpenDataAlex
OpenDataAlex

Reputation: 1475

Querying for a set number of nodes for both parents and children in Neo4J

Given the following data set:

(a)-[:PARENT]->(b)
(b)-[:PARENT]->(c)
(c)-[:PARENT]->(d)
(d)-[:PARENT]->(e)
(e)-[:PARENT]->(f)
(g)-[:PARENT]->(h)
(h)-[:PARENT]->(i)

I want to be able to traverse the graph both for parents as well as children from the "D" node and limit the number of hops done in the result set (i.e. I want to only go back and forwards two hops to get this data ending up from "B" through "H" nodes but ignoring all other generations).

Upvotes: 0

Views: 230

Answers (1)

cybersam
cybersam

Reputation: 67019

Does this query do what you want? It assumes that all the nodes have an id property with a string value.

MATCH p=()-[:PARENT*..2]->(x)-[:PARENT*..2]->()
WHERE x.id = 'd'
WITH DISTINCT NODES(p) AS np
UNWIND np AS n
RETURN COLLECT(DISTINCT n.id)

The result, given your data, will be ["b","c","d","e","f"].

Upvotes: 1

Related Questions