I have a graph with “Chunk” nodes that each have about 5 connected nodes of various types. I would like to know a cypher query which returns every “Chunk” node and say only 3 connected nodes per “Chunk” node.
I already tried asking LLMs and Google, but couldn’t find anything.
I actually tried Duck.ai again and got something which works:
MATCH (c:Chunk)
OPTIONAL MATCH (c)<-[r]-(p)
WITH c, r, p
ORDER BY r // Specify an order if needed
WITH c, COLLECT(p)[..3] AS limited_p, COLLECT(r)[..3] AS limited_r
RETURN c, limited_r, limited_p
If someone has insight into up- and downsides for this, im always ears, will close this for now though.
You can use subqueries to accomplish this.
A subquery will execute per incoming row, so if you match on the :Chunk nodes and use a subquery, it will execute per chunk. The LIMIT will be scoped to the individual subquery execution (in this case per :Chunk) which should be what you want:
MATCH (c:Chunk)
CALL (c) {
MATCH (c)<-[r]-(p)
RETURN p
LIMIT 3
}
RETURN c, p
If you want to collect the nodes into a list, then you can use a collect {} subquery instead:
MATCH (c:Chunk)
WITH c, collect {
MATCH (c)<-[r]-(p)
RETURN p
LIMIT 3
} as pList
RETURN c, pList
There are other ways to alter these, in case you want to collect the paths, or have separate lists for the relationships and nodes.