Neo4j cypher查询:具有指定节点和关系属性的AllShortestPaths

时间:2018-03-16 13:06:48

标签: neo4j cypher graph-databases

我是neo4j的新手。

我创建了这个例子:

//         (Node2)
//         /     \
//   Rel2 /       \ Rel3
//       /         \
// (Node1) ------> (Node3)
//          Rel1
// 
// create nodes
CREATE
(n1:Node1{id:1,rights:["admin","user"]}),
(n2:Node2{id:2,rights:["admin","user"]}),
(n3:Node3{id:3,rights:["admin","user"]})
// create relationships
CREATE (n1)-[r1:Rel1{id:11,rights:["admin"]}]->(n3)
CREATE (n1)-[r2:Rel2{id:12,rights:["admin","user"]}]->(n2)
CREATE (n2)-[r3:Rel3{id:13,rights:["admin","user"]}]->(n3)
RETURN n1,n2,n3,r1,r2,r3

每个节点和关系都有一个属性数组,其中包含一些权限值。 我想创建一个查询,它给出了具有指定属性的两个节点之间的(最短)路径。 例如:

用户拥有权限'admin',路径应为:

(节点1) - [Rel1] - >(节点3)
(每个节点和关系在'rights'属性中都有'admin'字符串。)

如果用户拥有正确的“用户”,则路径应为:

(节点1) - [REL2] - (节点2) - [REL3] - (节点3)
(因为Rel1关系在'rights'属性中没有'user'字符串。)

起初我尝试了这个有效的查询:

WITH ["admin","otherRight"] AS usersRights
MATCH path=allShortestPaths((n1:Node1{id:1})-[*..4]-(n2:Node3{id:3})) 
WITH *, relationships(path) AS rels, nodes(path) as nodes
WHERE ANY (rel IN rels WHERE ANY(r IN rel.rights WHERE r IN usersRights))
AND ANY (node IN nodes WHERE ANY(r IN node.rights WHERE r IN usersRights))
RETURN path

然后我将'admin'替换为'user',但是这个查询不起作用(没有rusults):

WITH ["user","otherRight"] AS usersRights
MATCH ... // same as above
...
RETURN path

以下查询符合我需要的结果,但在这种情况下, 我必须进行多次查询才能获得深度为n的预期结果(最短路径)。

WITH ["user","otherRight"] AS usersRights
MATCH path=(n1:Node1{id:1})-[r1]-(n2)-[r2]-(n3:Node3{id:3}) 
WHERE ANY(r IN n1.rights WHERE r IN usersRights)
AND ANY(r IN r1.rights WHERE r IN usersRights)
AND ANY(r IN n2.rights WHERE r IN usersRights)
AND ANY(r IN r2.rights WHERE r IN usersRights)
AND ANY(r IN n3.rights WHERE r IN usersRights)
RETURN path

是否可以创建一个能够给我带来不良结果的密码查询?

感谢。

1 个答案:

答案 0 :(得分:0)

您的第一个查询有WITH子句分隔MATCHWHERE子句,这会阻止WHERE子句影响allshortestpath()函数的行为。因此,该函数只返回最短路径而不测试节点和关系。

试试这个,而不是:

WITH ["admin","otherRight"] AS usersRights
MATCH path=allShortestPaths((n1:Node1{id:1})-[*..4]-(n2:Node3{id:3})) 
WHERE
  ANY (rel IN relationships(path) WHERE ANY(r IN rel.rights WHERE r IN usersRights)) AND
  ANY (node IN nodes(path) WHERE ANY(r IN node.rights WHERE r IN usersRights))
RETURN path;