如何避免Neo4j密码查询中的循环 [英] How to avoid cycle in neo4j cypher queries

查看:86
本文介绍了如何避免Neo4j密码查询中的循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个friend-friend数据模型,该模型基于一个朋友定义另一个朋友的方式在任何两个朋友节点之间具有两种关系。
例如,用户 A可以将用户 B定义为朋友,而 B可以将用户 A定义为好友。
问题是,当我尝试获取用户 A的第三级关系时,它将返回用户 B,而实际结果应仅为 D。

I have friend-friend data model which has two relationships between any two friend nodes based on how one friend defines the other friend. For example, User "A" can define user "B" as 'FRIEND' and "B" can define "A" as 'BUDDY'. The problems is, when I try to get the 3rd degree of relationship of user "A", it returns user "B", where as the actual result should be "D" only.

MATCH(a:Users {first_name : "A"}) -[:BUDDY|FRIEND*3] -> (b)
RETURN a,b

OR

MATCH (a)-[]-(b)-[]-(c)-[]-(d)
WHERE a.first_name="A" 
RETURN a,d

推荐答案

或者,您可以执行以下操作:

Alternatively, you can do this:

MATCH p=((a:Users {first_name : "A"})-[:BUDDY|FRIEND*3]->(b))
WITH DISTINCT a, b, nodes(p) as nodes
UNWIND nodes AS node
WITH a, b, nodes, COLLECT(DISTINCT node) as distinct_nodes
WITH a, b WHERE SIZE(nodes)=SIZE(distinct_nodes)
RETURN a, b

或通过APOC调用更轻松:

or a bit easier with an APOC call:

MATCH p=((a:Users {first_name : "A"})-[:BUDDY|FRIEND*3]->(b))
WITH DISTINCT a, b WHERE SIZE(nodes(p)) = SIZE(apoc.coll.toSet(nodes(p)))
RETURN a, b

这篇关于如何避免Neo4j密码查询中的循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