繁体   English   中英

Neo4J Cypher:按条件过滤出可变长度路径

[英]Neo4J Cypher: filter out variable length paths by criteria

如何暗示对可变长度路径的限制?

我有一些start节点查询提供的所有可能路径:

CREATE INDEX ON :NODE(id)
MATCH all_paths_from_Start = (start:Person)-[:FRIENDSHIP*1..20]->(person:Person)
WHERE start.id = 128 AND start.country <> "Uganda"
RETURN paths;

不,我想过滤出至少有两个人来自同一country所有路径。 我该怎么办?

1)获取可能重复的国家列表: REDUCE

2)删除重复项并比较数组的大小: UNWIND + COLLECT(DISTINCT...)

MATCH path = (start:Person)-[:FRIENDSHIP*1..20]->(person:Person)
      WHERE start.id = 128 AND start.country <> "Uganda"
WITH path, 
     REDUCE(acc=[], n IN NODES(path) | acc + n.country) AS countries
     UNWIND countries AS country
WITH path, 
     countries, COLLECT(DISTINCT country) AS distinctCountries
     WHERE SIZE(countries) = SIZE(distinctCountries)
RETURN path

PS REDUCE可以用EXTRACT代替(感谢Gabor Szarnyas):

MATCH path = (start:Person)-[:FRIENDSHIP*1..20]->(person:Person)
      WHERE start.id = 128 AND start.country <> "Uganda"
WITH path, 
     EXTRACT(n IN NODES(path) | n.country) AS countries
     UNWIND countries AS country
WITH path, 
     countries, COLLECT(DISTINCT country) AS distinctCountries
     WHERE SIZE(countries) = SIZE(distinctCountries)
RETURN path

PPS再次感谢Gabor Szarnyas提供了另一个简化查询的方法:

MATCH path = (start:Person)-[:FRIENDSHIP*1..20]->(person:Person)
      WHERE start.id = 128 AND start.country <> "Uganda"
WITH path
     UNWIND NODES(path) AS person
WITH path, 
     COLLECT(DISTINCT person.country) as distinctCountries
     WHERE LENGTH(path) + 1 = SIZE(distinctCountries)
RETURN path

我能想到的一种解决方案是获取路径的nodes ,并为路径上的每个人extract同一国家/地区的人数(通过对同一国家/地区进行filter确定)。如果来自同一国家的人为零,则该人具有来自唯一国家的人,即,对于所有人,只有来自该国家的一个人(该人本人)。

MATCH p = (start:Person {id: 128})-[:FRIENDSHIP*1..20]->(person:Person)
WHERE start.country <> "Uganda"
WITH p, nodes(p) AS persons
WITH p, extract(p1 IN persons | size(filter(p2 IN persons WHERE p1.country = p2.country))) AS personsFromSameCountry
WHERE length(filter(p3 IN personsFromSameCountry WHERE p3 > 1)) = 0
RETURN p

该查询在语法上是正确的,但是我没有对任何数据进行测试。

请注意,我将id = 128条件移至该模式,并将all_paths_from_Start变量缩短为p

暂无
暂无

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

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