Overview: Neo4j JDBC Driver
This is the official JDBC driver for Neo4j.
This driver was mainly developed by Larus BA, Italy, a certified consulting and integration solutions partner for Neo4j. Thank you so much for all your work.
Being a graph database, Neo4j is not serving data in a relational way, nevertheless thanks to this driver it’s possible for projects that are using the classic JDBC connector in the relational paradigm to interact with Neo4j.
This driver supports various types of database transports, through:
-
The
Bolt
protocol usingjdbc:neo4j:bolt://<host>:<port>/
from Neo4j 3.0+ -
The
Bolt+Routing
protocol usingjdbc:neo4j:bolt+routing://<host>:<port>/
from Neo4j 3.1+ -
The
HTTP
protocol usingjdbc:neo4j:http://<host>:<port>/
from Neo4j 2.0+
Going forward there will also be support for:
-
direct file connection
-
embedded connection
Note
|
The previous JDBC driver for Neo4j 2.x was moved to the https://github.com/neo4j-contrib/neo4j-jdbc-2x repository. |
Maven dependency
For the all-in-one module supporting both Bolt and HTTP, you can simply use:
<dependency>
<groupId>org.neo4j</groupId>
<artifactId>neo4j-jdbc-driver</artifactId>
<version>{neo4j-jdbc-version}</version>
</dependency>
If you want only one of the protocols, you can depend on its module:
<dependency>
<groupId>org.neo4j</groupId>
<artifactId>neo4j-jdbc-bolt</artifactId>
<version>{neo4j-jdbc-version}</version>
</dependency>
or
<dependency>
<groupId>org.neo4j</groupId>
<artifactId>neo4j-jdbc-http</artifactId>
<version>{neo4j-jdbc-version}</version>
</dependency>
Minimum viable snippet
org.neo4j:neo4j-jdbc-driver:3.3.1
// Connecting
try (Connection con = DriverManager.getConnection("jdbc:neo4j:bolt://localhost", 'neo4j', password)) {
// Querying
String query = "MATCH (u:User)-[:FRIEND]-(f:User) WHERE u.name = {1} RETURN f.name, f.age";
try (PreparedStatement stmt = con.prepareStatement(query)) {
stmt.setString(1,"John");
try (ResultSet rs = stmt.executeQuery()) {
while (rs.next()) {
System.out.println("Friend: "+rs.getString("f.name")+" is "+rs.getInt("f.age"));
}
}
}
}
Please note that the example above uses the try-with-resource blocks that automatically closes resources when the try
block is exited.
Usage with Neo4j Server
-
Install a Neo4j 3.3.x server and start it with the Bolt protocol enabled
-
Connect with URLs in the following 3 forms:
-
jdbc:neo4j:http://<host>:<port>/
(e.g.jdbc:neo4j:http://localhost/
) -
jdbc:neo4j:bolt://<host>:<port>/
(e.g.jdbc:neo4j:bolt://localhost/
) -
jdbc:neo4j:bolt+routing://<host>:<port>/
(e.g.jdbc:neo4j:bolt+routing://localhost?routing:policy=eu
)
-
-
You can also use additional parameters in the URL separated by an
&
character for authentication, debug mode, SSL encryption and flattening e.g.jdbc:neo4j:bolt://localhost/?user=neo4j&password=xxxx&debug=true&nossl&flatten=[-1,100,1000]
Note
|
We’ve deprecated the usage of , as the parameter separator in favour of & to be compliant with the URL parameter syntax.
|
-
Add the JDBC driver dependency or jar file to your project
-
Get a connection from
DriverManager
-
Execute queries and transactions using the Cypher graph query language
Flattening
As most JDBC clients and tools don’t support complex objects, the driver can flatten returned nodes and relationships by providing all their properties as individual columns with names like u.name
,r.since
if you just return a node u
or relationship r
.
This is enabled with the JDBC-URL parameter flatten=<rows>
, where <rows>
indicates how many rows are sampled to determine those columns.
With -1
all rows are sampled and with any other value you determine the number of rows being looked at.
Building the driver yourself
First clone the repository.
This project is composed by the following modules:
-
Neo4j JDBC - the core module
-
Neo4j JDBC - Bolt - module supporting the Bolt protocol
-
Neo4j JDBC - HTTP - module supporting the HTTP protocol
-
Neo4j JDBC - Driver packaging - module to package all above modules
mvn clean test
mvn clean test -Pintegration-test
mvn clean test -Pperformance-test
Note
|
To run the performance test, you must have a Neo4j Server 3.3.x running with the Bolt protocol enabled on port 7687 (default). |
License
Copyright (c) 2017 Neo4j and LARUS Business Automation
The "Neo4j JDBC Driver" is licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
You may obtain a copy of the License at
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and limitations under the License.
Feedback
Please provide feedback and report bugs as GitHub issues or join the neo4j-users Slack and ask on the #neo4j-jdbc channel.
You might also ask on StackOverflow, please tag your question there with neo4j
and jdbc
.
Technical Reference
The HTTP Driver
The HTTP driver uses the existing (since Neo4j 2.x) transaction Cypher HTTP API, and is implemented using Apache Commons httpclient
and Jackson
for JSON (de)serialization.
The JDBC URL has this format: jdbc:neo4j:http://host:port/?username=neo4j,password=xxxx
The Bolt Driver
The Bolt driver connects to any Neo4j 3.x database that has the binary "Bolt" transport enabled.
It uses the neo4j-java-driver to provide the connectivity.
Just provide your username and password and you can connect to Neo4j.
The JDBC URL has this format: jdbc:neo4j:bolt://host:port/?username=neo4j,password=xxxx
The Bolt+Routing Driver
Starting from version 3.3.1, the JDBC driver brings with it the bolt+routing protocol.
Again, it uses the neo4j-java-driver to provide the connectivity.
If you’re connecting to a Neo4j Causal Cluster the JDBC URL has this format:
jdbc:neo4j:bolt+routing://host1:port1,host2:port2,…,hostN:portN/?username=neo4j,password=xxxx
The list of "hostX:portX"
pairs in the URL correspond to the list of servers that are partecipating in the Neo4j cluster (both as Core and Read-Replica nodes),
but if you or your preferred tool don’t like this format you can then fall back to the dedicated parameter "routing:servers"
, as in the following example:
jdbc:neo4j:bolt+routing://host1:port1?username=neo4j,password=xxxx,routing:region=EU&country=Italy&routing:servers=host2:port2;…;hostN:portN
In that case, the address in the URL must be that of a Core server and the alternative servers must be ;
separated (instead of ,
).
Routing Context
Routing driver with routing context is an available option with a Neo4j Causal Cluster of version 3.2 or above.
In such a setup you can include a preferred routing context via the "routing:policy"
parameter.
jdbc:neo4j:bolt+routing://host1:port1,host2:port2,…,hostN:portN?username=neo4j,password=xxxx,routing:policy=EU
And for custom routing strategies via the generic "routing:"
parameter:
jdbc:neo4j:bolt+routing://host1:port1,host2:port2,…,hostN:portN?username=neo4j,password=xxxx,routing:region=EU&country=Italy
Access Mode (READ, WRITE)
In order to start a transaction in read or write mode just use the Connection#setReadOnly
method.
Be aware not to invoke it while the transaction is open otherwise the driver will raise an SQLException.
If you’re accessing to a Neo4j Causal Cluster, by calling this method write operations will be forwarded to CORE instances, while read operations will be managed by READ REPLICA nodes.
Bookmarks
When working with a causal cluster, causal chaining is carried out by passing bookmarks between transactions in a session (see causal chaining).
The JDBC driver allows you to read bookmarks by calling the following method:
connection.getClientInfo(BoltRoutingNeo4jDriver.BOOKMARK);
Also you can set the bookmark by calling the corresponding method:
connection.setClientInfo(BoltRoutingNeo4jDriver.BOOKMARK, "my bookmark");
Bolt+Routing with Bookmark Example
String connectionUrl = "jdbc:neo4j:bolt+routing://localhost:17681,localhost:17682,localhost:17683,localhost:17684,localhost:17685,localhost:17686,localhost:17687?noSsl&routing:policy=EU";
try (Connection connection = DriverManager.getConnection(connectionUrl, "neo4j", password)) {
connection.setAutoCommit(false);
// Access to CORE nodes, as the connection is opened by default in write mode
try (Statement statement = connection.createStatement()) {
statement.execute("create (:BoltRoutingTest { protocol: 'BOLT+ROUTING' })");
}
// closing transaction before changing access mode
connection.commit();
// printing the transaction bookmark
String bookmark = connection.getClientInfo(BoltRoutingNeo4jDriver.BOOKMARK);
System.out.println(bookmark);
// Switching to read-only mode to access READ REPLICA nodes
connection.setReadOnly(true);
try (Statement statement = connection.createStatement()) {
try (ResultSet resultSet = statement.executeQuery("match (t:BoltRoutingTest) return count(t) as tot")) {
if (resultSet.next()) {
Long tot = resultSet.getLong("tot");
}
}
}
connection.commit();
}
JDBC Compatibility
We cover these aspects of the JDBC-APIs, everything that’s not explicitely mentioned should be assumed to be not implemented:
-
Driver handling automatic loading and JDBC URLs
-
Connection, incl. autocommit and manual commit
-
Read-only and write transactions
-
Statements for reads and writes
-
PreparedStatement for reads and writes, including parameters, both question marks
?
and named numbered parameters{1}
-
ResultSet retrieving all columns as String, Object and their native type with optional conversions
Libraries and Frameworks
Java JDBC Usage
Plain JDBC usage was already shown before:
org.neo4j:neo4j-jdbc-driver:3.3.1
// Connecting
try (Connection con = DriverManager.getConnection("jdbc:neo4j:bolt://localhost", 'neo4j', password)) {
// Querying
String query = "MATCH (u:User)-[:FRIEND]-(f:User) WHERE u.name = {1} RETURN f.name, f.age";
try (PreparedStatement stmt = con.prepareStatement(query)) {
stmt.setString(1,"John");
try (ResultSet rs = stmt.executeQuery()) {
while (rs.next()) {
System.out.println("Friend: "+rs.getString("f.name")+" is "+rs.getInt("f.age"));
}
}
}
}
Spring JDBC Template
Integrating with Spring JDBC is as easy as defining a datasource in your Spring config and then using it via JDBC Template.
You can find an example application here:
Play Framework
Taken from the Play Framework Documentation.
Enable the database plugin by adding javaJdbc
in your build dependencies:
libraryDependencies += javaJdbc
Then you must configure a connection pool in the conf/application.conf
file.
By convention the default JDBC data source must be called default, but you can use other names for named databases, in this case we use neo4j
# Neo4j database configuration db.neo4j.driver=org.neo4j.jdbc.bolt.BoltDriver db.neo4j.url="jdbc:neo4j:bolt://localhost"
import javax.inject.Inject;
import play.mvc.Controller;
import play.db.NamedDatabase;
import play.db.Database;
// inject "neo4j" database instead of "default"
class JavaNamedDatabase extends Controller {
private Database db;
@Inject
public JavaNamedDatabase(@NamedDatabase("neo4j") Database db) {
this.db = db;
}
// do whatever you need with the db
}
Integration Examples with Popular Database Tools
Reporting Tools
Jasper Reports
Step 1: Create new Data Adapters:
-
Right click on Data Adapters and click on Create Data Adapter and select "Database JDBC Connection*


