在Neo4j cypher查询中匹配为逻辑AND / OR?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (1)
  • 查看 (842)

我需要查询匹配的图形或任何子图,如下所示:

所以我尝试了OPTIONAL MATCH,但我意识到它不能提供我所需的结果。这是我之前尝试过的查询。

OPTIONAL MATCH (w:W)-[:WRITES]->(a1:A{name:"A1"})
WITH w,a1
OPTIONAL MATCH (w)-[:WRITES]->(a2:A{name:"A2"})
WITH w,a1,a2
OPTIONAL MATCH (w)-[:WRITES]->(a3:A{name:"A3"})
WITH w,a1,a2,a3
OPTIONAL MATCH (w)-[:WRITES]->(a4:A{name:"A4"})
RETURN w,a1,a2,a3,a4

虽然它是可选的匹配,但它仍然是与外连接的逻辑AND匹配(在SQL的上下文中)

在我的情况下,我需要在每个匹配中同时使用OR和AND结果,这意味着它应匹配上述解释图的任何子图。

所以,我需要获取结果如下。

MATCH (w:W)-[:WRITES]->(a1:A{name:"A1"})

OR / AND

MATCH (w)-[:WRITES]->(a2:A{name:"A2"})

OR / AND

MATCH (w)-[:WRITES]->(a3:A{name:"A3"})

OR / AND

MATCH (w)-[:WRITES]->(a4:A{name:"A4"})
RETURN w,a1,a2,a3,a4

有没有可能通过Neo4j cypher查询来实现我的要求?

我的结果集应该是这样的。

W, A1, A2, A3, A4
{name:w1,....}, {name:A1,....}, {name:A2,....}, {name:A3,....}, {name:A4,....}
{name:w1,....}, null, {name:A2,....}, null, {name:A4,....}
{name:w1,....}, null, null, null, {name:A4,....}
{name:w1,....}, {name:A1,....}, {name:A2,....}, null, null
{name:w1,....}, {name:A1,....}, null, {name:A3,....}, {name:A4,....}
提问于
用户回答回答于

可以使用以下查询:

MATCH (a1:A{name:"A1"}), (a2:A{name:"A2"}), (a3:A{name:"A3"}), (a4:A{name:"A4"})
UNWIND [a1, a2, a3, a4] as a
MATCH (w:W)-[:WRITES]->(a)
WITH a1, a2, a3, a4, w, collect(a) as connectedNodes
WITH w, CASE WHEN a1 in connectedNodes THEN a1 ELSE null END as a1, 
        CASE WHEN a2 in connectedNodes THEN a2 ELSE null END as a2,
        CASE WHEN a3 in connectedNodes THEN a3 ELSE null END as a3,
        CASE WHEN a4 in connectedNodes THEN a4 ELSE null END as a4
RETURN w, a1, a2, a3, a4

扫码关注云+社区

领取腾讯云代金券