2015-10-14 63 views
1

我有一個密碼查詢,其中總結了每個孩子的數量,並將這個總和設置爲父節點。在java遍歷框架中的neo4j密碼查詢

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。

回答

2

這是我對你的問題

辦法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; 
} 
+0

感謝您的方法,它是真正幫助我。但我也必須在每個節點上設置計算的總和。解釋:不僅要在根節點上設置物業成本,還要在例如值爲70等的p2上設置物業成本 - 也許我會根據您的想法找到解決方案。 –

+0

@ K.E。我更新了代碼。 – MicTech

+0

在同一秒我寫了相同的代碼 - 非常感謝你 –