-
Insert the values of JDBC driver: "org.neo4j.jdbc.bolt.BoltDriver" and
-
JDBC Url:
jdbc:neo4j:bolt://localhost
like the image below and -
insert your username and password

-
Click on Driver Classpath tab then to add:

-
Add the Neo4j JDBC jar file:


-
Click on Test and you should have a successful message:

Step 2: Retrieve Columns from Database:
-
Create new Jasper Report and click on DataSet and Query editor Dialog:

-
Insert the cypher "MATCH (a)-[:ACTED_IN]→(m)←[:DIRECTED]-(d) RETURN a.name, m.title, d.name;" then click on Read Field:

-
You can check data retrieve clicking on Data preview tab then Refresh Preview Data:

Step 3: Prepare Report and create document:


Eclipse BIRT
-
Start a new "Report project" under "Report design" perspective
-
Select the project’s name
-
Create a new report (File→New→Report) and give it a name
-
Choose your template
-
Create a new Datasource by right clicking "Data sources" → New Data Source and choose the second option
-
Create a new Connection profile store (click new on both windows)
-
Choose "BIRTH JDBC Data Source" and give it a name
-
Load your jdbc jar by clicking "Manage Drivers" and select "Add"
-
Choose your dirver location and press OK
-
Fill the driver connection parameters
-
Click "Next" and "Finish" and choose the newly created connection profile store
-
Click "Next" and "Finish" and the Data Source should be created
-
Create a new Dataset (right click Data Sets → New Data Set) and choose Next
-
Type the query you want to create your Dataset with and click Finish
-
A new Window will appear showing the columns available with your query
-
You can also preview the results
-
Close this window and create a new Table element (Right click the document → Insert → Table)
-
Choose 4 columns and click Finish
-
Fill the table with the following data (drag and drop the datasource colums in the right position)
-
To export the report click Run → View report → As PDF
Business Intelligence Tools
QlikView / Qlik Sense via TIQ JDBC Connector
(Thanks a lot to Ralf Becher, TIQ Solutions)
TIQ Solutions provides a commercial product to enable JDBC connectivity in QlikView and Qlik Sense. The configuration is simple.
In QlikView, you can connect to Neo4j directly. In Qlik Sense you need to copy the CUSTOM CONNECT script code.

