neo4j:直到结束才遵循关系

时间:2018-06-28 21:23:43

标签: neo4j cypher

我试图用neo4j表示网络配置。 这是我到目前为止一直在使用的Cyper脚本:

 CREATE (router1:Router {name:'router1', defaultgw:'192.168.123.1'})
 CREATE (router2:Router {name:'router2', defaultgw:'172.31.39.1'})
 CREATE (gateway1:Gateway {name:'gateway1', ip:'192.168.123.1' })
 CREATE (network1:Network {name:'network1', cidr:'192.168.123.0/24'})
 CREATE (network2:Network {name:'network2', cidr:'10.23.47.0/24'})
 CREATE (network3:Network {name:'network3', cidr:'172.31.39.0/24'})
 CREATE (server10:Server {hostname:'server10', ip:'172.31.39.10'})
 CREATE (server1:Server {hostname:'server1', ip:'192.168.123.7'})
 CREATE (server2:Server {hostname:'server2', ip:'192.168.123.9'})
 CREATE (server3:Server {hostname:'server3', ip:'192.168.123.10', ip:'10.23.47.7'})
 CREATE (server4:Server {hostname:'server4', ip:'192.168.123.13'})
 CREATE (server5:Server {hostname:'server5', ip:'192.168.123.23'})
 CREATE (server6:Server {hostname:'server6', ip:'192.168.123.15', ip:'10.23.47.17'})
 CREATE
   (gateway1)-[:CONNECTED_TO {}]->(router1),
   (router2)-[:CONNECTED_TO {}]->(network3),
   (router1)-[:CONNECTED_TO {}]->(network1),
   (router1)-[:CONNECTED_TO {}]->(network2),
   (router1)-[:CONNECTED_TO {}]->(router2),
   (network1)-[:CONNECTED_TO {}]->(server1),
   (network1)-[:CONNECTED_TO {}]->(server2),
   (network1)-[:CONNECTED_TO {}]->(server3),
   (network2)-[:CONNECTED_TO {}]->(server3),
   (network1)-[:CONNECTED_TO {}]->(server4),
   (network1)-[:CONNECTED_TO {}]->(server5),
   (network1)-[:CONNECTED_TO {}]->(server6),
   (network2)-[:CONNECTED_TO {}]->(server6),
   (network3)-[:CONNECTED_TO {}]->(server10)
 WITH gateway1 AS g
   MATCH (g)-[:CONNECTED_TO]->(r)-[:CONNECTED_TO]->(n)-[:CONNECTED_TO]->(s) RETURN g,r,n,s
 ;

但是,MATCH情况直到第三网络的服务器都不允许渲染!

Servers related to network3 are not getting represented

我的请求出了什么问题,如何改进? 还有另一种方法可以发出此请求,即表示与每个有关联或没有关联的每个节点,而不是与单个关联的节点(此处为{{1} })起源?

非常感谢!

2 个答案:

答案 0 :(得分:3)

如果您要查询以将子树中的所有节点都植根于gateway1,则您的MATCH不起作用,因为它仅匹配具有3个CONNECTED_TO关系的路径。到server10的路径需要4跳。

要返回具有以CONNECTED_TO为根的1个或多个gateway1关系的完整路径,这应该可行(WHERE子句过滤掉x是非叶子的路径节点):

...
WITH gateway1 AS g
MATCH p=(g)-[:CONNECTED_TO*]->(x)
WHERE NOT (x)-[:CONNECTED_TO]->()
RETURN p;

并且,如果您还希望在子图中没有其他节点时仅返回根网关节点,则可以将*更改为*0..

...
WITH gateway1 AS g
MATCH p=(g)-[:CONNECTED_TO*0..]->(x)
WHERE NOT (x)-[:CONNECTED_TO]->()
RETURN p;

答案 1 :(得分:1)

正如@cybersam所说,网络3中的服务器相距四跳,因为它们需要遍历到路由器。

如果您知道您正在寻找3个到4个跳:Server个节点,则可以使用他的解决方案。

...
WITH gateway1 AS g
MATCH p=(g)-[:CONNECTED_TO*3..4]->(:Server)
RETURN p