Neo4j 查询 2 个关系并计算 2 个关系的聚合函数

Neo4j querying over 2 relationships and compute an aggregate function on the 2 relationship

我有这个数据模型:

有节点:

以及关系:

我正在尝试获得具有平均资格的最畅销产品,我实际上尝试了这个查询:

MATCH (p:Product)<-[b:Buy]-(c:Client)
CALL{
    WITH c, p
    MATCH (c)-[r:Recommend]->(p)
    RETURN avg(r.qualification) as average_qualification
} 
RETURN p, c, count(b) as qty, average_qualification 
ORDER BY qty DESC

但是查询 return 每个客户端的每个 average_qualification 一行(类似这样):

但我想对每个产品进行分组,因此它需要合并产品相同的行,因此例如第 1 行和第 4 行将合并,average_qualification 将是 average_qualification 的产品(不按客户资格划分)。

您可以这样做:

MATCH (p:Product)<-[b:Buy]-(:Client)
WITH p, count(b) AS qty
MATCH (:Client)-[r:Recommend]->(p)
RETURN p, qty, avg(r.qualification) AS average_qualification
ORDER BY qty DESC

其中包含此示例数据:

MERGE (a:Client{name: 'A'})
MERGE (b:Client{name: 'B'})
MERGE (c:Client{name: 'C'})
MERGE (d:Client{name: 'D'})
MERGE (e:Client{name: 'E'})
MERGE (f:Vendor{key: 2})
MERGE (g:Vendor{key: 3})
MERGE (h:Vendor{key: 4})
MERGE (j:Product{key: 5})
MERGE (i:Product{key: 6})
MERGE (k:Product{key: 7})
MERGE (l:Product{key: 8})
MERGE (m:Product{key: 9})

MERGE (a)-[:Recommend{qualification: 4}]-(j)
MERGE (a)-[:Recommend{qualification: 4}]-(k)
MERGE (c)-[:Recommend{qualification: 3}]-(i)
MERGE (e)-[:Recommend{qualification: 3}]-(j)
MERGE (a)-[:Buy]-(k)
MERGE (a)-[:Buy]-(j)
MERGE (b)-[:Buy]-(l)
MERGE (d)-[:Buy]-(m)
MERGE (c)-[:Buy]-(i)
MERGE (d)-[:Buy]-(i)
MERGE (e)-[:Buy]-(i)
MERGE (e)-[:Buy]-(j)
MERGE (f)-[:Sell]-(i)
MERGE (f)-[:Sell]-(j)
MERGE (g)-[:Sell]-(k)
MERGE (h)-[:Sell]-(l)
MERGE (h)-[:Sell]-(m)

会 return:

╒═════════╤═════╤═══════════════════════╕
│"p"      │"qty"│"average_qualification"│
╞═════════╪═════╪═══════════════════════╡
│{"key":6}│3    │3.0                    │
├─────────┼─────┼───────────────────────┤
│{"key":5}│2    │3.5                    │
├─────────┼─────┼───────────────────────┤
│{"key":7}│1    │4.0                    │
└─────────┴─────┴───────────────────────┘

为了理解这个解决方案,以及为什么它与您的不同,我建议您阅读 cardinality 的概念。

不需要同时计算[:buy]和(:Client)。只保留其中一个,然后 counting 它,让我们可以用产品列表而不是客户列表来完成第一个 MATCH。第二个 MATCH 也是如此,我们在 r.qualification 上使用 avg,允许我们维护产品列表而不是推荐列表。