If your Neo4j connection is established, you now can execute Cypher queries in LOAD statements (but mention the SQL prefix). The results get loaded into memory tables as usual.


Tableau via jdbc2tde
(Thanks a lot to Ralf Becher, TIQ Solutions)
Integration with Tableau is not that trivial as it only generates SQL.
So you can either use the Tableau REST integration (which we will publish soon).

Or the jdbc2tde tool from TIQ that uses JDBC queries to generate TDE files.
Those can then be loaded into Tableau and visualized and interacted with in the many ways you know and love.




ETL Tools
Pentaho
Step 1: Create database connections:
Right click on Database connections and click on New

Insert the connection parameters for source database the press Test button to check the connection:


As before, select a new Database connections and insert neo4j connection parameters, set:
-
Connection Type: Generic database
-
Custom Connection URL: "jdbc:neo4j:bolt://localhost:7687"
-
Custom Driver Class Name: "org.neo4j.jdbc.Driver"
-
Login and password:


Then press to Test button to check the connection:

Step 2: Create Steps and Hops:
-
From Design select input and click on table input top insert the source table:


-
From Scripting click on Execute SQL script:


-
Double click on table input. Select the source database Connection and write query to extract data the press Preview button to check query:


-
Double click on Hops, select as From step the table input and as to step the Execute SQL Script:


