Showing posts with label groovy. Show all posts
Showing posts with label groovy. Show all posts

Sunday, 17 May 2026

Inspecting Edges Between Vertices in Gremlin

  

In many graph queries, the vertices themselves are only part of the story. Often, the real insight lies in the relationship between two vertices, the edge that connects them and the properties stored on that edge. In Apache TinkerPop, edges are first class elements and can carry rich metadata such as distances, timestamps, weights, roles, or permissions.

 

This post focuses on how to locate, traverse, and inspect edges between specific vertices using Gremlin. You will learn how to move from vertices to edges using steps like outE(), inE(), outV(), and inV(), and how to capture and revisit edges within a traversal using as() and select(). These techniques allow you to precisely target the relationship of interest while filtering vertices along the way.

 

By the end of this post, you will be comfortable treating edges as primary query targets and extracting meaningful relationship data, an essential skill for building expressive, accurate, and efficient Gremlin traversals.

 

1. Building the Sample Graph

Let’s start by creating a small in-memory graph using TinkerGraph.

 

Creating the Graph and Traversal Source

graph = TinkerGraph.open()
g = graph.traversal()

   

Adding Airport Vertices

Each airport is modeled as a vertex with the label airport and a code property.

 

g.addV('airport').property('code','DEL')   // Delhi
g.addV('airport').property('code','BOM')   // Mumbai
g.addV('airport').property('code','BLR')   // Bengaluru
g.addV('airport').property('code','HYD')   // Hyderabad

   

At this point, we have four airport vertices with no relationships between them.

 

Adding Route Edges with Distance

Now we add directed route edges from each city to Delhi, storing the flight distance in kilometers using the dist property.

 

g.V().has('code','BOM').
  addE('route').property('dist',1148).
  to(__.V().has('code','DEL'))

g.V().has('code','BLR').
  addE('route').property('dist',1740).
  to(__.V().has('code','DEL'))

g.V().has('code','HYD').
  addE('route').property('dist',1260).
  to(__.V().has('code','DEL'))

gremlin> g.V().valueMap(true)
==>[id:0,label:airport,code:[DEL]]
==>[id:2,label:airport,code:[BOM]]
==>[id:4,label:airport,code:[BLR]]
==>[id:6,label:airport,code:[HYD]]
gremlin> 
gremlin> 
gremlin> g.E().valueMap(true)
==>[id:8,label:route,dist:1148]
==>[id:9,label:route,dist:1740]
==>[id:10,label:route,dist:1260]

2. Examples

Example1: Find the Route distance from Mumbai to Delhi

g.V().
  hasLabel('airport').
  has('code', 'BOM').
  outE('route').as('e').
  inV().has('code', 'DEL').
  select('e').
  valueMap(true)

gremlin> g.V().
......1>   hasLabel('airport').
......2>   has('code', 'BOM').
......3>   outE('route').as('e').
......4>   inV().has('code', 'DEL').
......5>   select('e').
......6>   valueMap(true)
==>[id:8,label:route,dist:1148]

This confirms that the route edge from BOM DEL has a distance of 1148 km.

 

We can even achieve above result using inE

g.V().
  hasLabel('airport').
  has('code', 'DEL').
  inE('route').as('e').
  outV().has('code', 'BOM').
  select('e').
  valueMap(true)

gremlin> g.V().
......1>   hasLabel('airport').
......2>   has('code', 'DEL').
......3>   inE('route').as('e').
......4>   outV().has('code', 'BOM').
......5>   select('e').
......6>   valueMap(true)
==>[id:8,label:route,dist:1148]

   

Example 2: Inspecting All Incoming Routes to Delhi

If you’re interested in all routes leading to Delhi, you don’t need to traverse back to the source vertex.

 

g.V().
  hasLabel('airport').
  has('code', 'DEL').
  inE('route').
  valueMap(true)

gremlin> g.V().
......1>   hasLabel('airport').
......2>   has('code', 'DEL').
......3>   inE('route').
......4>   valueMap(true)
==>[id:8,label:route,dist:1148]
==>[id:9,label:route,dist:1740]
==>[id:10,label:route,dist:1260]

 

 

Previous                                                    Next                                                    Home

Monday, 6 April 2026

Discovering Gremlin Command Line Options via --help

The Gremlin Console provides a rich set of command-line options that control how the console starts, executes scripts, and reports output. These options are especially useful when integrating Gremlin into automation workflows, debugging scripts, or tailoring the console experience for different environments.

 

To view all supported command-line flags, invoke the console with the --help option:

gremlin.sh --help

$gremlin.sh --help

