如何为流中的每个记录展开集合,执行操作并重新组合集合?

时间:2019-01-18 19:21:25

标签: neo4j cypher

我正在运行随机游走算法以生成时间事件链。结果集合中的每个条目都是一个节点ID。一个例子是:

[43116, 43116, 43116, 43116, 43116, 43116]
[61412, 61416, 4948, 61417, 61419, 61420]
...

对于从流返回的每一行,如何解开值,对该元素执行algo.getNodeById(node_id),然后将这些结果打包回集合中?

密码查询如下:

CALL algo.randomWalk.stream(null, 5, 20, {
  nodeQuery: "MATCH (a:Asset) RETURN id(a) as id",
  relationshipQuery: "MATCH (a1:Asset)<-[:PATIENT]-(e1:EVENT)-[:NEXT]->(e2:EVENT)-[:PATIENT]-(a2:Asset) RETURN id(a1) as source, id(a2) as target",
  graph: "cypher" })
YIELD nodeIds

2 个答案:

答案 0 :(得分:1)

在对集合执行UNWIND之后,Cypher不会删除该集合。因此,无需重新创建集合。

例如:

WITH [61412, 61416, 4948, 61417, 61419, 61420] AS data
UNWIND data AS d
RETURN data, d;

返回此:

╒════════════════════════════════════╤═════╕
│"data"                              │"d"  │
╞════════════════════════════════════╪═════╡
│[61412,61416,4948,61417,61419,61420]│61412│
├────────────────────────────────────┼─────┤
│[61412,61416,4948,61417,61419,61420]│61416│
├────────────────────────────────────┼─────┤
│[61412,61416,4948,61417,61419,61420]│4948 │
├────────────────────────────────────┼─────┤
│[61412,61416,4948,61417,61419,61420]│61417│
├────────────────────────────────────┼─────┤
│[61412,61416,4948,61417,61419,61420]│61419│
├────────────────────────────────────┼─────┤
│[61412,61416,4948,61417,61419,61420]│61420│
└────────────────────────────────────┴─────┘

答案 1 :(得分:1)

(我的第二个答案是基于对第一个答案的评论中的澄清。)

您可以改为执行此操作(使用algo.getNodesById(),它使用节点ID的列表):

CALL algo.randomWalk.stream(null, 5, 20, {
  nodeQuery: "MATCH (a:Asset) RETURN id(a) as id",
  relationshipQuery: "MATCH (a1:Asset)<-[:PATIENT]-(e1:EVENT)-[:NEXT]->(e2:EVENT)-[:PATIENT]-(a2:Asset) RETURN id(a1) as source, id(a2) as target",
  graph: "cypher" })
YIELD nodeIds
UNWIND nodeIds AS nodeId
WITH DISTINCT nodeId
RETURN algo.getNodesById(COLLECT(nodeId)) AS nodes;

或者,您可以在没有algo.getNodesById()的情况下做同样的事情:

CALL algo.randomWalk.stream(null, 5, 20, {
  nodeQuery: "MATCH (a:Asset) RETURN id(a) as id",
  relationshipQuery: "MATCH (a1:Asset)<-[:PATIENT]-(e1:EVENT)-[:NEXT]->(e2:EVENT)-[:PATIENT]-(a2:Asset) RETURN id(a1) as source, id(a2) as target",
  graph: "cypher" })
YIELD nodeIds
UNWIND nodeIds AS nodeId
WITH DISTINCT nodeId
MATCH (n) WHERE ID(n) = nodeId
RETURN COLLECT(n) AS nodes;

在两个查询中,都需要WITH DISTINCT nodeId子句才能删除重复项。