将两个密码查询与UNION结合使用的问题

时间:2014-04-22 11:26:54

标签: neo4j cypher

console.neo4j.org

上组合两个密码查询时遇到了以下问题

查询:

MATCH (p1:Crew)-[r_pfq]->(fq:Crew)
WHERE fq.name IN ["Neo", "Morpheus"]
RETURN distinct(p1) AS person, count(r_pfq) AS friend_score, collect(fq.name) AS friends
ORDER BY friend_score DESC
LIMIT 10

工作正常,

MATCH (f:Crew)<-[r_fqf]-(fq:Crew)
WHERE fq.name IN ["Neo", "Morpheus"]
WITH distinct(f), count(r_fqf) AS weight
ORDER BY weight DESC
LIMIT 10
MATCH f<--(p:Crew)
RETURN distinct(p) AS person, sum(weight) AS friend_score, collect(f.name) AS friends
ORDER BY friend_score DESC
LIMIT 10

现在,当我尝试使用UNION命令组合查询结果时,即

MATCH (p1:Crew)-[r_pfq]->(fq:Crew)
WHERE fq.name IN ["Neo", "Morpheus"]
RETURN distinct(p1) AS person, count(r_pfq) AS friend_score, collect(fq.name) AS friends
ORDER BY friend_score DESC
LIMIT 10
UNION
MATCH (f:Crew)<-[r_fqf]-(fq:Crew)
WHERE fq.name IN ["Neo", "Morpheus"]
WITH distinct(f), count(r_fqf) AS weight
ORDER BY weight DESC
LIMIT 10
MATCH f<--(p:Crew)
RETURN distinct(p) AS person, sum(weight) AS friend_score, collect(f.name) AS friends
ORDER BY friend_score DESC
LIMIT 10

我收到错误

Error: org.neo4j.graphdb.NotFoundException: Unknown identifier `weight`.

任何人都可以向我解释为什么这些查询结果无法合并以及如何正确执行此操作?为什么在单独运行两个查询但在UNION组合查询中未知时知道标识符?

1 个答案:

答案 0 :(得分:1)

修改

以下更简单的查询基本相同,只是UNION中的第二个查询 ORDER BY weight。这是因为我们已经按派生的friend_score排序,所以它似乎是多余的。此外,为了使变量包含在ORDER BY子句中,它必须在RETURN子句中 - 但UNION中的第一个查询没有weight变量,这会违反要求对于合法的UNION声明。

此外,第二个查询中还有第二个WITH子句,因为您必须在 RETURN子句之前定义ORDER BY子句中使用的变量(如friend_score! / p>

MATCH (p1:Crew)-[r_pfq]->(fq:Crew)
WHERE fq.name IN ["Neo", "Morpheus"]
RETURN DISTINCT (p1) AS person, count(r_pfq) AS friend_score, collect(fq.name) AS friends
ORDER BY friend_score DESC 
LIMIT 10
UNION
MATCH (p:Crew)-->(f:Crew)<-[r_fqf]-(fq:Crew)
WHERE fq.name IN ["Neo", "Morpheus"]
WITH f, count(r_fqf) AS weight, p
WITH f, sum(weight) AS friend_score, p
RETURN DISTINCT (p) AS person, friend_score, collect(DISTINCT (f).name) AS friends
ORDER BY friend_score DESC 
LIMIT 10