Usage: gremlin.sh [-CDhlQvV] [-e=<SCRIPT ARG1 ARG2 ...>]... [-i=<SCRIPT ARG1 
                  ARG2 ...>...]...
  -C, --color     Disable use of ANSI colors
  -D, --debug     Enabled debug Console output
  -e, --execute=<SCRIPT ARG1 ARG2 ...>
                  Execute the specified script (SCRIPT ARG1 ARG2 ...) and close
                    the console on completion
  -h, --help      Display this help message
  -i, --interactive=<SCRIPT ARG1 ARG2 ...>...
                  Execute the specified script and leave the console open on
                    completion
  -l              Set the logging level of components that use standard logging
                    output independent of the Console
  -Q, --quiet     Suppress superfluous Console output
  -v, --version   Display the version
  -V, --verbose   Enable verbose Console output

This command prints a usage summary along with a detailed description of each available option.

 

Understanding these command-line flags significantly expands how the Gremlin Console can be used:

 

·      As an interactive exploration tool for learning and experimentation

·      As a script execution engine for automation and testing

·      As a diagnostic utility when investigating configuration or runtime issues

 

In practice, the Gremlin Console is not just a shell for typing traversals, it is a flexible execution environment whose behavior can be precisely controlled from the command line. Mastery of these options enables more efficient workflows and smoother integration with larger data and graph processing systems.

 

Previous                                                    Next                                                    Home

Running Groovy Scripts with the Gremlin Command Line Tool

 The Gremlin Console is most commonly used in interactive mode, where queries are typed and evaluated one at a time. This mode is ideal for exploration, learning, and ad-hoc analysis. However, the console is not limited to interactive usage. It can also execute prewritten Groovy scripts, making it a practical tool for automation, repeatable experiments, and scripted graph operations.

 

Apache TinkerPop provides built-in support for executing Groovy files directly from the command line through the Gremlin Console.

 

Executing a Script and Exiting the Console

To run a Groovy script non-interactively, pass the script file to the Gremlin Console using the -e (execute) option. When invoked this way, the console evaluates the script and then terminates immediately after execution.

 

For example, given a Groovy script named myscript.groovy, it can be executed as follows:

gremlin.sh -e myscript.groovy

In this mode:

 

·      The script is executed in the same environment as an interactive console session.

·      All standard Gremlin objects (such as graph, g, and imports provided by the console) are available.

·      Once the script finishes running, the Gremlin Console exits automatically.

 

myscript.groovy

// ---------------------------------------------
// myscript.groovy
// Simple Gremlin script: graph creation + stats
// ---------------------------------------------

// Create an in-memory TinkerGraph
graph = TinkerGraph.open()
g = graph.traversal()

println "Graph initialized"

// ---------------------------------------------
// Add vertices
// ---------------------------------------------
vHari     = graph.addVertex(label, 'person', 'name', 'Hari',     'age', 30)
vKrishna  = graph.addVertex(label, 'person', 'name', 'Krishna',  'age', 28)
vRam      = graph.addVertex(label, 'person', 'name', 'Ram',      'age', 35)
vSita     = graph.addVertex(label, 'person', 'name', 'Sita',     'age', 32)

println "Vertices added"

// ---------------------------------------------
// Add edges
// ---------------------------------------------
vHari.addEdge('knows', vKrishna, 'since', 2020)
vKrishna.addEdge('knows', vRam, 'since', 2019)
vRam.addEdge('knows', vSita, 'since', 2018)
vHari.addEdge('knows', vSita, 'since', 2021)

println "Edges added"

// ---------------------------------------------
// Print basic graph statistics
// ---------------------------------------------
println "---------------------------------"
println "Graph Statistics"
println "---------------------------------"

println "Total vertices      : " + g.V().count().next()
println "Total edges         : " + g.E().count().next()

println "Person vertices     : " + g.V().hasLabel('person').count().next()
println "Knows relationships : " + g.E().hasLabel('knows').count().next()

println "Average age         : " + g.V().hasLabel('person').values('age').mean().next()

println "---------------------------------"

// ---------------------------------------------
// Print per-vertex degree information
// ---------------------------------------------
println "Vertex Degree Details"
println "---------------------------------"

g.V().hasLabel('person').forEachRemaining { v ->
    def name = v.value('name')
    def outDegree = g.V(v).outE().count().next()
    def inDegree  = g.V(v).inE().count().next()

    println "${name} -> outDegree=${outDegree}, inDegree=${inDegree}"
}

println "---------------------------------"
println "Script execution completed"

 Run the Script.

$gremlin.sh -e myscript.groovy
Graph initialized
Vertices added
Edges added
---------------------------------
Graph Statistics
---------------------------------
Total vertices      : 4
Total edges         : 4
Person vertices     : 4
Knows relationships : 4
Average age         : 31.25
---------------------------------
Vertex Degree Details
---------------------------------
Hari -> outDegree=2, inDegree=0
Krishna -> outDegree=1, inDegree=1
Ram -> outDegree=1, inDegree=1
Sita -> outDegree=0, inDegree=2
---------------------------------
Script execution completed

   

This approach is well suited for:

·      Batch processing of graph mutations

·      Automated data loading or cleanup tasks

·      Running repeatable queries as part of a build or deployment pipeline

 

Conceptually, this usage mirrors running a SQL script against a database from the command line, the script is executed once, produces its effects or results, and the process ends.

 

