在Neo4j v2.3.3中聚合以设置关系的值

时间:2016-05-14 15:54:05

标签: neo4j cypher

我尝试使用现有数据来创建新的关系类型。我正在尝试策略in this question,但我没有得到预期的结果。

此:

MATCH (user)-[r:POSTS_TO]->(thread)<-[s:POSTS_TO]-(other) 
MERGE (user)-[act:TALKS_TO]->(other)

有效,可以在同一论坛帖子中发布的用户之间创建唯一关系,但没有为TALKS_TO设置关系属性。我想将每个用户共享的线程数添加到关系中,目的是删除基础POSTS_TO关系。

当我尝试这个时:

MATCH (user:User)-[r:POSTS_TO]->(thread:Thread)<-[s:POSTS_TO]-(other:User) 
WITH thread, count(r.thread_id) as total_threads
MERGE (user)-[act:TALKS_TO]->(other)
ON CREATE SET act.total_threads = thread.total_threads

只有两个节点(两者都不是用户节点)和一个关系被设置,没有属性。

我也试过

MATCH (user:User)-[r:POSTS_TO]->(thread:Thread)<-[s:POSTS_TO]-(other:User) 
WITH thread, count(thread) as total_threads
MERGE (user)-[act:TALKS_TO]->(other)
ON CREATE SET act.total_threads = thread.total_threads

具有相同的结果。

我无法比较with this question中我出错的地方。评论与评论请更正?

这是我要设置为每个TALKS_T0关系的属性的完整数据集:

MATCH (user)-[r:POSTS_TO]->(thread)<-[s:POSTS_TO]-(other) 
WITH r, 
    min(r.event_time) as first_post, 
    max(r.event_time) as last_post, 
    count(distinct r.post_id) as total_posts, 
    count(distinct r.thread_id) as total_threads,
    count(distinct r.forum_id) as total_forums
MERGE (user)-[act:TALKS_TO]->(other)
ON CREATE SET act.first_post = first_post,
          act.last_post = last_post,
          act.total_posts = total_posts,
          act.total_threads = total_threads,
          act.total_forums = total_forums

2 个答案:

答案 0 :(得分:0)

您尝试的第一个查询存在多个问题:

  1. 您没有在user子句中包含otherWITH,因此MERGE子句没有看到它们,而是被迫创建新节点。< / LI>
  2. 您的SET子句使用thread.total_threads(不存在)而不是total_threads的值。因此,SET子句从未创建任何属性。
  3. 此查询修复了这两个问题:

    MATCH (user:User)-[r:POSTS_TO]->(thread:Thread)<-[s:POSTS_TO]-(other:User)
    WITH user, other, thread, count(r.thread_id) as total_threads
    MERGE (user)-[act:TALKS_TO]->(other)
    ON CREATE SET act.total_threads = total_threads;
    

    评论1:POSTS_TO关系具有冗余thread_id属性,因为关系的Thread结束节点可能具有相同的id值。 评论2:如果你摆脱了POSTS_TO关系,那么看起来Thread节点最终会完全断开连接。您可能需要更仔细地考虑您要完成的任务。

答案 1 :(得分:0)

这最终正常运作:

MATCH (user:User)-[r:POSTS_TO]->(thread:Thread)<-[s:POSTS_TO]-(other:User) 
WITH 
user, 
other, 
thread, 
r.first_post as first_posts,
r.last_post as last_posts,
r.total_posts as total_posts_to_thread
WITH 
user, 
other,
sum(total_posts_to_thread) as total_posts,
count(thread) as total_threads, 
min(first_posts) as first_post, 
max(last_posts) as last_post
MERGE (user)-[act:TALKS_TO]->(other)
ON CREATE SET act.first_post = first_post,
          act.last_post = last_post,
          act.total_posts = total_posts,
          act.total_threads = total_threads