简体   繁体   English

根据两个不同节点之间的关系查询节点

[英]Querying nodes based on relationships between two different nodes

I have a graph with two different types of nodes A and B connected by a relationship rel.我有一个图表,其中有两种不同类型的节点 A 和 B 通过关系 rel 连接。 It exists such that there may be multiple nodes of A connected to one of B. My exact problem is this, suppose I have 2 nodes a1, a2 of type A connected to b1 via the relationship rel.它的存在使得 A 的多个节点可能连接到 B 之一。我的确切问题是,假设我有 2 个 A 类型的节点 a1、a2 通过关系 rel 连接到 b1。 I have node a3 of type A related to node b2.我有与节点 b2 相关的类型 A 的节点 a3。 I want to find a node b3 which contains a1, a2 and a3 and then form a relationship between b3 and b2, b1 if they fulfill a property(b3.prop/b2.prop>x & b3.prop/b1.prop>x).我想找到一个包含 a1、a2 和 a3 的节点 b3,然后在 b3 和 b2、b1 之间建立关系,如果它们满足一个属性(b3.prop/b2.prop>x & b3.prop/b1.prop>x )。 Is it possible to write a query in cypher that handles multiple relationships like this?是否可以在 cypher 中编写一个查询来处理这样的多个关系?

This may work for your scenario:这可能适用于您的场景:

MATCH (b1:B), (b2:B)
WHERE b1.id = 123 AND b2.id = 456
MATCH (a1:A)-[:rel]->(b1)
MATCH (a1)-[:rel]->(y1:B)
WHERE y1 <> b1 AND y1 <> b2
WITH b2, COLLECT(DISTINCT a1) AS a1s, COLLECT(DISTINCT y1) AS otherBs
WITH b2, [b IN otherBs WHERE ALL(a IN a1s WHERE (a)-[:rel]->(b))] AS candidates
WHERE SIZE(candidates) > 0
MATCH (a2:A)-[:rel]->(b2)
WITH candidates, COLLECT(a2) AS a2s
UNWIND [c IN candidates WHERE ALL(a IN a2s WHERE (a)-[:rel]->(c))] AS b3
RETURN b3

This query assumes the rel relationship is directed from A to B , and it will only return a result if there are any appropriate b3 nodes.此查询假定rel关系从A指向B ,并且仅当存在任何适当的b3节点时才会返回结果。 It first creates a list of all the possible B candidates related to the A nodes related to b1 .它首先创建与b1相关的A节点相关的所有可能B candidates的列表。 Then it whittles down the candidates list, keeping only the B nodes that are also related to the A nodes related to b2 .然后它会缩减candidates列表,只保留与b2相关的A节点的B节点。

There are many nuances in this query.此查询中有许多细微差别。 For example, this snippet would abort the query if any A node with a rel relationship to b1 does not also have a rel relationship to some other B node (that is not the same as b1 and b2 ):例如,如果与b1rel关系的任何A节点与其他B节点(与b1b2不同)不具有rel关系,则此代码段将中止查询:

MATCH (a1)-[:rel]->(b1)
MATCH (a1)-[:rel]->(y1:B)
WHERE y1 <> b1 AND y1 <> b2

Whereas the following refactoring of the above snippet would only abort the query if all A nodes with a rel relationship to b1 do not also have a rel relationship to some other B node (that is not the same as b1 and b2 ):然而,如果所有b1rel关系的A节点也不与其他某个B节点有rel关系(与b1b2不同),则对上述代码段的以下重构只会中止查询:

MATCH (y1:B)<-[:rel]-(a1)-[:rel]->(b1)
WHERE y1 <> b1 AND y1 <> b2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM