如何通过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
matchblock finds edges fromsourceto 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 edgesuntil(has('tag','person'))stops as soon as we hit another person vertex- The
whereclause 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., onlyout()orin()instead ofboth()). - If you need to include both incoming and outgoing edges, replace
out()withboth(). - For large graphs, always add constraints (like length limits) to prevent performance issues from infinite traversals.
内容的提问来源于stack exchange,提问作者Jeff
相关产品推荐
相关产品推荐

