GREMLIN API使用choose步骤查询图数据库时出现数据不匹配问题

上图为图数据库的局部结构,需求是通过关联的detail顶点的name属性搜索product顶点,输出所有关联name为test3的detail的产品及其详情列表。
问题原因
数据不匹配的核心是Gremlin的遍历结果复用机制:你写的choose分支中,variable类型对应的out('value').valueMap(true)如果没有返回有效结果,Gremlin会默认复用最近一次遍历输出的有效值(也就是第一个detail条目的value值1583884800),最终导致第二个条目的value字段错误。
另外原查询存在重复的in()查询逻辑,也会提升遍历上下文串扰的概率。
修复方案
按如下规则调整查询即可解决问题:
- 给需要走边查询的
choose分支添加兜底逻辑,确保无匹配时也有明确返回值,避免结果复用 - 优化遍历路径,提前缓存父顶点减少重复查询
- 给
choose补充默认分支,覆盖未匹配的label、type场景
修改后的查询语句如下:
g .V() .hasLabel(within( 'data_computed_property', 'data_variable','recipe_ingredient', 'cost_setting_variable','benefit_analysis_variable', 'formula', 'detail' )) .has('name', 'test3') .where(__.as('v').in().hasLabel(within('product','recipe','machine')).as('parent') .in().hasId('13eec000-78fa-41fd-856b-bbc37711b1f0')) .project('parent','property') .by(select('parent').valueMap(true)) .by( choose(label()) .option('detail', project('detail','value') .by(valueMap(true)) .by( choose(values('type')) .option('string', values('value')) .option('number', values('value')) .option('date', values('value')) .option('formula', out('value').valueMap(true).fold().coalesce(unfold(), constant([:]))) .option('condition', out('value').valueMap(true).fold().coalesce(unfold(), constant([:]))) .option('variable', out('value').valueMap(true).fold().coalesce(unfold(), constant([:]))) .option('element', out('value').valueMap(true).fold().coalesce(unfold(), constant([:]))) .option(none, constant(null)) ) ) .option('data_computed_property', valueMap(true)) .option('data_variable', valueMap(true)) .option('recipe_ingredient', valueMap(true)) .option('cost_setting_variable', valueMap(true)) .option('benefit_analysis_variable', valueMap(true)) .option('formula', valueMap(true)) .option(none, constant([:])) )
调整后variable类型的detail会正确返回关联的cost_setting_variable顶点属性,不会复用前一个条目的值,完全匹配预期输出要求。
内容的提问来源于stack exchange,提问作者ephraim lambarte
相关产品推荐
相关产品推荐

