Skip to content

User Defined Steps

okram edited this page Jan 6, 2011 · 37 revisions

Gremlin provides the ability for a user to define their own step definitions natively in Groovy or in Java. This is very useful when wishing to work with your low-level graph data at a higher level of abstraction. This section will discuss how to write your own step definitions and demonstrate how they are useful for making your Gremlin code more concise and more self-explanatory.

  1. Defining a Step in Gremlin
  2. Defining a Step in Java

Defining a Step in Gremlin

Gremlin comes with a collection of built-in step definitions (see Gremlin Steps). It is possible for developers to create their own step definitions. Simply add a closure that represents the step to the respective classes.

c = { _{x = it}.outE[[label:'created']].inV.inE[[label:'created']].outV{ x != it} }
Pipe.metaClass.co_developer = { Gremlin.compose(delegate, c()) } 
Vertex.metaClass.co_developer = { Gremlin.compose(delegate,c()) }

Given the graph diagrammed in Defining a Property Graph, we can determine the co-developers of a particular vertex.

gremlin> g = TinkerGraphFactory.createTinkerGraph()
==>tinkergraph[vertices:6 edges:6]
gremlin> g.v(1).co_developer
==>v[4]
==>v[6]

Realize that this step definition can be used like any other step definition.

gremlin> g.v(1).co_developer.name
==>josh
==>peter

What step definitions allow you to do is to work with “higher order” relationships in your graph. Thus, instead of working at the level of

_{x = it}.outE[[label:'created']].inV.inE[[label:'created']].outV{ x != it}

you can work at the more semantically natural level of

co_developer

Defining a Step in Java

To ensure speed, it is possible to define steps in Java and then load the paths using import. Here is the previous co-developer path written in Java as a pipe (see Pipes).

public class CoDeveloperPipe extends Pipeline<Vertex,Vertex> {
  public CoDeveloperPipe() {
     Pipe pipe1 = new VertexEdgePipe(Step.OUT_EDGES);
     Pipe pipe2 = new LabelFilterPipe("created", Filter.NOT_EQUALS);
     Pipe pipe3 = new EdgeVertexPipe(Step.IN_VERTEX);
     Pipe pipe4 = new VertexEdgePipe(Step.IN_EDGES);
     Pipe pipe5 = new LabelFilterPipe("created", Filter.NOT_EQUALS);
     Pipe pipe6 = new EdgeVertexPipe(Step.OUT_VERTEX);
     this.setPipes(pipe1, pipe2, pipe3, pipe4, pipe5, pipe6);
   }
}

Make sure that this class is in your Java classpath. If so, you can now include this newly created step/pipe in Gremlin.

Pipe.metaClass.co_developer = { Gremlin.compose(delegate, new CoDeveloperPipe()) } 
Vertex.metaClass.co_developer = { Gremlin.compose(delegate, new CoDeveloperPipe()) }