问题描述
是否可以在Cypher中的多个路径上允许可变长度匹配?通过路径,我的意思是类似两个KNOWS遍历或三个BLOCKS遍历,其中KNOWS和BLOCKS是我图中的关系类型。例如,我希望能够编写以下内容:
Is it possible to allow variable length matching over multiple paths in Cypher? By a path I mean something like two KNOWS traversals or three BLOCKS traversals, where KNOWS and BLOCKS are relationship types in my graph. For example, I'd like to be able to write something like:
MATCH (s)-[r*]->(t)
WHERE ALL (x in type(r) WHERE x=KNOWS/KNOWS OR x= BLOCKS/BLOCKS/BLOCKS)
RETURN s, t
其中 KNOWS / KNOWS的意思是(a)-[:KNOWS]->(b)-[:KNOWS]-> (C)。我想通过添加诸如KNOWS / KNOWS之类的关系而不更改数据本身来做到这一点,而只是将其作为密码查询。
where by "KNOWS/KNOWS" I mean something like (a)-[:KNOWS]->(b)-[:KNOWS]->(c). I want to do this without changing the data itself, by adding relationships such as KNOWS/KNOWS, but rather just as a cypher query.
推荐答案
是的,您可以这样做。实际上,它比您想象的要容易得多:
Yes, you can do this. It's actually much easier than you think:
MATCH p=(s)-[r:KNOWS|BLOCKS*]->(t)
RETURN s, t;
指定 r
时,冒号,您可以指明要遍历的类型,并用竖线将它们分隔为 OR
。星号只是按您期望的方式运行。
When you specify the r
, with a colon you can indicate which types you want to traverse, and separate them by a pipe for OR
. The asterisk just operates the way you expect.
如果您一次只想要一种关系,可以这样做:
If you only want one type of relationship at a time you can do this:
OPTIONAL MATCH p1=(s1)-[r1:KNOWS*]->(t1)
OPTIONAL MATCH p2=(s2)-[r2:BLOCKS*]->(t2)
RETURN p1, p2;
如果您只想知道2个知识和3个块,则为:
If you want exactly two knows and 3 blocks, then it's:
OPTIONAL MATCH p1=(s1)-[:KNOWS]->()-[:KNOWS]->(t1)
OPTIONAL MATCH p2=(s2)-[:BLOCKS]->()-[:BLOCKS]->()-[:BLOCKS]->(t2)
RETURN p1, p2;
这篇关于Cypher中路径上的可变长度匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!