gpt4 book ai didi

java - java遍历框架中的neo4j cypher查询

转载 作者:行者123 更新时间:2023-11-30 03:13:41 25 4
gpt4 key购买 nike

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

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。

最佳答案

这是我回答您问题的方法

数据

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

关于java - java遍历框架中的neo4j cypher查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33125049/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com