Uzair Ahmed
Uzair Ahmed

Reputation: 96

Iterate over nodes in neo4j

I have a graph with 2137 different paths, not connected to each other. The nodes in each path are numbered by a property, "Isnad", where Isnad = 1,2,3....2137. I want to return the lengths of all 2137 paths.

match(n:Narrator)
where n.Isnad = "1"
return count(n)

Now this works for me but I want to iterate for "Isnad" so I get the count for all 2137 paths instead of just one. Any suggestions? In pseudocode, it would be like:

for(int i = 1 to 2137)
    match(n:Narrator)
    where n.Isnad = i
    return count(n)

Upvotes: 1

Views: 938

Answers (1)

Gabor Szarnyas
Gabor Szarnyas

Reputation: 5057

Use range and UNWIND:

unwind range(1, 2137) AS i
match p=(n:Narrator)-[*]->(m)
where toInteger(n.Isnad) = i
  and not ()-[]->(n)
  and not (m)-[]->()
return n.Isnad, length(p)
limit 10

Note that we are looking for the longest paths. This is expressed in the WHERE condition: the first node of the path should not have a preceding node (not ()-[]->(n)), while the last node of the path should not have a succeeding node (not (m)-[]->()) -- see this answer.

I included the limit 10 line so that the computation and returning the result will not freeze the server or the web user interface. If the query seems okay, remove limit 10 and see if it still works. When embedded to a client application, it can scale to more results as the rendering of the web UI will no longer be a bottleneck.

Upvotes: 1

Related Questions