Cypher查询以获取具有数组的单个对象的节点和子节点

时间:2013-08-22 17:48:27

标签: neo4j cypher

我有这个json:

{
    "name":"david", //node:Person
    "TAKING":[ //link
        {"name":"math"}, //node:Subject
        {"name":"physics"} //node:Subject
    ],
    "FRIEND":[ //link
        {"name":"andres"}, //node:Person
        {"name":"luis"} //node:Person
    ]
}

我有这个查询从neo4j中提取它

start person=node(*) match person-[:FRIEND]->friend, person-[:TAKING]->subject where person.name="Andres" return person, collect(distinct friend), collect(distinct subject);

结果如下:

==> +------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
==> | person                                   | collect(distinct friend)                                                         | collect(distinct subject)                      |
==> +------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
==> | Node[1]{name:"Andres",title:"Developer"} | [Node[2]{name:"David",title:"Developer"},Node[3]{name:"Luis",title:"Developer"}] | [Node[5]{name:"math"},Node[6]{name:"physics"}] |
==> +------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+

我认为这部分查询可以更好:

person-[:FRIEND]->friend, person-[:TAKING]->subject

目标是避免返回部分中的distinc子句:

collect(distinct friend), collect(distinct subject)

我把它重写为:

subject<-[:TAKING]-person-[:FRIEND]->friend

但结果相同。

有没有更好的方法来进行此查询?有没有办法用cypher构建原始json?

1 个答案:

答案 0 :(得分:1)

尝试http://console.neo4j.org/?id=mlwmlt中演示的以下查询,以避免使用DISTINCT关键字:

START person=node(*) 
WHERE HAS (person.name) AND person.name='A' 
WITH person 
MATCH (subject)<-[:TAKING]-(person) 
WITH person, COLLECT(subject) AS subjects 
MATCH (person)-[:FRIEND]->(friend) 
RETURN person, subjects, COLLECT(friend)

但一般来说,你不应该使用node(*)。一个好主意是使用名称索引。