基于Neo4j实现浮点数区间分组统计细胞表达量数量
Got it, let's break down how to get the exact output you need for counting cells by their gene expression value intervals in Neo4j.
核心思路
We'll match the cell-expression-gene relationships, categorize each expression value into your target intervals, then group and count cells per interval. Here's the step-by-step Cypher query:
针对特定基因的统计(推荐,更精准)
If you want to count cells based on expression of a specific gene (the most common use case), use this query:
MATCH (c:Cell)-[ex:EXPRESSES]->(g:Gene) // 替换成你要查询的基因名 WHERE g.geneName = "EGFR" WITH c, ex.expr AS expr // 划分你指定的表达区间 WITH CASE WHEN expr >= 0 AND expr < 0.1 THEN "[0, 0.1)" WHEN expr >= 0.1 AND expr < 0.2 THEN "[0.1, 0.2)" WHEN expr >= 0.2 AND expr < 0.3 THEN "[0.2, 0.3)" // 可选:处理超出上述区间的情况 ELSE "Other" END AS expr_interval, c // 按区间分组,统计唯一细胞数量 WITH expr_interval, COUNT(DISTINCT c) AS cell_count // 按区间顺序排序,保证输出逻辑连贯 ORDER BY expr_interval // 合并成你想要的格式字符串 WITH COLLECT("细胞数量:" + cell_count + ",表达量:" + expr_interval) AS result_items RETURN STRING_AGG(result_item, ";") AS final_result
针对所有基因的统计(如果需要全局汇总)
If you want to count cells across all genes (note: a cell may be counted multiple times if it expresses multiple genes), remove the WHERE clause:
MATCH (c:Cell)-[ex:EXPRESSES]->(g:Gene) WITH c, ex.expr AS expr WITH CASE WHEN expr >= 0 AND expr < 0.1 THEN "[0, 0.1)" WHEN expr >= 0.1 AND expr < 0.2 THEN "[0.1, 0.2)" WHEN expr >= 0.2 AND expr < 0.3 THEN "[0.2, 0.3)" ELSE "Other" END AS expr_interval, c WITH expr_interval, COUNT(DISTINCT c) AS cell_count ORDER BY expr_interval WITH COLLECT("细胞数量:" + cell_count + ",表达量:" + expr_interval) AS result_items RETURN STRING_AGG(result_item, ";") AS final_result
关键细节说明
COUNT(DISTINCT c): 确保每个细胞在同一个区间内只被统计一次,避免因数据中存在重复表达记录导致的计数偏差。CASE语句:你可以根据需求调整区间边界,或者添加分支处理负数、NULL等特殊情况(比如WHEN expr IS NULL THEN "NULL")。STRING_AGG: 把所有区间的统计结果合并成一个字符串,完全匹配你期望的输出格式。
示例输出
执行查询后会返回一行结果,格式如下:
细胞数量:20,表达量:[0, 0.1);细胞数量:25,表达量:[0.1, 0.2);细胞数量:10,表达量:[0.2, 0.3)
内容的提问来源于stack exchange,提问作者Nikita Vlasenko

