Introduction
In the Cypher Fundamentals course, you learned how to query Neo4j using Cypher.
To run Cypher statements in a Java application, you’ll need the Neo4j Java Driver. The driver acts as a bridge between your Java code and Neo4j, handling connections to the database and the execution of Cypher queries.
Creating a Driver Instance
Open the src/main/java/com/neo4j/app/App.java
file.
Import the driver:
import org.neo4j.driver.GraphDatabase;
import org.neo4j.driver.AuthTokens;
Creating a Driver Instance
Create a driver
instance in main()
:
public class App {
public static void main(String[] args) {
AppUtils.loadProperties();
// Create a new Neo4j driver instance
var driver = GraphDatabase.driver(
System.getProperty("NEO4J_URI"), // (1)
AuthTokens.basic(
System.getProperty("NEO4J_USERNAME"), // (2)
System.getProperty("NEO4J_PASSWORD"))
);
}
}
-
The connection string for your Neo4j database
-
Your Neo4j username and password
Best Practice
Create one Driver instance and share it across your entire application.
Verifying Connectivity
You can verify the connection by calling the verifyConnectivity()
method.
driver.verifyConnectivity();
Verify Connectivity
The verifyConnectivity()
method will raise an exception if the connection cannot be made.
Running Your First Query
The executableQuery()
method executes a Cypher query and returns the results.
// (1)
var result = driver.executableQuery(
"RETURN COUNT {()} AS count"
).execute();
// Get the first record
var records = result.records(); // (2)
var first = records.get(0);
// Print the count entry
System.out.println(first.get("count")); // (3)
-
executableQuery()
runs a Cypher query to get the count of all nodes in the database -
records()
returns a list of the records returned -
Keys from the
RETURN
clause are accessed using theget
method
Full driver lifecycle
Once you have finished with the driver, call close()
to release any resources held by the driver.
driver.close();
Run the application
You can run the application to see the output:
./mvnw compile exec:java -Dexec.mainClass="com.neo4j.app.App"
Try with resources
You can use try-with-resources
to automatically close the driver when the block is exited.
try (
var driver = GraphDatabase.driver(
System.getProperty("NEO4J_URI"),
AuthTokens.basic(
System.getProperty("NEO4J_USERNAME"),
System.getProperty("NEO4J_PASSWORD"))
)
) {
driver.verifyConnectivity();
var result = driver.executableQuery(
"RETURN COUNT {()} AS count"
).execute();
}
Check your understanding
Lesson Summary
In this lesson you learned how to install the Neo4j Java Driver, create a Driver instance, verify connectivity to your database, and execute your first Cypher statement.
For async applications, use the AsyncGraphDatabase
method.
In the next lesson, you will take a quiz to test your knowledge of installing and creating a driver instance.