Skip to content

Neo4j with the Java driver

Uses neo4j-java-driver 6.3. The code is an ordinary application for the original database; nothing in it knows about MachNoSQL.

neo4j://neo4j.example.com:7687
neo4j://machnosql.example.com:7687

The address comes from the environment variable NEO4J_URI, so switching to MachNoSQL changes configuration only.

Terminal window
export NEO4J_URI='neo4j://machnosql.example.com:7687'
mvn -q compile exec:java

Credentials come from NEO4J_USERNAME and NEO4J_PASSWORD.

The program as it is kept and tested in the Mach Database NoSQL repository; highlighted lines read the connection setting.

src/main/java/example/App.java
// Friends of friends on Neo4j, unchanged on MachNoSQL.
package example;
import java.util.List;
import java.util.Map;
import org.neo4j.driver.AuthTokens;
import org.neo4j.driver.Driver;
import org.neo4j.driver.GraphDatabase;
public final class App {
public static void main(String[] args) {
var auth = AuthTokens.basic(System.getenv("NEO4J_USERNAME"), System.getenv("NEO4J_PASSWORD"));
try (Driver driver = GraphDatabase.driver(System.getenv("NEO4J_URI"), auth)) {
driver.verifyConnectivity();
var pairs = List.of(List.of("ada", "grace"), List.of("grace", "linus"),
List.of("grace", "margaret"), List.of("linus", "ken"));
driver.executableQuery("UNWIND $pairs AS pair MERGE (a:Person {name: pair[0]}) MERGE (b:Person {name: pair[1]}) MERGE (a)-[:KNOWS]->(b)")
.withParameters(Map.of("pairs", pairs))
.execute();
var result = driver.executableQuery("MATCH (p:Person {name: $name})-[:KNOWS]->()-[:KNOWS]->(fof) WHERE fof <> p RETURN DISTINCT fof.name AS name ORDER BY name")
.withParameters(Map.of("name", "ada"))
.execute();
result.records().forEach(record -> System.out.println(record.get("name").asString()));
}
}
}
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<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.example.machnosql</groupId>
<artifactId>neo4j-example</artifactId>
<version>1.0</version>
<properties>
<maven.compiler.release>21</maven.compiler.release>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<exec.mainClass>example.App</exec.mainClass>
</properties>
<dependencies>
<dependency>
<groupId>org.neo4j.driver</groupId>
<artifactId>neo4j-java-driver</artifactId>
<version>6.3.0</version>
</dependency>
</dependencies>
</project>