匹配cypher shortestPath路径中节点的属性

时间:2016-01-20 17:12:21

标签: neo4j cypher graph-databases

为简单起见,假设我有一个这样的图形(以演员/电影为例):

节点:

Actor(id:1)
Actor(id:2)
Actor(id:3)
Movie(id:4,rating:'PG-13')
Movie(id:5,rating:'PG-13')

关系:

Actor(id:1) APPEARS_IN Movie(id:4)
Actor(id:2) APPEARS_IN Movie(id:4)
Actor(id:2) APPEARS_IN Movie(id:5)
Actor(id:3) APPEARS_IN Movie(id:5)

Cypher创建示例图:

create (a1:Actor {id: 1, name: 'Actor 1'})
create (a2:Actor {id: 2, name: 'Actor 2'})
create (a3:Actor {id: 3, name: 'Actor 3'})
create (m1:Movie {id: 4, rating:'PG-13', name: 'Movie 1' } )
create (m2:Movie {id: 5, rating:'PG-13', name: 'Movie 2' } )
create (a1)-[:APPEARS_IN]->(m1)
create (a2)-[:APPEARS_IN]->(m1)
create (a2)-[:APPEARS_IN]->(m2)
create (a3)-[:APPEARS_IN]->(m2)
return *

现在我们想要找到Actor(id:1)Actor(id:3)之间的最短路径。这很容易,我们可能会尝试一个密码查询,如:

MATCH p=shortestPath((a:Actor { id: 1 })-[:APPEARS_IN*0..14]-(b:Actor { id: 3 })) RETURN NODES(p)

我们会得到一个结果。

这是我的问题所在如何对两者之间的节点(特别是电影节点)提出要求,仅将rating:'R'作为其路径的一部分?

1 个答案:

答案 0 :(得分:1)

此查询仅返回两个演员之间最短路径的节点,其中所有电影均为 R 评级。

它过滤掉Movie节点,然后检查以确保集合中每个电影节点的评级为 R

MATCH p=shortestPath((a:Actor { id: 1 })-[:APPEARS_IN*0..14]-(b:Actor { id: 3 })) 
WHERE all ( movie in filter( m in nodes(p) where 'Movie' in labels(m)) where movie.rating = 'R')
RETURN nodes(p)