1

我对 Neo4j 很感兴趣,我需要知道如何找到与给定子图的每个节点都有关系的节点。

让我们用一个例子来解释一下:

(我的数据库中有大约 15000 个节点)

现在,给定子图 (c1:Thing),(c2:Thing),...(cn:Thing) 我想知道所有不是 (c1),...,(cn) 但它们与 (c1),...,(cn) 的每个节点都有关系

换句话说,我会在关系存在的地方找到 Cj: (Cj)-[r1]-(c1) 。. . (Cj)-[rn]-(cn)

而 j 不在 {1, ...., n}

查看此图像以查看示例

所以基本上我想匹配像 c6 这样的节点,那些与子图的每个节点(红色节点)连接的节点。

注意:给定的子图可以有任意数量的节点(n 是可变的)。

我的第一个想法是:

MATCH (c1:Thing)-[r1]-(suggest:Thing), (c2:Thing)-[r2]-(suggest:Thing), .... ,(cn:Thing)-[rn]-(suggest :Thing) WHERE c1.id=1 AND ..... AND cn.id=n AND NOT(suggest.id IN [1, ...., n]) RETURN c1, r1, ...... , cn, rn, 建议;

但是当我们有一个很大的“n”时,这真的很糟糕。

你可以帮帮我吗?

感谢,并有一个愉快的一天!

4

1 回答 1

1

What follows is a way of tackling your question while making some assumptions about your data modeling.

A query similar to this one will likely get you what you want:

MATCH p=(n:Thing)-[:RELATED_TO]->(n2), (suggest:Thing)
WHERE n <> n2 AND NOT suggest IN nodes(p) AND ALL (x IN nodes(p) WHERE (suggest)-[:RELATED_TO]->(x))
RETURN suggest

Now, this assumes that the subgraph of interest (i.e. c1 to cn) are related by the same relationship. Of course, you could define the path/subgraph however you like, and even better would be to know your starting and endpoints, but you may or may not have that information handy. Also, if you're doing multi-length paths/subgraphs, be careful to limit them. As well if you ARE considering multi-length paths/subgraphs, the results you'll get back will potentially not be unique.

Another assumption is that (suggest) has the same relationship to each node of the subgraph and is of the same type as the relationships in your subgraph. Tweak this as necessary.

That said, this should be enough to get you started and/or thinking in the right direction. As always, how you model your data is just as important as how you write your queries, if not moreso.

HTH

于 2014-07-29T15:47:45.717 回答