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

如何通过Gremlin获取指定顶点及顶点间的全部路径?

获取Person顶点间所有路径的Gremlin方案

Got it, let's break this down for you. You want to first grab all vertices tagged person, then find every possible path between those person vertices—here's how to do it in Gremlin, with variations for different scenarios:

1. 直接相邻的Person顶点路径(一步跳转)

If you only need paths between directly connected person vertices (one edge apart), use the match step to precisely target these relationships:

g.V().has('tag','person').as('source').
  match(
    __.as('source').outE().inV().has('tag','person').as('target'),
    __.path().from('source').to('target')
  ).
  select('path')

Quick breakdown:

  • First, we mark all person vertices as source
  • The match block finds edges from source to another person vertex (target)
  • Finally, we extract and return these direct paths

2. 任意长度的Person顶点路径

For multi-step paths (like Alice → Bob → Charlie, where all are person vertices), use repeat + until to recursively traverse the graph:

g.V().has('tag','person').as('start').
  repeat(out()).
    until(has('tag','person')).
  path().
    where(neq('start', end)) // Remove this line if you want to include self-loop paths (e.g., Alice→Bob→Alice)

Quick breakdown:

  • repeat(out()) keeps traversing outgoing edges
  • until(has('tag','person')) stops as soon as we hit another person vertex
  • The where clause filters out paths that start and end at the same vertex (self-loops)

3. 带长度限制的路径

If you want to cap the maximum number of steps (e.g., no more than 3 hops), add a loop limit to the until condition:

g.V().has('tag','person').as('start').
  repeat(out()).
    until(has('tag','person').or().loops().is(3)). // Stop at person vertex OR after 3 steps
  path().
    where(has('tag','person', end)). // Ensure the final vertex is a person
    where(neq('start', end))

实用小提示

  • To avoid duplicate paths (like Alice→Bob and Bob→Alice), add dedup() at the end, or stick to one traversal direction (e.g., only out() or in() instead of both()).
  • If you need to include both incoming and outgoing edges, replace out() with both().
  • For large graphs, always add constraints (like length limits) to prevent performance issues from infinite traversals.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:14:09