How to use max() on a collection?

眉间皱痕 提交于 2020-01-05 05:33:08

问题


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.



来源:https://stackoverflow.com/questions/36090701/how-to-use-max-on-a-collection

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!