结合不同的Neo4j Cypher查询

时间:2015-02-05 23:56:48

标签: neo4j cypher

我目前正在使用以下三个查询从数据库中提取一些信息。

 MATCH (u:User { id: "1" }), (x:Label)  
 WHERE (u)-[:SEES]->(x) 
RETURN collect(x) as labels

 MATCH (u:User { id: "1" }), (x:Label)  
 WHERE (u)-[:SEES]->(x)    
   AND NOT((x)-[:CLASSIFIES]->())    
   AND NOT(()-[:CLASSIFIES]->(x)) 
RETURN collect(x) as uniquelabels

 MATCH (u:User { id: "1" }), p=(a:Label)-[:CLASSIFIES*]->(b:Label)  
 WHERE ALL(n IN nodes(path) WHERE ((u)-[:SEES]->(n)))
   AND NOT(()-[:CLASSIFIES]->(a))    
   AND NOT((b)-[:CLASSIFIES]->())   
  WITH collect(extract(n IN nodes(p) | n.id)) as paths 
RETURN distinct paths

将这些查询合并为一个的正确方法是什么?

1 个答案:

答案 0 :(得分:1)

首先,我建议不要在MATCH子句中使用WHERE语法(ASCII艺术箭头语法),除非您正在执行NOT()

我认为你应该可以像这样使用UNION

 MATCH (u:User { id: "1" })-[:SEES]->(x:Label)  
RETURN extract(n IN collect(distinct x) | n.id) as labels
   UNION
 MATCH (x:Label)  
 WHERE NOT((x)-[:CLASSIFIES]-())    
RETURN extract(n IN collect(distinct x) | n.id) as uniquelabels
   UNION
 MATCH (u:User { id: "1" }), p=(a:Label)-[:CLASSIFIES*]->(b:Label)  
 WHERE ALL(n IN nodes(path) WHERE ((u)-[:SEES]->(n)))
   AND NOT(()-[:CLASSIFIES]->(a))    
   AND NOT((b)-[:CLASSIFIES]->())   
 RETURN DISTINCT collect(extract(n IN nodes(p) | n.id))

可能有一种更优雅的方式,但是,我没有仔细查看查询