如何通过Gremlin获取遍历过程中经过的边?基于TinkerPop Modern示例
Got it, let's break down how to get exactly the output format you need for the TinkerPop Modern graph. The goal is to capture every traversal path, extract the edge labels (your relation field), vertex IDs, and vertex names (your title field) in that structured dictionary format.
Core Query Solution
Here's a Gremlin query that does exactly what you're asking for. It works by traversing all possible paths (with at least one edge), then projecting the required fields from each path:
g.V() .repeat(outE().inV()) .emit() .path() .project('relation', 'id', 'title') .by(path().objects().is(Edge).label().fold()) .by(path().objects().is(Vertex).id().fold()) .by(path().objects().is(Vertex).values('name').fold())
Let's Walk Through What This Does
g.V(): Starts traversal from every vertex in the TinkerPop Modern graph. If you want to start from a specific vertex (e.g., Vadas), replace this withg.V(<vertex-id>)(likeg.V(2)for Vadas).repeat(outE().inV()).emit(): Repeatedly traverses outgoing edges to adjacent vertices, and emits every path that has at least one edge (so we don't get empty paths). Add.times(N)insiderepeat()if you want to limit path length (e.g.,.times(4)for max 4 edges in a path).path(): Captures the full traversal path, which includes both vertices and edges in the order they were traversed.project('relation', 'id', 'title'): Builds the output structure with your three required fields:by(path().objects().is(Edge).label().fold()): Extracts all edges from the path, grabs their labels (likeknowsorcreated), and folds them into a list for therelationfield.by(path().objects().is(Vertex).id().fold()): Extracts all vertices from the path, grabs their unique IDs, and folds them into a list for theidfield.by(path().objects().is(Vertex).values('name').fold()): Extracts all vertices from the path, grabs theirnameproperty (Marko, Vadas, etc.), and folds them into a list for thetitlefield.
Example Output (Matching Your Format)
For the path Vadas → Marko → Josh → Ripple, the query will return:
{"relation": ["knows", "knows", "created"], "id": [2, 1, 3, 5], "title": ["vadas", "marko", "josh", "ripple"]}
(Note: The IDs here match TinkerPop Modern's default IDs; your example uses different numeric IDs, which just reflects your graph's actual storage IDs—this query will pull whatever IDs exist in your graph.)
Alternative for Graphs That Don't Support is(Vertex)/is(Edge)
If your graph database doesn't support checking element types directly, you can filter by label instead (since TinkerPop Modern uses person/software for vertices and knows/created for edges):
g.V() .repeat(outE().inV()) .emit() .path() .project('relation', 'id', 'title') .by(path().objects().hasLabel(within('knows','created')).label().fold()) .by(path().objects().hasLabel(within('person','software')).id().fold()) .by(path().objects().hasLabel(within('person','software')).values('name').fold())
内容的提问来源于stack exchange,提问作者Srinath Ganesh

