25+ Handy Gremlin Examples and Code Snippets for Graph Database Traversal and Manipulation

Gremlin Examples and Code Snippets
Gremlin is a powerful domain specific traversal language for graph databases. This language is supported by all popular graph databases.

In recent past, I was doing some case studies on graph databases and realized that gremlin is the graph language that I must learn. Learning this language can ensure you to be able to work on multiple graph databases.

Gremlin works smoothly on all graph databases that support Blueprints property graph data model. Gremlin can be easily used with JVM languages like Groovy, Clojure, Scala and more.

A lot of graph databases support their custom languages (e.g. Cipher in Neo4j). These languages are really useful, however they become useless on other databases.

Learning Gremlin for graph databases is equivalent to learning SQL for relational databases. Once you know SQL, you can easily work on MySQL or Postgres or Oracle without worrying about details of vendors. Same way knowing Gremlin can ensure you can work on Neo4j or Titan Graph DB, or OrientDB and other dozens of graph databases.

In this simple code snippets collection, I am trying to list down all commonly used snippets that you can use as a cheatsheet while doing graph query, analysis and manipulation.

Some Useful Graph Traversal Queries

These queries are focused on reading the data from a graph database. We have taken simple examples to demonstrate the commands, however you can try various complex combinations and come up with really complex queries.

Simple graph used in most of the queries on this page

Get A Vertex By Its Id

This is probably the simplest query. Make sure the "v" in query is lower case. The upper case "V" has different use.


Get All The Vertices With ID Range

Lets say you want to get all the vertex that has id in the range of 1 to 100

To get the vertex object itself you can use below query

To get a specific attribute of each vertex, lets say firstName. You can use below query


Get The Attribute Of A Vertex By Its Id

Lets say the attribute name is "firstName" then we can use below query to find first name of a vertex id 1


This can be done with any custom attribute you may have added in your node. Lets say "lastName" can be obtained by this


Get A Vertex By An Attribute

Lets say we want to find a vertex (or all vertices) that have "firstName" as "John", below query can be used.
Note the V in this case is upper case. The lowercase v will not work with attribute query.


Get The Id Of A Vertex By An Attribute

id attribute is a inbuilt attribute that is always available for any vertex. So even if you did not add a id attribute, graph db is going to assign at value to uniquely identify a vertex. You can find out the id of a vertex by this query.


Get The Count Of Vertices With A Attribute Value

Lets say you just want to know how may people in you database with first name "John". This simple query can be done like below.


Get The Edge Of A Vertex With A Label "friend"

Now starts the real fun with graph language. You may already know that you can have outgoing or incoming relations in a graph.

Lets say you want to know all the out going edges with label "friend" .


Lets say you want to know all the in coming edges with label "friend" .


Lets say you want to know all the in coming and out going edges with label "friend" .


Get The Count Of Edges Of A Vertex With Label "friend"

Count is a useful function that can be applied on vertices and edges to count them instead of getting the object itself.

Lets say you want to know, how many friends are connected to a node id 1


Get The Label Of All Out Going Edges Of A Vertex

Just like vertex, you can also fetch the attributes of any edge using the name of the attribute.


Get The Count Of All Out Going Edges Of A Vertex

Lets say you want to know, how many edges are connected to a node id 1 (irrespective of relation label)


Get The First Names Of All People That Are Connected By A Friend Relation

This query should return the first names of all people that are friend to a vertex id 1


Get The Age Of All Friends

In this queury we can get the age of all people that are connected to a person (with last name 'Doe') by a friend relation
This is another combination to demonstrate the starting point can be a property and any attribute of a connected vertex can be obtained. For example we are extracting age of all friends of all persons that have last name Doe.


Get All Friends With Age 25

In this example you can get first name of all friends of a vertex id 1 that are connected by a friend relation


Find All People That Have Age Greater Than 25

This may be a really common scenario, where you may want to target people with specific age group.

g.V.filter{it.age > 25}.firstName

Find All People That Have Age Greater Than 25 And Less Than 35

g.V.and(_().has("age", T.gt, 25), _().has("age", T.lt, 35));

or a simpler alternative exists with interval function

g.V.interval("age", 25, 35);

Get All People That Have Email Address

This is a reverse approach for checking all the people do not have email address as null

g.V.hasNot('email', null)

On the other hand you can do the opposite very easily to find people who do not have email address by simply using has function instead of hasNot

g.V.has('email', null)

Get Unique Results On A Complex Query

This can be done by the dedup function.


Get The Count Of Unique Results On A Complex Query

This can be achieved easily by using count function.


Graph Manipulation Queries In Gremlin

These queries can be used to do manipulation of graph from the gremlin console or api.

Add A New Vertex In The Graph


Add Two New Vertex And A Relation (with Label 'friend') Between Them

This will require multiple statements. Note how the variables (jdoe and mj) are defined just by assigning them a value from gremlin query.

jdoe = g.addVertex([firstName:'John',lastName:'Doe',age:'25']);
mj = g.addVertex([firstName:'Mary',lastName:'Joe',age:'21']);

Add A Relation Between Two Existing Vertices With Id 1 And 2


Remove All Vertices From The Graph


Remove All Edges From The Graph


Remove All Vertices With FirstName = 'John'


Remove A Vertex With Id 1


Remove An Edge With Id 1


Create A Index Using Gremlin

This is to index the graph with specific field you may want to search frequently. Lets say "myfield"


Note: The index creation can be done for not existing fields therefore incase you want to create a index for existing fields you may need to delete all and then create index.

I have recently started using gremlin and had tough time figuring out a few simple things on it. This language may be more intuitive for people who understand languages like groovy or scala.

I have tried these queries thru Rexster (server version 2.3.0) gremlin console with Neo4j (version 1.8.2) as backend, however these should be functional in any other Blueprints graph like Titan or OrientDB or later versions of Neo4j as well.

Let me know your inputs if you see any issues on other databases.

Can you think of more gremlin queries? Feel free to suggest in comments section.


Tutorials 8775128658554680801

Post a Comment Default Comments