Neo4j Cypher查询空集使整个结果为空

时间:2016-09-21 10:05:21

标签: neo4j cypher graph-databases

我一直面临着奇怪的问题,我试图从我建立的neo4j图中获取数据。这是我的查询

MATCH (u1:User {user_id: 4})-[:FOLLOWS]->(u2:User)-[]->(r1:Rest{city_id: 1})
WITH COLLECT ({ REST: r1.res_id}) as rows
MATCH (u1:User {user_id: 4})-[rel]->(r2:Rest{city_id: 1})
WHERE NOT (u1:User {user_id: 4})-[rel : BEEN_THERE | ADD_REVIEW]->(r2:Rest{city_id: 1})
WITH rows + COLLECT ({ REST: r2.res_id}) AS allrows
UNWIND allrows as row 
RETURN row.REST as RESTAURANT_ID, count(row.REST) as COUNT
ORDER BY COUNT desc
LIMIT 15;

但是当COLLECT({REST:r2.res_id})的结果为空时,整个结果变为空。此外,查询无法识别第一个匹配的行并返回未定义的rows。请告诉我。谢谢!

1 个答案:

答案 0 :(得分:2)

如果模式与任何路径不匹配,则结果确实为空。

您必须将MATCH拆分为2并将第二个OPTIONAL拆分,或者在实际情况下,一遍又一遍地停止匹配同一个u1节点:

MATCH (u1:User {user_id: 4})
OPTIONAL MATCH (u1)-[:FOLLOWS]->(:User)-->(r1:Rest {city_id: 1})
WITH u1, collect({ REST: r1.res_id }) AS rows
OPTIONAL MATCH (u1)-->(r2:Rest {city_id: 1})
WHERE NOT (u1)-[:BEEN_THERE | ADD_REVIEW]->(r2)
WITH rows + collect({ REST: r2.res_id }) AS allrows
UNWIND allrows as row 
RETURN row.REST AS RESTAURANT_ID, count(row.REST) AS COUNT
ORDER BY COUNT desc
LIMIT 15

我不确定你的第一个OPTIONAL MATCH(你只提到第二个collect是一个阻止者),但如果你想要两个模式的聚合,其中每个都可以为空,你走了。