如何获得按关系属性排序的节点关系列表?

时间:2019-03-25 18:16:47

标签: neo4j cypher

我想获取节点关系列表,该列表按关系属性排序。 例如,我的节点有两个标签,分别为Org和Company,它们之间只有一种关系类型为INVEST_IN。 INVEST_IN关系具有属性“系列”,该属性可以是“系列A”,“系列B”,“系列C” 因此该图如下所示:

merge (o:Org{name:'Google'})
merge (o2:Org{name:'Facebook'})
merge (c:Company{name:'Company1'})
merge (c2:Company{name:'Company2'})
merge (o)-[:INVEST_IN{series:'A'}]-(c)
merge (o)-[:INVEST_IN{series:'B'}]-(c)
merge (o)-[:INVEST_IN{series:'C'}]-(c)
merge (o)-[:INVEST_IN{series:'A'}]-(c2)
merge (o)-[:INVEST_IN{series:'B'}]-(c2)
merge (o2)-[:INVEST_IN{series:'C'}]-(c)
merge (o2)-[:INVEST_IN{series:'B'}]-(c2)
merge (o2)-[:INVEST_IN{series:'C'}]-(c2)

enter image description here

所以我需要这样的结果:

组织ordered_series

Google [A,B,C]
Facebook [C,B]

结果由每个组织关系的序列数排序。 Google有2 A系列,2 B系列,1 C系列,所以结果是[A,B,C] Facebook有1个B系列和2个C系列,所以结果是[C,B]

match (o:Org)-[r:INVEST_IN]->(c:Company)
return o.name, r.series, count(r.series)

返回enter image description here

我不了解

之间的区别
match (o:Org)-[r:INVEST_IN]->(c:Company)
return o.name, r.series, count(r.series)

match (o:Org)-[r:INVEST_IN]->(c:Company)
with o, r, count(r.series) as cr
return o.name, r.series, cr

它们是如此不同。我无法订购该关系并收集它们。 谁能告诉我我该怎么做?

1 个答案:

答案 0 :(得分:1)

只要Org节点具有唯一的name值,您的2个查询在逻辑上是相同的。

此查询:

MATCH (o:Org)-[r:INVEST_IN]->(c:Company)
RETURN o.name AS name, r.series AS series, COUNT(r.series) AS cnt
ORDER BY name ASC, cnt DESC

产生以下结果:

╒══════════╤════════╤═════╕
│"name"    │"series"│"cnt"│
╞══════════╪════════╪═════╡
│"Facebook"│"C"     │2    │
├──────────┼────────┼─────┤
│"Facebook"│"B"     │1    │
├──────────┼────────┼─────┤
│"Google"  │"A"     │2    │
├──────────┼────────┼─────┤
│"Google"  │"B"     │2    │
├──────────┼────────┼─────┤
│"Google"  │"C"     │1    │
└──────────┴────────┴─────┘

[更新]

要获取列表中每个Org的系列:

MATCH (o:Org)-[r:INVEST_IN]->(c:Company)
WITH o.name AS name, r.series AS series, COUNT(r.series) AS cnt
ORDER BY name ASC, cnt DESC
RETURN name, COLLECT(series) AS seriesList

产生以下结果:

╒══════════╤═════════════╕
│"name"    │"seriesList" │
╞══════════╪═════════════╡
│"Facebook"│["C","B"]    │
├──────────┼─────────────┤
│"Google"  │["A","B","C"]│
└──────────┴─────────────┘