问题描述
我从Neo4j(v2.1.5)开始,并且以下Cypher查询出现问题:
I'm starting with Neo4j (v2.1.5) and I'm having an issue with the following Cypher query:
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安装随附的迷你电影图.
It is based on the mini movie graph which comes with Neo4j installation.
一切正常,它显示了与汤姆·克鲁斯(Tom Cruise)在电影中合作的所有角色和他们一起合作了多少次,但是问题出在我想要的时候列出他们合作过的电影.将'movies'变量放置在RETURN语句中会引发以下错误:
Everything works fine, it shows all coactors which coacted in movies with Tom Cruise and how many times they coacted together, but the problem occurs when I want to list in which movies they coacted. Placing 'movies' variable in RETURN statement is throwing the following error:
movies not defined (line 3, column 9)
"RETURN movies, coactors.name, avg(TimesCoacted)"
^
有什么办法可以在一个查询中做到吗?
Is there any way I can do it in one query?
推荐答案
尝试以下操作:
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语句中使用.
What you define in the WITH
-statement is the only thing that is available for further processing. In the original question the movies
were not carried on to the next section (it was not part of WITH
) and therefore movies
could not be used in the return statement.
编辑:从OP更新后,添加了以下内容.
After updates from the OP the following was added.
另一个例子.如果您希望计算演员在电影中合作的次数,并列出电影标题.请尝试以下操作:
Another example. If you wish to count the number of times the actors have coacted in a movie and list the movie-titles as well. Try the following:
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
这篇关于在Neo4j Cypher的RETURN语句中的WITH语句之前使用vars的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!