【问题标题】:neo4j cypher interleave nodes and relationshipsneo4j cypher 交错节点和关系
【发布时间】:2013-12-19 14:12:09
【问题描述】:

如何返回交错的节点和关系?使用Matrix电影数据库查询

    MATCH p=(a1:Actor {name:"Keanu Reeves"})-[r *0..5]-(a2:Actor {name: "Carrie-Anne Moss"})
    return [n in nodes(p)|coalesce(n.title,n.name)], [rel in relationships(p)|type(rel)]

返回两列,一列包含节点,一列包含关系

    Keanu Reeves, The Matrix, Laurence Fishburne, The Matrix Reloaded, Carrie-Anne Moss | ACTS_IN, ACTS_IN, ACTS_IN, ACTS_IN
    ...

但我想要

    Keanu Reeves, ACTS_IN, The Matrix, ACTS_IN, Laurence Fishburne, ACTS_IN, The Matrix Reloaded, ACTS_IN, Carrie-Anne Moss
    ...

【问题讨论】:

    标签: neo4j cypher


    【解决方案1】:

    这曾经更容易,但他们打破了 2.0-RC1 中的“简单方法”,因为他们在 Cypher 中不再使用路径而不是集合。

    match p= shortestPath((kevin)-[:ACTED_IN*]-(charlize))
    where kevin.name="Kevin Bacon"
    and charlize.name="Charlize Theron"
    with nodes(p) as ns, rels(p) as rs, range(0,length(nodes(p))+length(rels(p))-1) as idx
    return [i in idx | case i % 2 = 0 when true then coalesce((ns[i/2]).name, (ns[i/2]).title) else type(rs[i/2]) end];
    

    以前的方法是:

    match p= shortestPath((kevin)-[:ACTED_IN*]-(charlize))
    where kevin.name="Kevin Bacon"
    and charlize.name="Charlize Theron"
    return [x in p | coalesce(x.name,x.title, type(x))]
    

    更改的好处是路径现在更安全,尽管我需要相当多的时间才能说服我同意它们。这种查询的真正用例非常少。

    【讨论】:

    • 谢谢。我不知道它已经改变了(我只在 v2 中尝试过),但第二个解决方案起初对我来说似乎很明显(并且没有工作) p 将是一个集合。
    【解决方案2】:

    这是另一个解决方案:

    MATCH (kevin:Person {name="Kevin Bacon"}), (charlize:Person {name:"Charlize Theron"})
    MATCH p= shortestPath( (kevin)-[:ACTED_IN*]-(charlize) )
    
    WITH nodes(p)+rels(p) AS c, length(p) AS l 
    RETURN reduce(r=[], x IN range(0,l) | r + (c[x]).name + type(c[l+x+1]))
    

    它将路径重新聚合到一个集合中,然后仅使用路径长度作为偏移量来访问后半部分。

    Reduce 用于“展平”集合,如果您不需要,这也可以。

    MATCH (kevin:Person {name="Kevin Bacon"}), (charlize:Person {name:"Charlize Theron"})
    MATCH p= shortestPath( (kevin)-[:ACTED_IN*]-(charlize) )
    
    WITH nodes(p)+rels(p) AS c, length(p) AS l 
    RETURN [x IN range(0,l) | [c[x]).name + type(c[l+x+1])]]
    

    【讨论】:

    • 非常好。学习了 Clojure,reduce 函数是我的第二个猜测,但我不知道如何组合节点和关系集合。现在我对 Neo4j 的工作原理有了更多了解。
    • 为什么需要写 (c[x]).name 而为什么 c[x].name 不起作用?我在手册中没有找到这样的例子(搜索“]”)。在文本版本中)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多