【问题标题】:neo4j cypher query in java traversal frameworkjava遍历框架中的neo4j密码查询
【发布时间】:2023-11-22 15:52:01
【问题描述】:

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

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 版。

【问题讨论】:

    标签: java neo4j cypher traversal


    【解决方案1】:

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

    数据

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

    【讨论】:

    • 感谢您的方法,它真的帮助了我。但我还必须在每个节点上设置计算的总和。解释一下:不仅要在根节点上设置属性成本,还要在例如值为 70 的 p2 等上设置属性成本 - 也许我会根据您的想法找到解决方案。
    • 在同一秒钟内我编写了相同的代码 - 非常感谢