在Cypher Neo4j中创建一个节点并为其分配表的总和

时间:2019-02-06 14:25:35

标签: neo4j cypher cypher-3.1

我试图弄清楚如何在Cypher中实现OLAP操作汇总。 我坚持寻找如何创建节点,然后在Cypher中为其分配表的列总和。更具体地说,我正在尝试实现以下结果: Code result [EDITED] 通过此代码,我得到的结果如图所示:

MATCH(p:Product)
WITH sum(p.unitsInStock) as SommeUnits, p.supplierID as Supplier, p.reorderLevel as ReordLevel
CREATE(reord:Product {productName : "TotalReord", unitsInStock : SommeUnits})
RETURN ReordLevel,Supplier, SommeUnits
ORDER BY ReordLevel

关系:供应商-[:供应]->(产品) 产品属性:unitsInStock,productName,productId,unitsInOrder,supplierID

问题在于此代码无法正常工作,因为它不仅会生成一个节点,而且会生成多个节点,并且只有当我两次查询时才能获得我得到的结果。

1 个答案:

答案 0 :(得分:1)

Aggregating functionsSUM一样,将同一(WITHRETURN)子句中的非聚合项用作“分组键”。因此,您的WITH子句将为每个不同的SommeUnits组合生成一个SommeUnits/ReordLevel值。每个CREATE值都会调用您的SommeUnits

此查询应该正常工作(假设您希望每个返回的记录都具有相同的SommeUnits值):

MATCH(p:Product) WHERE p.productName <> "TotalReord"
WITH SUM(p.unitsInStock) AS SommeUnits, COLLECT(p) AS ps
MERGE(t:Product {productName: "TotalReord"})
SET t.unitsInStock = SommeUnits
WITH ps, SommeUnits
UNWIND ps AS p
RETURN p.reorderLevel AS ReordLevel, p.supplierID AS Supplier, SommeUnits
ORDER BY ReordLevel

此查询使用MERGE来避免每次您调用此查询时都创建重复的“ TotalReord”节点。并且WHERE子句会过滤掉“ TotalReord”节点,以便在计算新的总和并对其进行膨胀时不会使用其现有的unitsInStock值。

如果您实际上希望每个返回的记录都具有该记录的SommeUnits/ReordLevel组合的总和,则可以执行以下操作:

MATCH(p:Product) WHERE p.productName <> "TotalReord"
WITH SUM(p.unitsInStock) AS u, p.reorderLevel AS r, p.supplierID AS s
WITH COLLECT({u:u, r:r, s:s}) AS data, SUM(u) AS total
MERGE(t:Product {productName: "TotalReord"})
SET t.unitsInStock = total
WITH data
UNWIND data AS d
RETURN d.r AS ReordLevel, d.s AS Supplier, d.u AS SommeUnits
ORDER BY ReordLevel

[已更新]

最后,如果您要执行上一个查询,但又要获得总计,此查询将在每个返回的记录中将总计显示为第四个值:

MATCH(p:Product) WHERE p.productName <> "TotalReord"
WITH SUM(p.unitsInStock) AS u, p.reorderLevel AS r, p.supplierID AS s
WITH COLLECT({u:u, r:r, s:s}) AS data, SUM(u) AS total
MERGE(t:Product {productName: "TotalReord"})
SET t.unitsInStock = total
WITH data, total
UNWIND data AS d
RETURN d.r AS ReordLevel, d.s AS Supplier, d.u AS SommeUnits, total
ORDER BY ReordLevel