Executing a Script and Staying in Interactive Mode

In some cases, it is useful to run a script to initialize state and then continue working interactively. For example, a script may load a graph, define helper functions, or configure traversal sources.

 

For this purpose, the Gremlin Console provides the -i (initialize) option. When a script is supplied with -i, the console executes the script and then remains open for further interactive commands.

$gremlin.sh -i myscript.groovy

         \,,,/
         (o o)
-----oOOo-(3)-oOOo-----
plugin activated: tinkerpop.server
plugin activated: tinkerpop.utilities
plugin activated: tinkerpop.tinkergraph
Graph initialized
Vertices added
Edges added
---------------------------------
Graph Statistics
---------------------------------
Total vertices      : 4
Total edges         : 4
Person vertices     : 4
Knows relationships : 4
Average age         : 31.25
---------------------------------
Vertex Degree Details
---------------------------------
Hari -> outDegree=2, inDegree=0
Krishna -> outDegree=1, inDegree=1
Ram -> outDegree=1, inDegree=1
Sita -> outDegree=0, inDegree=2
---------------------------------
Script execution completed
gremlin>

   

With this option:

 

·      The script is executed as part of the console startup sequence.

·      Any variables, functions, or traversal sources defined in the script remain available.

·      The console does not exit, allowing immediate continuation in interactive mode.

 

This pattern is commonly used for:

 

·      Preloading sample datasets

·      Setting up remote connections or traversal aliases

·      Defining reusable Groovy functions for complex traversals

 

Choosing Between -e and -i

The distinction between -e and -i reflects two different usage styles:

 

·      Use -e when the script is the entire task and no further interaction is required.

·      Use -i when the script prepares the environment for an interactive session.

 

Both options enable a smooth transition between scripted automation and exploratory graph work, reinforcing the Gremlin Console’s role as both a development and operational tool within the Apache TinkerPop ecosystem.

 


Previous                                                    Next                                                    Home

Saturday, 8 June 2024

Executing Groovy Scripts from Java: A Comprehensive Guide

In this post, you are going to learn, how to run Groovy scripts in Java.

Groovy

Groovy is an object-oriented programming language for the Java platform. It's known for its ease of use, conciseness, and powerful features. Groovy can easily integrated with Java and allow you to leverage existing Java libraries and frameworks.

 

Use cases of running Groovy Script in Java

1.   Add dynamic scripting capabilities to your Java application.

2.   Use Groovy for tasks that require scripting flexibility and ease.

3.   Leverage Groovy’s concise syntax for rapid prototyping and development.

 

How to run Groovy Script in Java?

Below snippet execute the groovy script from Java.

GroovyShell shell = new GroovyShell();
String script = "println 'Hello, Groovy from Java!'";
shell.evaluate(script);

 

GroovyShell: A simple scripting engine to run Groovy scripts.

evaluate(): A method to execute a script passed as a string.

 

Find the below working application.

 

Step 1: Create new maven project “run-groovy-in-java”.

 

Step 2: Update pom.xml with maven dependencies.

 

pom.xml

 

<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.sample.app</groupId>
	<artifactId>run-groovy-in-java</artifactId>
	<version>0.0.1-SNAPSHOT</version>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<jdk.version>17</jdk.version>
		<release.version>17</release.version>
	</properties>

	<dependencies>
		<!-- https://mvnrepository.com/artifact/org.codehaus.groovy/groovy-all -->
		<dependency>
			<groupId>org.codehaus.groovy</groupId>
			<artifactId>groovy-all</artifactId>
			<version>3.0.21</version>
			<type>pom</type>
		</dependency>

	</dependencies>
	
	<build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>11</source>
                    <target>11</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>3.2.4</version>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                        <configuration>
                            <createDependencyReducedPom>false</createDependencyReducedPom>
                            <transformers>
                                <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                                    <mainClass>com.sample.app.RunGroovyScript</mainClass>
                                </transformer>
                            </transformers>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>

Step 3: Define RunGroovyScript class.

 

RunGroovyScript.java

package com.sample.app;

import groovy.lang.GroovyShell;

public class RunGroovyScript {
    public static void main(String[] args) {
        GroovyShell shell = new GroovyShell();
        String script = "println 'Hello, Groovy from Java!'";
        shell.evaluate(script);
    }
}

Total project structure looks like below.

 



Build the Artifact

Go to the folder, where pom.xml is located and execute the command ‘mvn package’.

 

Upon successful execution of ‘mvn package’ command, you can see a jar file run-groovy-in-java-0.0.1-SNAPSHOT.jar in the target folder.

 

Run the Application

Execute below command from the terminal to run the application.

java -jar ./target/run-groovy-in-java-0.0.1-SNAPSHOT.jar

$ java -jar ./target/run-groovy-in-java-0.0.1-SNAPSHOT.jar 
Hello, Groovy from Java!

You can download this application from this link.

Previous                                                    Next                                                    Home