Neo4j Cypher Query基于相关节点的属性。获取具有最大属性值

时间:2017-10-04 17:56:36

标签: neo4j cypher

我有以下结构:

(A)-[:many]->(B)-[:also_many]->(C)

B有一个名字属性。 C有一个日期属性。 A有很多B相关,而且每个B都有很多C相关。

我希望获得唯一B以及C,其中c.date最高。

日期存储如下:" YYYY-MM-DD HH:MM:SS"。我使用apoc.date.parse(date)来获取时间戳值。

真的不知道如何处理这个问题。

示例数据集:

create (o:A {outlet: "SFO"}), (a:B {name: "Varun", date: "2017-04-01 00:00:00"}), (b:B {name: "Karen", date: "2017-04-12 00:00:00"}), (c:B {name: "Vicky", date: "2017-06-01 00:00:00"}), (aa:C {date: "2017-09-8 00:00:00", tag_no: "R2017123"}), (ab:C {date: "2017-09-02 00:00:00", tag_no: "R2017321"}), (ac:C {date: "2017-09-10 00:00:00", tag_no: "R2017423"}), (ad:C {date: "2017-09-23 00:00:00", tag_no: "R2017523"}), (ae:C {date: "2017-09-10 00:00:00", tag_no: "R2017930"}), (ba:C {date: "2017-09-02 00:00:00", tag_no:"R2017928"}), (bb:C {date: "2017-09-15 00:00:00", tag_no:"R2017039"}), (bc:C {date: "2017-09-10 00:00:00", tag_no:"R2017837"}), (bd:C {date: "2017-09-08 00:00:00", tag_no:"R2017022"}), (be:C {date: "2017-09-10 00:00:00", tag_no:"R2017883"}), (ca:C {date: "2017-09-11", tag_no:"R2017827"}), (cb:C {date: "2017-09-18", tag_no:"R2017322"}), (cc:C {date: "2017-09-21", tag_no:"R2017122"}), (cd:C {date: "2017-09-16", tag_no:"R2017877"}), (ce:C {date: "2017-09-08", tag_no:"R2017930"}), (o)-[:owns]->(a),(o)-[:owns]->(b),(o)-[:owns]->(c),(a)-[:subs]->(aa),(a)-[:subs]->(ab),(a)-[:subs]->(ac),(a)-[:subs]->(ad),(a)-[:subs]->(ae),(b)-[:subs]->(ba),(b)-[:subs]->(bb),(b)-[:subs]->(bc),(b)-[:subs]->(bd),(b)-[:subs]->(be),(c)-[:subs]->(ca),(c)-[:subs]->(cb),(c)-[:subs]->(cc),(c)-[:subs]->(cd),(c)-[:subs]->(ce);

我需要两个查询:

我希望返回B2014-04-012014-05-01节点以及每个C节点的最新相关B节点B.date 1}}。在数据集中,我有两个C个节点,它们具有相同的date。但查询应该只返回每个B节点的一个结果。

第二个问题是:

返回B个节点,其中包含日期在上述值内的节点,其中没有C个节点,其日期在日期范围内,例如" 2017-09-01"和" 2017-09-09"。

1 个答案:

答案 0 :(得分:1)

  

我想返回日期在2014-04-01和之内的B节点   2014-05-01和B.date的每个B节点的最新相关C节点。在   数据集,我有两个具有相同日期的C节点。但查询   应该只返回每个B节点一个结果。

这应该有效:

MATCH (b:B)-[:subs]->(c:C)
// filter b nodes by date range
WHERE b.date >= "2017-04-01" and b.date <= "2017-04-15"
// store c nodes into collection and get the max date for c nodes
// grouped by b
WITH b as b, collect(c) as cs, MAX(c.date) as maxDate
// return b, filtering only c nodes that date are equals to maxDate
// getting only the first filtered 
return b, filter(c in cs WHERE c.date = maxDate)[0]
  

返回B节点,其中日期在上面的值之内,没有C   日期在日期范围内的节点,例如&#34; 2017-09-01&#34;和&#34; 2017-09-09&#34;。

而且:

MATCH (b:B)-[:subs]->(c:C)
WHERE (b.date >= "2017-04-01" and b.date <= "2017-04-15")
AND (c.date <= "2017-09-01" and c.date >= "2017-09-09")
RETURN b