我看不到您试图通过嵌套FOREACH
循环实现什么。
如果你真的得到了hit
节点和session
节点,一个简单的MERGE
应该没问题。我认为你必须包括hit
在WITH
声明中。
MERGE (session :Session { id: "xxx" })
MERGE (hit:Hit { date_time:"2015-04-03T06:00:44" })
CREATE (hit)-[:IN_SESSION]->(session)
WITH session, hit
MATCH (prev_hit:Hit)-[:IN_SESSION]->(session)
WHERE prev_hit <> hit // make sure that you only match other hits
WITH hit, prev_hit
ORDER BY prev_hit.date_time DESC LIMIT 1
MERGE (prev_hit)-[:NEXT]->(hit) // create relationship between the two
更新
我将查询更新为仅匹配prev_hit
不是当前命中的。上面的查询可以按您的意愿工作,即它创建与与相同NEXT
的单个Hit
节点相关的单个关系Session
。见这里:http ://console.neo4j.org/?id=ov7mer
date_time 可能存在问题。我认为您将其存储为字符串,排序可能并不总是给您预期的结果。
更新 2
关于您的第二条评论:如果您逐行查看文件并添加Hit
节点,则只能将关系添加到Hit
已添加的节点。如果您想要节点之间的连续NEXT
关系链,Hit
则只能在一个查询中执行此操作,前提是您确保 CSV 文件的条目按 date_time 升序排列。
您可以稍后添加节点NEXT
之间的关系,如下所述:http: //www.markhneedham.com/blog/2014/04/19/neo4j-cypher-creating-relationships-between-a-collection-of-nodes-invalid -输入/Hit
开始查询:
MATCH (s:Session)--(hit:Hit)
// first order by hit.date_time
WITH DISTINCT s, hit ORDER BY hit.date_time DESC
// this will return one row per session with the hits in a collection
WITH s, collect(hit) AS this_session_hits
// try this to check the ordering:
// RETURN s.session_id, this_session_hits
// the following queries will be done on each row, this is like iterating over the sessions
FOREACH(i in RANGE(0, length(this_session_hits)-2) |
FOREACH(e1 in [this_session_hits[i]] |
FOREACH(e2 in [this_session_hits[i+1]] |
MERGE (e1)-[:NEXT]->(e2))))
最终答案;)
此查询适用于 neo4j 控制台 ( http://console.neo4j.org/?id=mginka ) 中的数据集。它将Hit
会话中的所有内容与NEXT
关系联系起来。
MATCH (s:Session)<--(hit:Hit)
WITH DISTINCT s, hit
ORDER BY hit.date_time ASC
WITH s, collect(hit) AS this_session_hits
FOREACH (i IN RANGE(0, length(this_session_hits)-2)|
FOREACH (e1 IN [this_session_hits[i]]|
FOREACH (e2 IN [this_session_hits[i+1]]|
MERGE (e1)-[:NEXT]->(e2))))