0
votes

In Neo4J I have the following problem:

Nodes are arranged in a tree-like or parent/child style structure. On the "leafs" or child nodes, every node has a set of nummerical attributes.

I need a Cypher query to calculate the average of each attribute and strore it in an attribute with the same name in the parent node.

Something like

MATCH (p:Parent)-[]->(c:Child) 
SET p.attrib1 = avg(c.attrib1)
SET p.attrib2 = avg(c.attrib2)

will do the job, BUT...

The amount of attributes in the child-nodes should be dynamic, I do not want to change the code when a Child-node comes up with an additional attribute name. As long as the property is a decimal, the code should adapt to this.

Is there a way to achieve this?

1
Do all Child nodes share the same set of numerical properties? And are there any Child properties that you do not want to average?cybersam
Some properties might not be present in every node, but there is no need to explicitly exclude any propery from averaging.Ale

1 Answers

1
votes

You can accomplish this with help from the APOC procedure library. You can almost do this in native Cypher, but you can't dynamically specify the name of the property to create but we can use apoc.create.setProperty to do this:

MATCH (parent:Parent)<-[]-(child:Child) 
WITH parent, child, keys(child) AS props
UNWIND props AS prop
WITH parent, prop, avg(child[prop]) AS mean
CALL apoc.create.setProperty(parent, prop, mean) YIELD node
RETURN *

There is a simple example in this Neo4j Console.