从与 Cypher 的关系中获取 属性 的总比率

Getting aggregate ratio from a property from relationships with Cypher

假设我有这样的图表(请原谅伪代码):

(A)-[:RSVP {reply:true}]->(X)

(B)-[:RSVP {reply:true}]->(X)

(C)-[:RSVP {reply:false}]->(X)

如何获得正面回应的比例?我期待的结果会给我 0.66 的接受率。

我是这样模拟你的数据的:

CREATE (A), (B), (C), (X {label: "party time"})
MERGE (A)-[:RSVP {reply:true}]->(X)
MERGE (B)-[:RSVP {reply:true}]->(X)
MERGE (C)-[:RSVP {reply:false}]->(X);

然后,通过这个查询,我们可以简单地分别计算 "yes's" 和 "no's",并通过简单的除法创建比率:

MATCH (X {label:"party time"})
MATCH (X)<-[:RSVP {reply:true}]-(yeses),
      (X)<-[:RSVP {reply:false}]-(nos)
RETURN count(distinct(yeses))/count(distinct(nos));

我得到的答案是2,因为有2个是,1个不是。 (2/1 => 2)

使用@FrobberOfBits 的样本数据,以下是一个更通用的查询,它处理了几个特殊情况(否则会导致 Cypher 出现“/ by zero”错误)。

  1. 如果没有回复,查询returns字符串"No Matches".
  2. 如果没有false个回复,查询returns字符串"Infinity".
  3. 否则查询returns是与否的比率

    MATCH (X {label:"party time"})
    OPTIONAL MATCH (X)<-[:RSVP {reply:true}]-(yes)
    OPTIONAL MATCH (X)<-[:RSVP {reply:false}]-(no)
    WITH LENGTH(COLLECT(DISTINCT yes)) AS yeses, LENGTH(COLLECT(DISTINCT no)) AS nos
    RETURN CASE
      WHEN yeses = 0 AND nos = 0 THEN "No Matches"
      WHEN nos = 0 THEN "Infinity"
      ELSE TOFLOAT(yeses)/nos
    END;
    

要获得您最初要求的比率(是的比率与响应总数的比率),查询将是:

    MATCH (X {label:"party time"})
    OPTIONAL MATCH (X)<-[:RSVP {reply:true}]-(yes)
    OPTIONAL MATCH (X)<-[:RSVP {reply:false}]-(no)
    WITH LENGTH(COLLECT(DISTINCT yes)) AS yeses, LENGTH(COLLECT(DISTINCT no)) AS nos
    RETURN CASE
      WHEN yeses = 0 AND nos = 0 THEN "No Matches"
      ELSE TOFLOAT(yeses)/(yeses + nos)
    END;