1

I have a Spring Neo4j repository method getAvgVotesWeightForCriterion

@Query("MATCH (d:Decision)<-[:VOTED_FOR]-(v:Vote)-[:VOTED_ON]->(c:Criterion) WHERE id(d) = {0} AND id(c) = {1} RETURN avg(v.weight)")
double getAvgVotesWeightForCriterion(Decision decision, Criterion criterion);

and also I have another method calculateWeight completely written in Java. This method internally in loop uses getAvgVotesWeightForCriterion

public double calculateWeight(Decision decision, List<Criterion> criteria) {
    double weight = 0;

    for (Criterion criterion : criteria) {
        weight += getAvgVotesWeightForCriterion(decision, criterion);
    }

    return weight;
}

Is it possible to move logic inside calculateWeight method completely to Cypher query ? In order to get something like this:

@Query ....
double calculateWeight(Decision decision, List<Criterion> criteria)
alexanoid
  • 24,051
  • 54
  • 210
  • 410

1 Answers1

3

This should do what you want to do.

You group the avg - aggregation per criterion and then just sum the weights.

MATCH (d:Decision)<-[:VOTED_FOR]-(v:Vote)-[:VOTED_ON]->(c:Criterion) 
WHERE id(d) = {0} AND id(c) IN {1} 
WITH c, avg(v.weight) as weight
RETURN sum(weight)
Michael Hunger
  • 41,339
  • 3
  • 57
  • 80