Head's Up! These forums are read-only. All users and content have migrated. Please join us at community.neo4j.com.
03-03-2021 06:04 AM
03-03-2021 12:10 PM
I've got to point out first that a separate label per node in your graph doesn't make sense. If they're the same type of thing, then they should have the same label, though they would usually have different property values to differentiate each other.
However, for the sake of adhering to your model, you could use this approach to get the list of ancestors and descendants:
MATCH (n:Node2)
WITH n, [(n)<-[:Child*]-(x) | x] as ancestors, [(x)<-[:Child*]-(n) | x] as descendants
RETURN n, ancestors, descendants
If you only need the single parent, and the list of children, then that's even easier:
MATCH (n:Node2)
WITH n, [(n)<-[:Child]-(x) | x][0] as parent, [(x)<-[:Child]-(n) | x] as children
RETURN n, parent, children
I'm using pattern comprehensions here (all the stuff happening in the brackets) to expand a pattern and collect the results into lists. This is also why we're using [0]
for the parent, this extracts the first element of the list, which should make sense since each node only has at most a single parent.
The pattern comprehensions here are useful not only because they're concise, but also because they work even when such patterns don't exist, such as getting the (empty) list of children from a leaf node, or a null for a parent of the root node.
07-31-2022 02:09 AM
Hi Andrew, thank you for your post is very useful. I have been testing your queries because I want to get "n" parents and children but I'm not able to get it, could you help me please? "n" could be 2, 5 etc
08-03-2022 10:18 AM - edited 08-03-2022 11:39 AM
Hi @lky17
08-11-2022 08:45 AM
All the sessions of the conference are now available online