Gremlin查询优化咨询:按类型统计各类Post顶点数量
优化Gremlin帖子类型统计查询的方案
你的原查询存在几个明显的性能和冗余问题:
- 每次调用
.V()都会触发一次全图遍历,数据量增大后性能损耗会非常明显 - 重复统计了
post_gallery类型,做了无用功 - 用
store+cap的方式映射结果,写法繁琐且不直观
下面是两种更高效简洁的优化方案:
方案一:批量统计后映射结构(推荐)
利用groupCount一次性按type属性统计所有类型的数量,再转换成你需要的结构化响应,全程仅需一次全图遍历:
let data = await g .V() // 可选:限定要统计的顶点标签,过滤无关顶点进一步提升性能 .hasLabel(within('post_article', 'post_chirpy', 'post_gallery', 'post_shout', 'post_forum', 'post_poll', 'groups')) .groupCount() .by('type') .map(m -> project('total_articles', 'total_chirpies', 'total_events', 'total_shouts', 'total_forums', 'total_galleries', 'total_polls', 'total_groups') // coalesce处理某类帖子数量为0的情况,避免返回null .by(select('post_article').coalesce(__, constant(0))) .by(select('post_chirpy').coalesce(__, constant(0))) .by(select('post_gallery').coalesce(__, constant(0))) // 注意:原查询中total_events对应post_gallery大概率是笔误,若实际为post_event类型请替换 .by(select('post_shout').coalesce(__, constant(0))) .by(select('post_forum').coalesce(__, constant(0))) .by(select('post_gallery').coalesce(__, constant(0))) .by(select('post_poll').coalesce(__, constant(0))) .by(select('groups').coalesce(__, constant(0))) ) .next();
方案二:聚合后单独统计(适合需自定义逻辑的场景)
如果某些类型需要单独调整统计逻辑,可以先聚合所有目标顶点,再逐个统计:
let data = await g .V() .has('type', within('post_article', 'post_chirpy', 'post_gallery', 'post_shout', 'post_forum', 'post_poll', 'groups')) .fold() // 先将所有符合条件的顶点收集到一个列表 .project('total_articles', 'total_chirpies', 'total_events', 'total_shouts', 'total_forums', 'total_galleries', 'total_polls', 'total_groups') .by(unfold().has('type', 'post_article').count()) .by(unfold().has('type', 'post_chirpy').count()) .by(unfold().has('type', 'post_gallery').count()) .by(unfold().has('type', 'post_shout').count()) .by(unfold().has('type', 'post_forum').count()) .by(unfold().has('type', 'post_gallery').count()) .by(unfold().has('type', 'post_poll').count()) .by(unfold().has('type', 'groups').count()) .next();
额外优化建议
- 务必给
type属性创建索引,这样has('type', ...)的查询会跳过全图扫描,大幅提升速度 - 原查询中
total_events对应post_gallery明显不合理,检查是否是post_event类型的笔误,避免统计结果错误
内容的提问来源于stack exchange,提问作者Hari Krishnan Ramachandran
相关产品推荐
相关产品推荐

