Quarkus - Neo4j

    Neo4j offers Cypher, a declarative query language much like SQL.Cypher is used to for both querying the graph and creating or updating nodes and relationships.As a declarative language it used to tell the database what to do and not how to do it.

    Clients communicate over the so called Bolt protocol with the database.

    Neo4j - as the most popular graph database according to DB-Engines ranking - provides a variety of drivers for various languages.

    The Quarkus Neo4j extension is based on the official Neo4j Java Driver.The extension provides an instance of the driver configured ready for usage in any Quarkus application.You will be able to issue arbitrary Cypher statements over Bolt with this extension.Those statements can be simple CRUD statements as well as complex queries, calling graph algorithms and more.

    The driver itself is released under the Apache 2.0 license,while Neo4j itself is available in a GPL3-licensed open-source "community edition",with online backup and high availability extensions licensed under a closed-source commercial license.

    The Neo4j extension is based on an alpha version of the Neo4j driver. Some interactions with the driver might change in the future.

    The driver and thus the Quarkus extension support three different programming models:

    • Blocking database access (much like standard JDBC)

    • Asynchronous programming based on JDK’s completable futures and related infrastructure

    • Reactive programming based on

    The reactive programming model is only available when connected against a 4.0+ version of Neo4j.Reactive programming in Neo4j is fully end-to-end reactive and therefore requires a server that supports backpressure.

    In this guide you will learn how to

    • Add the Neo4j extension to your project

    • Configure the driver

    • And how to use the driver to access a Neo4j database

    This guide will focus on asynchronous access to Neo4j, as this is ready to use for everyone.At the end of this guide, there will be a reactive version, which needs however a 4.0 database version.

    The domain

    As with some of the other guides, the application shall manage fruit entities.

    Prerequisites

    To complete this guide, you need:

    • JDK 1.8+ installed with configured appropriately

    • an IDE

    • Apache Maven 3.5.3+

    • Access to a Neo4j Database

    • Optional Docker for your system

    The easiest way to start a Neo4j instance is a locally installed Docker environment.

    1. docker run --publish=7474:7474 --publish=7687:7687 -e 'NEO4J_AUTH=neo4j/secret' neo4j:3.5.6

    Have a look at the download page for other options to get started with the product itself.

    We recommend that you follow the instructions in the next sections and create the application step by step.However, you can go right to the completed example.

    Clone the Git repository: git clone , or download an archive.

    The solution is located in the neo4j-quickstart directory.It contains a very simple UI to use the JAX-RS resources created here, too.

    Creating the Maven project

    First, we need a new project. Create a new project with the following command:

    1. mvn io.quarkus:quarkus-maven-plugin:1.0.0.CR1:create \
    2. -DprojectGroupId=org.acme \
    3. -DprojectArtifactId=neo4j-quickstart \
    4. -Dextensions="neo4j,resteasy-jsonb"
    5. cd neo4j-quickstart

    It generates:

    • the Maven structure

    • a landing page accessible on http://localhost:8080

    • example Dockerfile files for both native and jvm modes

    • the application configuration file

    • an org.acme.datasource.GreetingResource resource

    • an associated test

    The Neo4j extension has been added already to your pom.xml.In addition, we added resteasy-jsonb, which allows us to expose Fruit instances over HTTP in the JSON format via JAX-RS resources.If you have an already created project, the neo4j extension can be added to an existing Quarkus project with the add-extension command:

    1. ./mvnw quarkus:add-extension -Dextensions="neo4j"

    Otherwise, you can manually add this to the dependencies section of your pom.xml file:

    1. <dependency>
    2. <groupId>io.quarkus</groupId>
    3. <artifactId>quarkus-neo4j</artifactId>
    4. </dependency>

    Configuring

    The Neo4j driver can be configured with standard Quarkus properties:

    src/main/resources/application.properties

    1. quarkus.neo4j.uri = bolt://localhost:7687
    2. quarkus.neo4j.authentication.username = neo4j
    3. quarkus.neo4j.authentication.password = secret

    You’ll recognize the authentication here that you passed on to the docker command above.

    Having done that, the driver is ready to use, there are however other configuration options, detailed below.

    General remarks

    The result of a statement consists usually of one or more org.neo4j.driver.Record.Those records contain arbitrary values, supported by the driver.If you return a node of the graph, it will be a org.neo4j.driver.types.Node.

    We add the following method to the Fruit, as a convenient way to create them:

    Add a FruitResource skeleton like this and @Inject a org.neo4j.driver.Driver instance:

    src/main/java/org/acme/neo4j/FruitResource.java

    1. package org.acme.neo4j;
    2. import javax.ws.rs.Consumes;
    3. import javax.ws.rs.Path;
    4. import javax.ws.rs.Produces;
    5. import javax.ws.rs.core.MediaType;
    6. import org.neo4j.driver.Driver;
    7. @Path("fruits")
    8. @Produces(MediaType.APPLICATION_JSON)
    9. @Consumes(MediaType.APPLICATION_JSON)
    10. public class FruitResource {
    11. @Inject
    12. Driver driver;
    13. }

    Reading nodes

    Add the following method to the fruit resource:

    1. @GET
    2. public CompletionStage<Response> get() {
    3. AsyncSession session = driver.asyncSession(); (1)
    4. return session
    5. .runAsync("MATCH (f:Fruit) RETURN f ORDER BY f.name") (2)
    6. .thenCompose(cursor -> (3)
    7. cursor.listAsync(record -> Fruit.from(record.get("f").asNode()))
    8. .thenCompose(fruits -> (4)
    9. session.closeAsync().thenApply(signal -> fruits)
    10. )
    11. .thenApply(Response::ok) (5)
    12. .thenApply(ResponseBuilder::build);
    13. }

    Now start Quarkus in dev mode with:

    1. ./mvnw compile quarkus:dev

    and retrieve the endpoint like this

    1. curl localhost:8080/fruits

    There are not any fruits, so let’s create some.

    The POST method looks similar.It uses transaction functions of the driver:

    src/main/java/org/acme/neo4j/FruitResource.java

    1. @POST
    2. public CompletionStage<Response> create(Fruit fruit) {
    3. AsyncSession session = driver.asyncSession();
    4. return session
    5. .writeTransactionAsync(tx ->
    6. tx.runAsync("CREATE (f:Fruit {name: $name}) RETURN f", Values.parameters("name", fruit.name))
    7. )
    8. .thenCompose(fn -> fn.singleAsync())
    9. .thenApply(record -> Fruit.from(record.get("f").asNode()))
    10. .thenCompose(persistedFruid -> session.closeAsync().thenApply(signal -> persistedFruid))
    11. .thenApply(persistedFruid -> Response
    12. .created(URI.create("/fruits/" + persistedFruid.id))
    13. .build()
    14. );
    15. }

    As you can see, we are now using a Cypher statement with named parameters (The $name of the fruit).The node is returned, a Fruit entity created and then mapped to a 201 created response.

    A curl request against this path may look like this:

    The response contains an URI that shall return single nodes.

    Read single nodes

    This time, we ask for a read-only transaction.We also add some exception handling, in case the resource is called with an invalid id:

    src/main/java/org/acme/neo4j/FruitResource.java

    1. @GET
    2. @Path("{id}")
    3. public CompletionStage<Response> getSingle(@PathParam("id") Long id) {
    4. AsyncSession session = driver.asyncSession();
    5. return session
    6. tx.runAsync("MATCH (f:Fruit) WHERE id(f) = $id RETURN f", Values.parameters("id", id))
    7. )
    8. .thenCompose(fn -> fn.singleAsync())
    9. .handle((record, exception) -> {
    10. if(exception != null) {
    11. Throwable source = exception;
    12. if(exception instanceof CompletionException) {
    13. source = ((CompletionException)exception).getCause();
    14. }
    15. Status status = Status.INTERNAL_SERVER_ERROR;
    16. if(source instanceof NoSuchRecordException) {
    17. status = Status.NOT_FOUND;
    18. }
    19. return Response.status(status).build();
    20. } else {
    21. return Response.ok(Fruit.from(record.get("f").asNode())).build();
    22. }
    23. })
    24. .thenCompose(response -> session.closeAsync().thenApply(signal -> response));
    25. }

    A request may look like this:

    1. curl localhost:8080/fruits/42
    In case Neo4j has been setup as a cluster, the transaction mode is used to decide whether a request is routed to a leader or a follower instance. Write transactions must be handled by a leader, whereas read-only transactions can be handled by followers.

    Deleting nodes

    Finally, we want to get rid of fruits again and we add the DELETE method:

    src/main/java/org/acme/neo4j/FruitResource.java

    1. @DELETE
    2. public CompletionStage<Response> delete(@PathParam("id") Long id) {
    3. AsyncSession session = driver.asyncSession();
    4. return session
    5. .writeTransactionAsync(tx ->
    6. tx.runAsync("MATCH (f:Fruit) WHERE id(f) = $id DELETE f", Values.parameters("id", id))
    7. )
    8. .thenCompose(fn -> fn.consumeAsync()) (1)
    9. .thenCompose(response -> session.closeAsync())
    10. .thenApply(signal -> Response.noContent().build());
    11. }

    A request may look like this

    1. curl -X DELETE localhost:8080/fruits/42

    And that’s already the most simple CRUD application with one type of nodes.Feel free to add relationships to the model.One idea would be to model recipes that contain fruits.The Cypher manual linked in the introduction will help you with modelling your queries.

    Next steps

    Packaging your application is as simple as ./mvnw clean package.It can be run with java -jar target/neo4j-quickstart-1.0-SNAPSHOT-runner.jar.

    With GraalVM installed, you can also create a native executable binary: ./mvnw clean package -Dnative.Depending on your system, that will take some time.

    Explore Cypher and the Graph

    There are tons of options to model your domain within a Graph.The Neo4j docs, the sandboxes and more are a good starting point.

    Going reactive

    If you have access to Neo4j 4.0, you can go fully reactive.

    The make life a bit easier, we will use Project Reactor for this.

    Please add the following dependency management and dependency to your pom.xml

    1. <dependencyManagement>
    2. <dependencies>
    3. <dependency>
    4. <groupId>io.projectreactor</groupId>
    5. <artifactId>reactor-bom</artifactId>
    6. <version>Californium-SR4</version>
    7. <type>pom</type>
    8. <scope>import</scope>
    9. </dependency>
    10. </dependencies>
    11. </dependencyManagement>
    12. <dependencies>
    13. <dependency>
    14. <groupId>io.projectreactor</groupId>
    15. <artifactId>reactor-core</artifactId>
    16. </dependencies>

    The reactive fruit resources streams the name of all fruits:

    src/main/java/org/acme/neo4j/ReactiveFruitResource.java

    Configuration Reference

    Configuration property fixed at build time - ️ Configuration property overridable at runtime

    TypeDefault
    The uri this driver should connect to. The driver supports bolt, bolt+routing or neo4j as schemes.stringbolt://localhost:7687
    TypeDefault
    The login of the user connecting to the database.stringneo4j
    The password of the user connecting to the database.stringneo4j
    Set this to true to disable authentication.booleanfalse
    TypeDefault
    Flag, if metrics are enabled.booleanfalse
    Flag, if leaked sessions logging is enabled.booleanfalse
    The maximum amount of connections in the connection pool towards a single database.int100
    Pooled connections that have been idle in the pool for longer than this timeout will be tested before they are used again. The value 0 means connections will always be tested for validity and negative values mean connections will never be tested.Duration-0.001S
    Pooled connections older than this threshold will be closed and removed from the pool.Duration1H
    Acquisition of new connections will be attempted for at most configured timeout.Duration1M