我从Neo4j(v2.1.5)开始,我遇到了以下Cypher查询的问题:
MATCH (actor:Person{name:"Tom Cruise"})-[role:ACTED_IN]->(movies)<-[r:ACTED_IN]-(coactors)
WITH coactors, count(coactors) as TimesCoacted
RETURN coactors.name, avg(TimesCoacted)
ORDER BY avg(TimesCoacted) DESC
它基于Neo4j安装附带的迷你电影图。
一切正常,它显示所有 coactors 与汤姆克鲁斯合作拍摄电影和他们共同合作的次数,但问题出现在我想要的时候列出他们合作的电影。在RETURN语句中放置'movies'变量会引发以下错误:
movies not defined (line 3, column 9)
"RETURN movies, coactors.name, avg(TimesCoacted)"
^
有什么办法可以在一个查询中完成吗?
答案 0 :(得分:2)
尝试以下方法:
MATCH
(actor:Person{name:"Tom Cruise"})-[role:ACTED_IN]->(movies)<-[r:ACTED_IN]-(coactors)
WITH
coactors,
count(coactors) as TimesCoacted,
movies // You have declare "movies" here in order to use it later in the query
RETURN
movies,
coactors.name,
avg(TimesCoacted)
ORDER BY
avg(TimesCoacted) DESC
您在WITH
语句中定义的内容是唯一可用于进一步处理的内容。在原始问题中,movies
未进入下一部分(它不属于WITH
),因此movies
无法在return语句中使用。
修改:在OP更新后,添加了以下内容。
另一个例子。如果您希望计算演员在电影中演绎的次数,并列出电影片名。请尝试以下方法:
MATCH
(actor:Person {name:"Tom Cruise"})-[:ACTED_IN]->(movie)<-[:ACTED_IN]-(coactor:Person)
WITH
actor,
coactor,
collect (distinct movie.title) as movieTitles
RETURN
actor.name as actorName,
coactor.name as coactorName,
movieTitles,
size(movieTitles) as numberOfMovies
答案 1 :(得分:0)
MATCH
(actor:Person{name:"Tom Cruise"})-[role:ACTED_IN]->(movies)<-[r:ACTED_IN]-(coactors)
WITH
coactors,
count(coactors) as TimesCoacted,
collect(DISTINCT movies.title) as movies // <=- this line was crucial!
RETURN
movies,
coactors.name,
avg(TimesCoacted)
ORDER BY
avg(TimesCoacted) DESC