java遍历框架中的neo4j cypher查询

时间:2015-10-14 12:16:04

标签: java neo4j cypher traversal

我有一个cypher查询,它总结了每个孩子的数量,并将这个总和设置为父节点。

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)

所以我的产品的结果是:

product1.costs = 42
product2.costs = 22

有人可以给我一个提示如何使用java中的neo4j遍历框架吗?

我正在使用neo4j 2.2.5和neo4j的核心api版本2.2.5。

1 个答案:

答案 0 :(得分:2)

以下是我提出问题的方法

数据

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)

代码

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;
}