查询树以避免冗余

时间:2019-01-01 21:48:50

标签: neo4j tree cypher

我已经建立了一个示例树:

  CREATE (c1:treeCategory {name:"root", catID:1})
  CREATE (c2:treeCategory {name:"Maschinen", catID:2})      
  CREATE (c3:treeCategory {name:"Siebe", catID:3}) 
  CREATE (c4:treeCategory {name:"Zubehör", catID:4})       
  CREATE (c5:treeCategory {name:"SUPERTAUT", catID:5}) 
  CREATE (c6:treeCategory {name:"Fusion", catID:6}) 
  CREATE (c7:treeCategory {name:"Motor", catID:7}) 
  CREATE (c8:treeCategory {name:"Rahmen", catID:8}) 
  CREATE (c9:treeCategory {name:"SonoWave", catID:9})       
  CREATE (c10:treeCategory {name:"Scalper", catID:10})       
  CREATE (c11:treeCategory {name:"Rundsieb", catID:11})               
  CREATE (c12:treeCategory {name:"Dom", catID:12})  
  CREATE (c13:treeCategory {name:"FlowThru", catID:13})  
  CREATE (c2) -[:IS_SUBCATEGORY_OF]-> (c1)
  CREATE (c3) -[:IS_SUBCATEGORY_OF]-> (c1)      
  CREATE (c4) -[:IS_SUBCATEGORY_OF]-> (c1)      
  CREATE (c5) -[:IS_SUBCATEGORY_OF]-> (c3)      
  CREATE (c6) -[:IS_SUBCATEGORY_OF]-> (c3)
  CREATE (c7) -[:IS_SUBCATEGORY_OF]-> (c4)      
  CREATE (c8) -[:IS_SUBCATEGORY_OF]-> (c2)      
  CREATE (c9) -[:IS_SUBCATEGORY_OF]-> (c4)      
  CREATE (c10) -[:IS_SUBCATEGORY_OF]-> (c2)      
  CREATE (c11) -[:IS_SUBCATEGORY_OF]-> (c2)
  CREATE (c12) -[:IS_SUBCATEGORY_OF]-> (c8)
  CREATE (c13) -[:IS_SUBCATEGORY_OF]-> (c8)

为了用PHP构建树,我需要阅读图形并将其放入数组中。数组的结构应类似于

enter image description here

所以我想出一个查询:

MATCH p=(a:treeCategory)<-[:IS_SUBCATEGORY_OF*1..]-() 
WITH nodes(p) as nodes
RETURN nodes[size(nodes)-2] as Parent, 
       nodes[size(nodes)-1] as Child;

不幸的是,我得到的大多数数据对都是冗余的。该表的第一列可能具有多余的名称,例如Maschinen有几个子节点。但是第二列应该每个节点只有一次,因此没有catID会出现两次或更多次。有更好的方法吗?

1 个答案:

答案 0 :(得分:0)

我认为您不需要在这里使用可变长度的模式,只要将其匹配到一对父母和孩子,就足够了。

Dispose()