-
Now your Hop is complete!

-
Double click on Execute SQL script. Click on Get Fields to retrive the column from source database. Write the cypher to create nodes and relationship:

Step 3: Run the job
-
Click on run this transformation or job and wait until finished:



-
If all ok, you should have like this:

Talend
(Thanks a lot to Benoit Simard)
With Talend, you can query or import your data into Neo4j using Talend JDBC Components. On the Job, you just have to add a tJDBCConnection and add the usual fields: JDBC-URL, Driver-Jar, Driver, username and password.

NB: On the Advanced Settings tab, you can also configure the auto-commit, if you want it.
Now, you can add some tJDBCInput to make some queries to your Neo4j databases like this :

Database Tools
Squirrel SQL
Squirrel SQL is a widely used SQL workbench that supports many databases out of the box. Adding the JDBC driver was straightforward, as was running Cypher queries and getting tabular results back.
Works in general for scalar values
-
Configured Driver via Add Driver → Extra ClassPath
-
Created New Session,
-
Worked but gave a warning about 2.1 incompatibility

Eclipse Database Tools
Step 1: Create a new connection profile
-
Open the Database Developement perspective:


-
Click on the icon New Connection Profile:

-
Choose Generic JDBC (and optionally type "Neo4j 3.0 JDBC Bolt Driver" in "name" and "description" fields. Then click Next:

Step 2: Create a new driver definition
-
Click on the icon New Driver Definition:

-
Choose "Generic JDBC Driver" in folder Name/Type (and optionally re-type "Neo4j 3.0 JDBC Bolt Driver" in the "Driver Name" field):

-
In Folder JAR List, click Add JAR/Zip and choose the new Neo4j JDBC Bolt Driver:

-
In Folder Properties choose the Driver Class" by clicking the icon [..]:

-
Choose org.neo4j.jdbc.bolt.BoltDriver as the Driver class:

-
Set the Connection URL to "jdbc:neo4j:bolt://localhost" and the User ID to "neo4j", then click OK:

-
Set the Password and click Test Connection:

-
You should get Ping Succeeded! message (with your database online). Click OK and then Finish:

Step 3: Test the connection (match and create)
-
Open an SQL Scrapbook and execute your statement (i.e.
match (n) return n
):

-
Create statements should work as well:

as you can see on the neo4j browser:

SQL-Shell
It’s working now on the master branch (6b166ec31bdb61f76279be717aa1f30ada5c553e)
-
Copy Neo4j JDBC driver into
SQLSHELL_HOME/lib
folder -
Edit the configuration file
SQLSHELL_HOME/sample.cfg
for : -
Adding neo4j driver :
[drivers] neo4j = org.neo4j.jdbc.bolt.BoltDriver
-
Adding your database
[db_neo4j] aliases: neo driver: neo4j url: jdbc:neo4j:bolt://localhost user: neo4j password: test
-
Now execute
sqlshell
with the configuration file to openneo
database :
$> SQLSHELL_HOME/bin/sqlshell -c SQLSHELL_HOME/sample.cfg neo
-
Execute some queries !

APOC LOAD JDBC
-
Copy Neo4j JDBC Driver jar into
NEO4J_HOME/plugins
folder -
Restart the database
-
Run some JDBC Queries:
WITH ['The Matrix'] as movies
CALL apoc.load.jdbcParams('jdbc:neo4j:bolt://localhost?user=neo4j,password=test','MATCH (m:Movie) WHERE m.title=? RETURN m', movies) YIELD row
RETURN row

Apache SolR
Description
You can index your Neo4j database directly into SolR with the help of SolR Data Import Handler
(DIH) feature and the neo4j jdbc driver.
This article is just on how to make the glue the two component via the JDBC driver.
If you want to learn how SolR works with its DIH feature, please refer to thoses documentations : * https://wiki.apache.org/solr/DataImportHandler * https://cwiki.apache.org/confluence/display/solr/Uploading+Structured+Data+Store+Data+with+the+Data+Import+Handler
How-to
Download the lastest release of SolR (for example : http://apache.crihan.fr/dist/lucene/solr/6.1.0/solr-6.1.0.tgz)
$>cd /tmp $> wget http://apache.crihan.fr/dist/lucene/solr/6.1.0/solr-6.1.0.tgz
Extract it to a folder (reference as SOLR_HOME)
$> tar xzvf solr-6.1.0.tgz -C SOLR_HOME
Copy the folder SOLR_HOME/example/example-DIH/solr/solr
to SOLR_HOME/server/solr/neo4j
.
This will create a new SolR core called neo4j
with all DIH feautres enabled.
$> cp -rf SOLR_HOME/example/example-DIH/solr/solr SOLR_HOME/server/solr/neo4j
Copy The Neo4j JDBC Driver jar into folder SOLR_HOME/server/solr/neo4j/lib
(create the folder of it doesn’t exist).
$> mkdir SOLR_HOME/server/solr/neo4j/lib $> cp neo4j-jdbc-driver-3.0.1-SNAPSHOT.jar SOLR_HOME/solr/server/solr/neo4j/lib/
Edit the file SOLR_HOME/server/solr/neo4j/config/solrconfig.xml
to add lib
folder by adding this line :
<lib dir="./lib" />
We will configure SolR DIH feature by editing the file SOLR_HOME/server/solr/neo4j/config/solr-data-config.xml
.
Just replace its content by this one (don’t forget to replace the jdbc url, login password by yours):
<dataConfig> <dataSource type="JdbcDataSource" driver="org.neo4j.jdbc.Driver" url="jdbc:neo4j:bolt://localhost?nossl" user="neo4j" password="test" /> <document name="movie"> <entity name="movie" query="MATCH (m:Movie) RETURN id(m) AS id, m.title AS title, m.tagline AS tagline, m.released AS released"> <field name="id" column="id" /> <field name="title" column="title" /> <field name="tagline_s" column="tagline" /> <field name="release_i" column="released" /> </entity> </document> </dataConfig>
Start SolR server :
$> SOLR_HOME/bin/solr start
Open your browser at this url, http://localhost:8983/solr/#/neo4j/dataimport//dataimport , and click on the Execute
button.
A click on the refresh status
allow you to see the status of the indexation.
