Working with the Neo4J Java Driver

Connections and Sessions

Connections are managed behind the scenes in a pool by the driver. As final user, you should work with Sessions instead.

// 1 Create a driver instance
AuthToken auth = AuthTokens.basic(
  "<your_username>",
  "<your_password>"
);
Driver driver = GraphDatabase.driver("neo4j://<your_ip>:<port>", auth);
driver.verifyConnectivity();

// ...

// 2. Now use driver to create a session
//.    try...finally will take care of releasing session resources
try (Session session = driver.session()) {
  // Your transaction code goes here
  // ...
}

Transactions

Driver will work the same for clustered or individual database deployments, there are read and write transactions.

Read transaction

// Write your cypher query as String
String findDir = "MATCH (d:Directory {path: $path}) RETURN d";

return session.executeRead(tx -> {
  
  	// Execute query and pass values for named parameters
    var res = tx.run(
      findDir,
      Values.parameters("path", path)
    );

  	// Retrieve single Record result and then get
    // properties as a Map
    if (res.hasNext()) {
        return rowMapper.from(res.single().get("d").asMap());
    }

    return null;
});

Write transaction

String mergeDir = """
    MERGE (d:Directory { path: $path })
    ON CREATE
        SET
            d.recursive = $recursive,
            d.status = $status
    ON MATCH
        SET
            d.recursive = $recursive,
            d.status = $status;
""";

// Pretty similar to 'read' query, you can pass values for
// named parameters as a map
session.executeWriteWithoutResult(tCtx -> tCtx.run(
  	mergeDir,
    rowMapper.asMap(directory)
));

Neo4J Type System

Even though Neo4j is written in Java, not all Cypher types map directly into a Java type.

Java Type Cypher Type Notes
null null
List List, Array Neo4j can only store a flat array containing strings, booleans or numbers.
Map Map
Boolean Boolean
Long Integer
Double Float
String String
byte[] byte[]
LocalDate LocalDate See Temporal Types
Time Time See Temporal Types
LocalTime LocalTime See Temporal Types
DateTime DateTime See Temporal Types
LocalDateTime LocalDateTime See Temporal Types
IsoDuration Duration
Point Point
Node Node See Nodes & Relationships
Relationship Relationship See Nodes & Relationships
Path Path See Nodes & Relationships

Reference: https://neo4j.com/docs/java-manual/current/data-types/