You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在TinkerPop Gremlin中匹配所有state=3后接state=5的路径

Gremlin查询:匹配所有符合条件的顶点

你的问题根源在于repeat().until()的行为——它会在第一次满足终止条件时停止遍历,没法继续探索后续路径里的匹配顶点。针对你的需求,这里提供两种可行的查询方案:

方案一:遍历所有可达顶点后筛选

这是最直接的写法,先把所有从state=1出发能到达的顶点都找出来,再过滤出符合要求的:

g.V().has('parent', 'state', 1)
  .repeat(out()).emit()
  .has('state', 3)
  .where(out().has('state', 5))
  .valueMap(true)

逻辑拆解:

  • 从state=1的顶点开始遍历
  • repeat(out()).emit()会遍历所有通过follows边能到达的子顶点,不会中途停下
  • 先筛选出state=3的顶点
  • 再用where(out().has('state',5))过滤掉那些不直接连接state=5顶点的项
  • valueMap(true)返回顶点的ID和属性,方便验证结果

方案二:修正你原有的match查询

如果想保留match的结构,可以把终止条件改成遍历到没有出边的顶点,再后续筛选:

g.V().match(
    __.as('x0').hasLabel('parent').has('state', 1),
    __.as('x0').repeat(out()).until(outE().count().is(0)).emit().as('x1'),
    __.as('x1').has('state', 3),
    __.as('x1').out().hasLabel('parent').has('state', 5).as('x2')
  ).select('x1').valueMap(true)

逻辑拆解:

  • 把原查询里的until(has(state,3))换成until(outE().count().is(0)),也就是遍历到没有出边的顶点才停止,这样能收集所有可达顶点
  • 后续依次筛选state=3的x1,以及它的直接邻居是state=5的条件
  • 最后用select('x1')只返回符合要求的state=3顶点

原查询无结果的原因

你的原查询里,repeat(out()).until(has(state,3))会在第一次碰到state=3的顶点(也就是顶点3)时就停止遍历,但顶点3的出边指向的是state=4的顶点,不满足state=5的条件,所以整个match没有匹配项,自然返回空。


内容的提问来源于stack exchange,提问作者Operator

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.12 07:43:22