variable length matching over paths in Cypher

亡梦爱人 提交于 2020-01-04 18:12:06

问题


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

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.


回答1:


Yes, you can do this. It's actually much easier than you think:

MATCH p=(s)-[r:KNOWS|BLOCKS*]->(t) 
RETURN s, t;

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;

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;


来源:https://stackoverflow.com/questions/30097082/variable-length-matching-over-paths-in-cypher

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!