有多种方法可以实现这一点。如果您真的想将人和车辆混在一个列表中,您可以使用store管道:
list = []
pipe.has("name", "NY").in("lives").has("gender", "male").store(list).out('owns').store(list).iterate()
list
如果您希望维护人与他们(可能有多辆)汽车之间的关系,则建议创建人与汽车之间的映射:
pipe.has("name", "NY").in("lives").has("gender", "male").groupBy{it.name}{it.out('owns')}.cap()
以下是一个完整的Java类,使用Tinkerpop图实现了所有三种方法。
import com.tinkerpop.blueprints.Graph;
import com.tinkerpop.blueprints.Vertex;
import com.tinkerpop.blueprints.impls.tg.TinkerGraph;
import com.tinkerpop.gremlin.java.GremlinPipeline;
import com.tinkerpop.pipes.util.PipesFunction;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class Foo
{
private static final PipesFunction<Vertex, String> NAME_FUNCTION = new PipesFunction<Vertex, String>()
{
@Override
public String compute(Vertex vertex)
{
return vertex.getProperty("name");
}
};
private static final PipesFunction<Vertex, Iterable<String>> OWNS_NAME_FUNCTION = new PipesFunction<Vertex, Iterable<String>>()
{
@Override
public Iterable<String> compute(Vertex vertex)
{
return new GremlinPipeline(vertex).out("owns").property("name");
}
};
public static void main(String[] args)
{
Graph graph = new TinkerGraph();
Vertex boy1 = graph.addVertex(1);
Vertex boy2 = graph.addVertex(2);
Vertex girl = graph.addVertex(3);
Vertex ny = graph.addVertex(4);
Vertex toyota = graph.addVertex(5);
Vertex tesla = graph.addVertex(6);
boy1.setProperty("type", "Person");
boy1.setProperty("name", "xyz");
boy1.setProperty("gender", "male");
boy2.setProperty("type", "Person");
boy2.setProperty("name", "abc");
boy2.setProperty("gender", "male");
girl.setProperty("type", "Person");
girl.setProperty("name", "def");
girl.setProperty("gender", "female");
ny.setProperty("type", "City");
ny.setProperty("name", "NY");
toyota.setProperty("type", "Car");
toyota.setProperty("name", "toyota");
toyota.setProperty("color", "red");
tesla.setProperty("type", "Car");
tesla.setProperty("name", "tesla");
toyota.setProperty("color", "white");
boy1.addEdge("lives", ny);
boy1.addEdge("owns", tesla);
boy2.addEdge("lives", ny);
boy2.addEdge("owns", toyota);
girl.addEdge("lives", ny);
girl.addEdge("owns", tesla);
GremlinPipeline pipe = new GremlinPipeline(graph.getVertices("type", "City"));
pipe = pipe.has("name", "NY").in("lives").has("gender", "male");
for (Object o : pipe)
{
System.out.println(o.toString());
}
List list = new ArrayList();
pipe = new GremlinPipeline(graph.getVertices("type", "City"));
pipe.has("name", "NY").in("lives").has("gender", "male").store(list, NAME_FUNCTION).out("owns").store(list, NAME_FUNCTION).iterate();
System.out.println(list);
pipe = new GremlinPipeline(graph.getVertices("type", "City"));
Map map = (Map) pipe.has("name", "NY").in("lives").has("gender", "male").groupBy(NAME_FUNCTION, OWNS_NAME_FUNCTION).cap().next();
System.out.println(map);
}
}