如何避免重复返回不同的节点,并使用neo4j来建立关系 [英] How to avoid duplications return distinct nodes and the relation ship using neo4j
问题描述
我想返回给定的node-id相关节点及其关系道具
I would like to return for a given node-id related nodes and their relationships props
例如:
->
使用属性时间戳定义双向关系
For example:
->
defines a bi direction relationship with property timestamp
1234->777
777->1234
1234->999
999->1234
1234->888
888->1234
1234,777,888,999是节点ID
1234,777,888,999 are node-ids
当我执行此操作时:
final PreparedStatement ps = conn.prepareStatement("start a = node(1234) match (a)-[k:nearby*]->(b) where a<>b return DISTINCT b, k");
ResultSet rs = ps.executeQuery();
while (rs.next()) {
Map result = (Map<String, Object>) rs.getObject("b");
System.out.println(result.toString());
}
} catch (SQLException e) {
e.printStackTrace();
logger.error("Error returning userId=" + userIdInput, e);
}
return null;
}
我得到:
{userId=777}
{userId=999}
{userId=888}
{userId=888}
{userId=999}
{userId=999}
{userId=777}
{userId=888}
{userId=888}
{userId=777}
{userId=888}
{userId=777}
{userId=999}
{userId=999}
{userId=777}
- 我如何仅获得不同的结果(777,888,999)
- 如何检索1234与dest节点的关系道具?我希望获得在每个关系上定义的时间戳道具
谢谢你, 射线.
推荐答案
我不确定您使用的是哪种语言,因此我将重点介绍Cypher.首先,我将在ID(a)
上的WHERE
替换为MATCH
的START
查询:
I'm not sure what language you're using so I'll focus on the Cypher. Firstly I would replace the START
query with a MATCH
with a WHERE
on ID(a)
:
MATCH (a)-[k:nearby*]->(b)
WHERE ID(a) = 1234 AND a<>b
RETURN DISTINCT b, k
第二,我很确定您不需要a<>b
,因为Cypher路径不会在相同的节点上循环:
Secondly I'm pretty sure you don't need the a<>b
because Cypher paths won't loop back on the same nodes:
MATCH (a)-[k:nearby*]->(b)
WHERE ID(a) = 1234
RETURN DISTINCT b, k
最后,对于您的问题,我怀疑您重复的原因是因为您有多个关系.如果是这样,您可以返回结果节点和关系数组,如下所示:
Lastly, and to your question, I suspect the reason that you're getting duplicates is because you have multiple relationships. If so you can return the result node and an array of the relationships like so:
MATCH (a)-[k:nearby*]->(b)
WHERE ID(a) = 1234
RETURN collect(b), k
那应该返回您的节点/关系对象(两个都有属性).根据您的语言/图书馆,您可能会获得地图,或者可能会得到包装数据的对象
That should return you node/relationship objects (with properties on both). Depending on your language/library you might get Maps or you might get objects wrapping the data
如果您的库没有为您返回关系的开始/结束节点,则可以执行以下操作:
If your library doesn't return the start/end nodes for relationships for you, you can do something like this:
MATCH (a)-[k:nearby*]->(b)
WHERE ID(a) = 1234
RETURN collect({rel: b, startnode: startnode(b), endnode: endnode(b)}), k
希望有帮助!
这篇关于如何避免重复返回不同的节点,并使用neo4j来建立关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!