Ale
Ale

Reputation: 247

Neo4J Cypher calculate average across multiple properties

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?

Upvotes: 0

Views: 908

Answers (1)

William Lyon
William Lyon

Reputation: 8546

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.

Upvotes: 1

Related Questions