【问题标题】:Calculate total count of two nodes and number of relations between them in single query using cypher - neo4j使用密码计算单个查询中两个节点的总数和它们之间的关系数 - neo4j
【发布时间】:2014-10-09 10:59:46
【问题描述】:

我有一个包含实体Customer、Product 和关系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  

谁能解释一下单个查询中发生了什么?

【问题讨论】:

    标签: neo4j cypher graph-databases


    【解决方案1】:

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

    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 关系,我认为您无法获得所有计数。如果有序关系可能发生在其他类型的节点之间,则必须在倒数第二行添加交换:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-19
      • 2014-07-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多