如何在Neo4J 3.x中构建一个Cypher / APOC查询,它可以搜索两种不同的关系类型?

时间:2018-02-21 11:48:23

标签: neo4j cypher neo4j-apoc

目前,我使用以下Cypher / APOC查询按特定属性(TO id)搜索关系类型user

CALL apoc.index.relationships('TO','user:16c01100-aa92-11e3-a3f6-35e25c9775ff') YIELD rel, start, end
WITH DISTINCT rel, start, end
MATCH (ctx:Context)
WHERE rel.context = ctx.uid 
ETURN DISTINCT start.uid AS source_id,
start.name AS source_name,
end.uid AS target_id,
end.name AS target_name,
rel.uid AS edge_id,
ctx.name AS context_name,
rel.statement AS statement_id,
rel.weight AS weight;

我希望不仅可以搜索索引TO,还可以搜索索引ATAT类型的关系),以便生成rel参数包含TOAT关系。

我认为这会像添加OR运算符一样简单,如下所示:

CALL apoc.index.relationships('TO','user:16c01100-aa92-11e3-a3f6-35e25c9775ff') OR
apoc.index.relationships('AT','user:16c01100-aa92-11e3-a3f6-35e25c9775ff') YIELD rel, start, end
WITH DISTINCT rel, start, end
MATCH (ctx:Context)
WHERE rel.context = ctx.uid
RETURN DISTINCT start.uid AS source_id,
start.name AS source_name,
end.uid AS target_id,
end.name AS target_name,
rel.uid AS edge_id,
ctx.name AS context_name,
rel.statement AS statement_id,
rel.weight AS weight;

但它不起作用......

也许有一些我可以做的事情,我从这两个rel获得apoc s然后简单地将它们合并为一个rel但我不会&#39我真的知道如何做到这一点......或许我有一种更容易看到的方式?

2 个答案:

答案 0 :(得分:1)

使用UNION条款怎么样:

CALL apoc.index.relationships('TO','user:16c01100-aa92-11e3-a3f6-35e25c9775ff') YIELD rel, start, end
WITH DISTINCT rel, start, end
MATCH (ctx:Context)
WHERE rel.context = ctx.uid
RETURN DISTINCT start.uid AS source_id,
start.name AS source_name,
end.uid AS target_id,
end.name AS target_name,
rel.uid AS edge_id,
ctx.name AS context_name,
rel.statement AS statement_id,
rel.weight AS weight
UNION
CALL apoc.index.relationships('AT','user:16c01100-aa92-11e3-a3f6-35e25c9775ff') YIELD rel, start, end
WITH DISTINCT rel, start, end
MATCH (ctx:Context)
WHERE rel.context = ctx.uid
RETURN DISTINCT start.uid AS source_id,
start.name AS source_name,
end.uid AS target_id,
end.name AS target_name,
rel.uid AS edge_id,
ctx.name AS context_name,
rel.statement AS statement_id,
rel.weight AS weight

答案 1 :(得分:0)

您可以使用run cypher fragment

执行此操作
WITH '16c01100-aa92-11e3-a3f6-35e25c9775ff' as userId

CALL apoc.cypher.run("
     CALL apoc.index.relationships('TO','user:' + $id) YIELD rel
     RETURN rel
", {id: userId}) YIELD value
WITH userId, collect(value.rel) as r1

CALL apoc.cypher.run("
     CALL apoc.index.relationships('AT','user:' + $id) YIELD rel
     RETURN rel
", {id: userId}) YIELD value
WITH r1, collect(value.rel) as r2

UNWIND (r1 + r2) as rel
WITH rel, nodeStart(rel) as start, nodeEnd(rel) as end
MATCH (ctx:Context)
WHERE rel.context = ctx.uid
RETURN DISTINCT start.uid AS source_id,
                start.name AS source_name,
                end.uid AS target_id,
                end.name AS target_name,
                rel.uid AS edge_id,
                ctx.name AS context_name,
                rel.statement AS statement_id,
                rel.weight AS weight;