neo4j - 在 Neo4j Cypher 的 RETURN 语句中使用WITH语句之前的变量

标签 neo4j cypher

我从 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安装时附带的迷你电影图。

一切正常,它显示了所有与汤姆·克鲁斯合作电影的合作 Actor 以及他们合作了多少次但是当我想要时就会出现问题列出他们合作过的电影。将“movies”变量放在 RETURN 语句中会引发以下错误:

movies not defined (line 3, column 9)
"RETURN  movies, coactors.name, avg(TimesCoacted)"
         ^

有什么办法可以在一个查询中完成它吗?

最佳答案

尝试以下操作:

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在返回语句中。

编辑:在 OP 更新后添加了以下内容。

另一个例子。如果您想计算 Actor 在电影中合作的次数并列出电影标题。请尝试以下操作:

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 - 在 Neo4j Cypher 的 RETURN 语句中使用WITH语句之前的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27903842/

相关文章:

python - 在 BOLT neo4j-driver 中使用 python datetime 类型会引发错误。可用的解决方法?

ubuntu - 如何访问新的 neo4j ubuntu/ec2 安装?

Neo4j 密码 : how to change the type of a relationship

neo4j - 查询可以阻止 Neo4j 工作吗

java - Neo4j:使用参数时 REST API 速度较慢

Neo4j:如何删除与密码的特定关系?

neo4j - 动态地向 Neo4j 添加属性

java - "Unknown error"对所有关系进行密码查询

shell - 如何使用 Neo4j 3.1.4 执行 .cypher 文件(不通过 .zip 文件)

neo4j - Neo4j 中的密码查询返回 'undefined'