K.E.
K.E.

Reputation: 838

neo4j cypher query in java traversal framework

I have a cypher query which sum up the amount of every child and sets this sum to the parent node.

MATCH (n:product)-[:COSTS*0..]->(child) WITH n,  sum(child.amount) as sum SET n.costs=sum;
product1(amount:20) -[:COSTS]-> product2(amount:10)
product2 -[:COSTS]-> product3(amount:5)
product2 -[:COSTS]-> product4(amount:7)

So the results for my products are:

product1.costs = 42
product2.costs = 22

Can someone give me a hint how to do that with the neo4j traversal framework in java?

I am using neo4j version 2.2.5 and the version 2.2.5 of the core api for neo4j.

Upvotes: 1

Views: 99

Answers (1)

MicTech
MicTech

Reputation: 45003

Here is my approach for your questions

DATA

CREATE (p1:Product {id: 1, amount: 30}),
       (p2:Product {id: 2, amount: 20}),
       (p3:Product {id: 3, amount: 10}),
       (p4:Product {id: 4, amount: 40}),
       (p1)-[:COSTS]->(p2),
       (p2)-[:COSTS]->(p3),
       (p2)-[:COSTS]->(p4)

Code

try (Transaction tx = getDatabase().beginTx()) {
    GraphDatabaseService database = getDatabase();

    Node rootProduct = database.findNode(DynamicLabel.label("Product"), "id", 1);

    int sum = getChildrenSum(rootProduct);

    rootProduct.setProperty("costs", sum);

    tx.success();
}

public int getChildrenSum(Node product) {
    int sum = 0;

    final DynamicRelationshipType relationshipType = DynamicRelationshipType.withName("COSTS");
    final Direction direction = Direction.OUTGOING;

    if (product.hasRelationship(relationshipType, direction)) {
        for (Relationship costs : product.getRelationships(relationshipType, direction)) {
            final Node child = costs.getEndNode();
            final String propertyName = "amount";

            if (child.hasProperty(propertyName)) {
                sum += Integer.parseInt(child.getProperty(propertyName).toString());
            }
            childrenSum += getChildrenSum(child);

            sum += childrenSum;

            child.setProperty("costs", childrenSum);
        }
    }

    return sum;
}

Upvotes: 2

Related Questions