作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个密码查询,它总结了每个子节点的数量,并将这个总和设置为父节点。
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/
我是一名优秀的程序员,十分优秀!