Can I recursively evaluate a tree in neo4j cypher language?

妖精的绣舞 提交于 2019-12-23 19:53:24

问题


In my application, I have what is essentially the syntax tree of a mathematical expression as neo4j graph... a picture is probably helpful:

I'm wondering if it's possible to write a Cypher query that fully evaluates a tree like this for the top node, i.e.:

  • gets the average of the connected inputs for Node 1.2,
  • the max for 1.1.2
  • the average of 1.1.2 and 3 for Node 1.1
  • and finally returns the max of 1.2 and 1.1 as value for Node 1

The value is stored in the property status for the input nodes, in the max and avg nodes the value is not present and should be calculated.

Here's the whole thing in neo4j console: http://console.neo4j.org/?id=gopwjn

I have a feeling that it might be possible with some WITH and REDUCE and similar voodoo, but I can't piece it quite together.


回答1:


here is a flat solution that seems to do the trick. I tried something like FOREACH (n in range(0,2)....... but you cannot use match within a foreach :/ so here i update all avg nodes, then update all max nodes and then repeat cause the first pass would not populated child max nodes of avg.

i hope this st least points you in a helpful direction :)

MATCH (n1:AVG)-[]-(p1)
WITH AVG(p1.status) AS NEWSTATUS1, n1 AS ND1
MERGE (n1:AVG { name:ND1.name })
ON MATCH SET n1.status=NEWSTATUS1
with 1 as A
MATCH (n2:MAX)-[]-(p2)
WITH MAX(p2.status) AS NEWSTATUS2, n2 AS ND2
MERGE (n2:MAX { name:ND2.name })
ON MATCH SET n2.status=NEWSTATUS2
with 2 as B
MATCH (n3:AVG)-[]-(p3)
WITH AVG(p3.status) AS NEWSTATUS3, n3 AS ND3
MERGE (n3:AVG { name:ND3.name })
ON MATCH SET n3.status=NEWSTATUS3
with 3 as C
MATCH (n4:MAX)-[]-(p4)
WITH MAX(p4.status) AS NEWSTATUS4, n4 AS ND4
MERGE (n4:MAX { name:ND4.name })
ON MATCH SET n4.status=NEWSTATUS4



回答2:


I don't think there is a single Cypher query that can solve every mathematical expression representable using your graph model. This is because Cypher has no looping statements powerful enough to iteratively calculate subresults (in the correct order) for trees of arbitrary depth.

Even for trees of fixed depth, the Cypher query would be pretty complex.



来源:https://stackoverflow.com/questions/27849188/can-i-recursively-evaluate-a-tree-in-neo4j-cypher-language

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