要使用Apache Tinkerpop Gremlin来使用选择值返回查询结果,您可以使用select()
步骤来选择您感兴趣的属性或值。以下是一个包含代码示例的解决方法:
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerGraph;
public class GremlinExample {
public static void main(String[] args) {
// 创建一个TinkerGraph实例并添加一些顶点和边
TinkerGraph graph = TinkerGraph.open();
Vertex v1 = graph.addVertex("name", "Alice", "age", 30);
Vertex v2 = graph.addVertex("name", "Bob", "age", 35);
v1.addEdge("knows", v2);
// 创建GraphTraversalSource实例
GraphTraversalSource g = graph.traversal();
// 使用选择值返回查询结果
g.V().hasLabel("person")
.has("age", 30)
.as("selectedVertex") // 将当前顶点标记为"selectedVertex"
.out("knows")
.select("selectedVertex") // 选择标记为"selectedVertex"的顶点
.values("name") // 选择"selectedVertex"顶点的"name"属性值
.forEachRemaining(System.out::println);
}
}
在上述示例中,我们首先创建了一个TinkerGraph实例,并添加了两个顶点("Alice"和"Bob")以及一条边("Alice" knows "Bob")。然后,我们创建了一个GraphTraversalSource实例,并使用select()
步骤来选择具有特定年龄的顶点。接下来,我们使用out()
步骤遍历"knows"边,并使用select()
步骤选择先前标记为"selectedVertex"的顶点。最后,我们使用values()
步骤选择"selectedVertex"顶点的"name"属性值,并通过forEachRemaining()
进行打印。
这将输出结果为:
Alice
这是因为我们选择了年龄为30的顶点,并通过边关系遍历到了与之相连的顶点"Bob",然后返回了"Bob"顶点的"name"属性值"Bob"。