首页 文章

使用cypher - neo4j计算单个查询中两个节点的总数和它们之间的关系数

提问于
浏览
1

我有一个实体 CustomerProduct 和关系 ORDERED 的图表 . 以下是Cypher方式之间的关系

(Customer)-[:ORDERED]->(Product)

我想在单个密码查询中计算产品总数,客户总数和订单总数 .

以下是我写的查询

单一查询

MATCH 
    (c:Customer)-[r:ORDERED]->(p:Product),
    (p1:Product),
    (c1:Customer)
WITH     
    count(r) as order_count , 
    count(DISTINCT c1) as  customer_count , 
    count(DISTINCT p1) as  product_count 
RETURN order_count , customer_count , product_count

但是它长时间执行会给出错误的结果,所有计数都是相同的值 .

如果我独立执行每个计数,那么它会非常快速和正确地给出结果

单独查询

MATCH  (c:Customer)-[r:ORDERED]->(p:Product)
WITH  count(r) as order_count
RETURN order_count

MATCH (p1:Product)
WITH count(DISTINCT p1) as  product_count 
RETURN  product_count 

MATCH (c1:Customer)
WITH  count(DISTINCT c1) as  customer_count  
RETURN  customer_count

任何人都可以解释单个查询中发生了什么?

1 回答

  • 0

    您的查询正在爆炸,生成三个初始匹配的交叉积 . 要避免交叉产品,您可以:

    MATCH (c:Customer)
    WITH COUNT(c) AS customer_count
    MATCH (p:Product)
    with cs, COUNT(p) AS product_count
    MATCH ()-[r:ORDERED]->()
    RETURN customer_count, product_count, COUNT(r) AS order_count
    

    如果没有ORDERED关系的重新匹配,我认为你不能得到所有的计数 . 如果有序的relationsip可以在其他类型的节点之间发生,则必须添加第二行到最后一行的交换:

    MATCH (:Customer)-[r:ORDERED]->(:Product)
    

相关问题