Can I recursively evaluate a tree in neo4j cypher language?

In my application, I have what is essentially a math expression syntax tree as neo4j graph ... the image is probably useful:

expression tree

I'm wondering if it is 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,
  • max for 1.1.2
  • mean 1.1.2 and 3 for Node 1.1
  • and finally returns max 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 there is no value and must be calculated.

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

I have a feeling that this is possible with some WITH and REDUCE and voodoo-like, but I can't quite put it together.

+3


source to share


2 answers


here is a flat solution that seems to do the trick. I tried something like FOREACH (n in the range (0,2) ....... but you cannot use match inside foreach: / so here I update all avg nodes and then update all max nodes and then I repeat, calling the first pass did not populate avg's child max nodes.

I hope this at least points to a useful 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

      

+3


source


I don't think there is one Cypher query that can solve every mathematical expression representable with your graph model. This is because Cypher does not have loop operators powerful enough to iteratively compute sub-selections (in the correct order) for trees of arbitrary depth.



Even for trees with a fixed depth, the Cypher query will be quite complex.

+2


source







All Articles