【问题标题】:Use vars from before WITH statement in RETURN statement in Neo4j Cypher在 Neo4j Cypher 的 RETURN 语句中使用 WITH 语句之前的 vars
【发布时间】:2015-03-10 07:53:22
【问题描述】:

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

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

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

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

【问题讨论】:

    标签: neo4j cypher


    【解决方案1】:

    尝试以下方法:

    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-statement 中定义的内容是唯一可用于进一步处理的内容。在最初的问题中,movies 没有被带到下一部分(它不是WITH 的一部分),因此movies 不能在返回语句中使用。

    编辑:从 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
    

    【讨论】:

    • 如果你想跨电影聚合使用WITH collect(distinct movie.title) as movies
    • 我以前试过这个,但这不是我想要的。此查询不汇总演员合作的时间。在此示例中,Cuba Googing Jr. 出现了两次: 电影:A Few Good Men 演员:Cuba Gooding Jr. timescoacted 1 电影:Jerry Maguire 演员:Cuba Gooding Jr. timescoacted 1
    • @SrdjanMarjanovic - 那么,你在找什么?
    • @wassgren 更像是:演员:Cuba Gooding jr.演出时间:2 部电影:几个好男人,杰瑞·马奎尔
    【解决方案2】:
    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-05-05
      • 1970-01-01
      • 2013-10-02
      • 1970-01-01
      • 2016-04-16
      • 2014-06-06
      • 2014-05-21
      • 1970-01-01
      相关资源
      最近更新 更多