如何汇总Cypher

时间:2016-11-21 05:58:06

标签: neo4j cypher aggregation

基本上,我问的是如何完成以下Cypher查询:

    unwind([[1, 2, 2, 3, 3, 3], [4, 4, 4, 4, 2, 2]]) as val
    ...
    return ...

,这样我就可以得到以下结果:

    +-----------------+
    | {1:1, 2:2, 3:3} |
    +-----------------+
    | {4:4, 2:2}      |
    +-----------------+

对于每一行val,它会计算val中每个元素的出现次数。

1 个答案:

答案 0 :(得分:0)

我在列表中使用字符,因为它们使结果更容易理解。

UNWIND [['a', 'b', 'b', 'c', 'c', 'c'], ['d', 'd', 'd', 'd', 'b', 'b']] as list
WITH list AS list1, list AS list2
UNWIND list2 AS element
WITH list1, element, COUNT(element) AS count
RETURN list1 AS list, COLLECT(element) AS values, COLLECT(count) AS counts

这导致:

╒══════════════════╤═════════╤═════════╕
│list              │values   │counts   │
╞══════════════════╪═════════╪═════════╡
│[a, b, b, c, c, c]│[c, a, b]│[3, 1, 2]│
├──────────────────┼─────────┼─────────┤
│[d, d, d, d, b, b]│[b, d]   │[2, 4]   │
└──────────────────┴─────────┴─────────┘

this question的回答表明

  

可能无法动态分配地图密钥

但它在创建双元素列表时提供了一个不错的选择。使用此方法,查询变为:

UNWIND [['a', 'b', 'b', 'c', 'c', 'c'], ['d', 'd', 'd', 'd', 'b', 'b']] as list
WITH list AS list1, list AS list2
UNWIND list2 AS element
WITH list1, element, COUNT(element) AS count
WITH list1 AS list, COLLECT(element) AS values, COLLECT(count) AS counts
RETURN
  list,
  EXTRACT(i IN RANGE(0, LENGTH(values) - 1) | [values[i], counts[i]]) AS occurrences

这给出了:

╒══════════════════╤════════════════════════╕
│list              │occurrences             │
╞══════════════════╪════════════════════════╡
│[a, b, b, c, c, c]│[[c, 3], [a, 1], [b, 2]]│
├──────────────────┼────────────────────────┤
│[d, d, d, d, b, b]│[[b, 2], [d, 4]]        │
└──────────────────┴────────────────────────┘