Setup Azure Cosmos DB for Gremlin in Spring Boot Java
Tags: database, java, springboot, azure
Published: 2024-05-01 04:45:40

[Azure Cosmos DB](https://learn.microsoft.com/en-us/azure/cosmos-db/introduction) is a fully managed NoSQL, relational, and vector database for modern app development. It handles all the database administration with automatic management, updates, and patching. It also handles capacity management with serverless and automatic scaling options to match capacity and demand of your application.

Azure Cosmos DB has multiple database APIs, including NoSQL, MongoDB, PostgreSQL, Cassandra, Gremlin, and Table. This guide will focus on setting up Azure Cosmos DB with the Gremlin API to store and access data from a Spring Boot application in Java.

The API for Gremlin is built based on [Apache TinkerPop](https://tinkerpop.apache.org/), a graph computing framework that uses the Gremlin query language. 

###Prerequisites

- An Azure Cosmos DB account 
  - Gremlin Database and Collection Created
- JDK 1.7+, but we'll use JDK 21
- Maven

In this example, I have a Cosmos DB Gremlin account with a database called `graphdb` and a collection called `Persons`. 

###Spring Boot Starter
Next step is to create a spring boot project using the Spring Initializr tool with the following options:
- Java 21
- Maven
- Jar Packaging

Add Spring Web as a dependency, then create. 

Once the spring boot project has been created, add the `gremlin-driver` dependency to the pom.xml:

```
<dependency>
    <groupId>org.apache.tinkerpop</groupId>
    <artifactId>gremlin-driver</artifactId>
    <version>3.7.2</version>
</dependency>
```
Make sure everything is installed and the build succeeds:
```bash
mvn clean install
```

Navigate to `src/main/resources/application.yml`. If `application.yml` doesn't exist, create it.
Add the following:
```
cosmosdb:
  host: ${GREMLIN_HOST} #cosmos db host (ex: <account-name>.gremlin.cosmos.azure.com)
  key: ${GREMLIN_KEY} #cosmos db key
  port: 443
  database: graphdb #database name
  collection: Persons #collection name
```

In the directory where your `SpringBootApplication` class is, create a class called `GremlinConfig` with the following code:
```
@Configuration
public class GremlinConfig {

    @Value("${cosmosdb.host}")
    private String gremlinHost;
    @Value("${cosmosdb.key}")
    private String gremlinKey;
    @Value("${cosmosdb.port}")
    private int port;
    @Value("${cosmosdb.database}")
    private String database;
    @Value("${cosmosdb.collection}")
    private String collection;

    @Bean
    public Client gremlinClient() {
        String username = "/dbs/%s/colls/%s".formatted(database, collection);
        Cluster cluster = Cluster.build()
                .addContactPoint(gremlinHost)
                .port(port)
                .credentials(username, gremlinKey)
                .enableSsl(true)
                .serializer(Serializers.GRAPHSON_V2)
                .create();
        return cluster.connect();
    }
}
```
This creates a gremlin client bean, using the values from `application.yml`. The client communicates with your gremlin database and can be used throughout your application. 

Next, create a class called `PersonsController`. This will be the REST Controller with a GET endpoint that will retrieve a Vertex given an id.

```
@RestController
public class PersonsController {

    private final Client client;

    public PersonsController(Client client) {
        this.client = client;
    }

    @GetMapping("/{name}")
    public String getPerson(@PathVariable("name") String name) {
        ResultSet results = client.submit("g.V('%s')".formatted(name));
        Result result = results.one();
        return result.getString();
    }
}
```
Once you've added this, you can test to see if everything works. After you define the `GREMLIN_HOST` and `GREMLIN_KEY` environment variables, run the spring boot application.

Assuming you have a vertex in your collection with an id of "Test", you can request the url: `localhost:8080/Test', and it should return the vertex, along with it's properties if any. 

To learn more about Tinkerpop and the Gremlin query language: https://tinkerpop.apache.org/docs/current/tutorials/getting-started/

This Github repository has all code needed to run this example: https://github.com/juhlmann75/cosmosdb-gremlin-spring-boot-starter