java 遍历框架中的 neo4j 密码查询

neo4j cypher query in java traversal framework

我有一个密码查询,它总结了每个 child 的数量并将这个总和设置到 parent 节点。

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 和核心版本 2.2.5 api for neo4j。

这是我对您问题的处理方法

数据

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