无法在密码查询Neo4j

时间:2016-01-12 21:21:41

标签: graph neo4j cypher

我有一些数据,如下所示:

(:Artist {id: 1, name: "Depeche Mode"})<-[:PLAYED_BY]-(:Song {id: 1, title: "Enjoy The Silence"})-[:PLAYED_BY]->(:Artist {id: 2, name: "Lacuna Coil"})

例如,我需要查询所有Song PLAYED_BY艺术家id 1和2。

我在考虑类似的事情:

MATCH (s:Song)-[:PLAYED_BY]->(a:Artist)
WHERE a.id IN [1, 2]
RETURN s

但是这个并不是我想要的:因为它就像OR,我想像AND一样使用它。

有什么建议吗?

EDIT1:Artist的数量应该是任意的。

EDIT2:我还需要使用全文索引运行此查询,如下所示:

START song=node:node_auto_index("title:*enjo*") 
MATCH ... 
RETURN ...

这首歌也由其他艺术家播放,例如Song 1Artist [1, 2, 3]播放。 当我查询[1,2]时,无论如何都应该返回它。

2 个答案:

答案 0 :(得分:2)

这适用于您的示例:

MATCH (a1:Artist)<-[:PLAYED_BY]-(s:Song)-[:PLAYED_BY]->(a2:Artist)
WHERE a1.id = 1 AND a2.id = 2
RETURN s

答案 1 :(得分:2)

所以你想找到由艺术家1和艺术家2演奏的歌曲吗?

这个查询怎么样:

MATCH (a1:Artist)<-[:PLAYED_BY]-(s:Song)-[:PLAYED_BY]->(a2:Artist)
WHERE a1.id = 1 AND a2.id = 2
RETURN s

修改

对于任意数量的艺术家:

WITH [1,2] AS ids
MATCH (a:Artist)<-[:PLAYED_BY]-(s:Song)
WITH collect(a.id) AS artistIds, ids,s
WHERE all(x IN artistIds WHERE x IN ids) AND all(x IN ids WHERE x IN artistIds)
RETURN s

收集播放该歌曲的所有艺术家的ID然后使用Cypher集合谓词函数all仅过滤所需的艺术家ID。

数组[1,2]可以像这样参数化:WITH {id_array} AS ids ...

修改

使用遗留索引进行模糊文本搜索应该可以使用此方法。只需将MATCH中未绑定的(s:Song)模式替换为由旧索引填充的绑定song变量:

START song=node:node_auto_index("title:*enjo*")
WITH [1,2] AS ids, song
MATCH (a:Artist)<-[:PLAYED_BY]-(song)
WITH collect(a.id) AS artistIds, ids, song
WHERE all(x IN artistIds WHERE x IN ids) AND all(x IN ids WHERE x IN artistIds)
RETURN s