Limiting the results of a Cypher Neo4j query to the sum of the relationship property

Is there a way to limit the cypher request to the sum of the relation property?

I am trying to create a cypher request that returns nodes at a distance of 100 from the beginning of the node. All relations have a given distance, the sum of all distances along the path is the total distance from the beginning of the node.

If the WHERE clause can handle aggregate functions, what I'm looking for might look like this:

START n=node(1) MATCH path = n-[rel:street*]-x WHERE SUM( rel.distance ) < 100 RETURN x 

Is there a way that I can summarize relationship distances in a path for a where clause?

+6
source share
3 answers

Of course, what you want to do is similar to being in a SQL query.

In cypher, you can link query segments and use the results of the previous parts in the next part with WITH , see the manual.

For your example, one might assume:

 START n=node(1) MATCH n-[rel:street*]-x WITH SUM(rel.distance) as distance WHERE distance < 100 RETURN x 

Unfortunately, the amount does not work with collections yet

So I tried to do it differently (for variable length paths):

 START n=node(1) MATCH n-[rel:street*]-x WITH collect(rel.distance) as distances WITH head(distances) + head(tail(distances)) + head(tail(tail(distances))) as distance WHERE distance < 100 RETURN x 

Unfortunately, the head of an empty list does not return null , which can be coalesce d to 0 , but just fails. So this approach will only work for fixed-length paths, I don't know if this works for you.

+1
source

I recently ran into the same problem. In later versions of neo4j, this was allowed by extract and reduction of sentences. You can write:

 START n=node(1) MATCH path = (n)-[rel:street*..100]-(x) WITH extract(x in rel | x.distance) as distances, x WITH reduce(res = 0, x in rs | res + x) as distance, x WHERE distance <100 RETURN x 
0
source

I don't know about the restriction in the WHERE clause, but you can just specify it in the MATCH clause:

 START n=node(1) MATCH path = n-[rel:street*..100]-x RETURN x 

see http://docs.neo4j.org/chunked/milestone/query-match.html#match-variable-length-relationships

-1
source

Source: https://habr.com/ru/post/925531/


All Articles