Cypher request to return one of each sub-node
I have the graph below ( try it in neo4j console ). Starting in the middle, how can I write a cypher-query that restricts the results to only including one of each bilevel node, eg. returning only red nodes?
+3
source to share
1 answer
I am assuming you want to pick at random on the second level. In this case, the following Cypher statement does the job:
START n=node:node_auto_index("name:start")
MATCH (n)-[:link]->(first)
WITH first
MATCH first-[:link]->(second)
WITH first, collect(second) AS coll
RETURN first, coll[toInt(length(coll)*rand())]
We use collect
to place second degree nodes in a collection for each first
node. Using the array index operator, we select one of the elements at random. rand()
returns a value between 0 and <1, so we need to multiply it by the length of the collection.
+3
source to share