How to use max() on a collection?

2019-08-09 22:19发布

问题:

I have a dataset that looks something like this:

CREATE (n {name:'main', val:3}) -[:r]-> ({name:'sub1', val:2}), (n)-[:r]->({name:'sub2', val:1})

Now, I need to find the maximum value for 'val' for all nodes that are connected to the node named 'main' (including 'main' too). So, in this case the answer is 3.

Since the node named 'main' may not have any subnodes, I used OPTIONAL MATCH to find the subnodes, then combine all the vals found into a list and call max() on it, like so:

MATCH (n {name:'main'})
OPTIONAL MATCH (n)-[:r]->(subs)
RETURN max(n.val +  collect(subs.val))

But this gives the following error:

Type mismatch: expected Float or Integer but was Collection (line 3, column 18 (offset: 73)) "RETURN max(n.val + collect(subs.val))"

What is the correct may to solve this sort of problem?

回答1:

This should work for you:

MATCH p=(n {name:'main'})-[:r*0..]->(subs)
UNWIND NODES(p) AS node
RETURN MAX(node.val) AS result;

This query uses a variable-length pattern to follow the entire (optional) chain of r relationships. Your query did not. The NODES() function produces a collection of path nodes, and the UNWIND converts the collection to data rows. Aggregation functions like MAX() only aggregate across data rows.



标签: neo4j max cypher