Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Find vertices with only incoming edges:
v[2]
v[5]
Find vertices with only outgoing edges:
v[1]
v[3]
v[7]
Find vertices with at most 1 edge on any side:
v[1]
v[3]
v[5]
v[7]
import com.tinkerpop.blueprints.Direction;
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.PipeFunction;
/**
* @author Daniel Kuppitz (daniel at thinkaurelius.com)
*/
public class App {
public static void main(final String[] args) throws Exception {
final Graph g = new TinkerGraph();
final Vertex v1 = g.addVertex(1);
final Vertex v2 = g.addVertex(2);
final Vertex v3 = g.addVertex(3);
final Vertex v4 = g.addVertex(4);
final Vertex v5 = g.addVertex(5);
final Vertex v7 = g.addVertex(7);
v1.addEdge("a", v2);
v3.addEdge("a", v2);
v4.addEdge("a", v5);
v7.addEdge("a", v4);
System.out.println("Find vertices with only incoming edges:");
new GremlinPipeline<Vertex, Vertex>(g).V().filter(new PipeFunction<Vertex, Boolean>() {
@Override
public Boolean compute(final Vertex v) {
return !v.getEdges(Direction.OUT).iterator().hasNext();
}
}).forEach(System.out::println);
// in Java 8:
// new GremlinPipeline<Vertex, Vertex>(g).V().filter(v -> !v.getEdges(Direction.OUT).iterator().hasNext())
// .forEach(System.out::println);
// Find vertices with only outgoing edges:
System.out.println("\nFind vertices with only outgoing edges:");
new GremlinPipeline<Vertex, Vertex>(g).V().filter(new PipeFunction<Vertex, Boolean>() {
@Override
public Boolean compute(final Vertex v) {
return !v.getEdges(Direction.IN).iterator().hasNext();
}
}).forEach(System.out::println);
// in Java 8:
// new GremlinPipeline<Vertex, Vertex>(g).V().filter(v -> !v.getEdges(Direction.IN).iterator().hasNext())
// .forEach(System.out::println);
// Find vertices with at most 1 edge on any side:
System.out.println("\nFind vertices with at most 1 edge on any side:");
new GremlinPipeline<Vertex, Vertex>(g).V().filter(new PipeFunction<Vertex, Boolean>() {
@Override
public Boolean compute(final Vertex v) {
return new GremlinPipeline<>(v).bothE().count() == 1;
}
}).forEach(System.out::println);
// in Java 8:
//new GremlinPipeline<Vertex, Vertex>(g).V().filter(v -> new GremlinPipeline<>(v).bothE().count() == 1)
// .forEach(System.out::println);
}
}
@rajasankar
Copy link

rajasankar commented Jan 13, 2015

Thanks for code Daniel. Will let you know how my POC comes by.

Rajasankar

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment