這是我對你的問題
辦法DATA
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上設置物業成本 - 也許我會根據您的想法找到解決方案。 –
@ K.E。我更新了代碼。 – MicTech
在同一秒我寫了相同的代碼 - 非常感謝你 –