Connecting to Neo4j Database from a Java Program using JDBC

This class demonstrate how you can connect to the Neo4j database using their JDBC driver and create nodes/relationships from a Java Program. We have used neo4j-desktop-2.2.2.jar for compiling and running this program.

package com.icodejava.blog.published.neo4j;

/**
 * @author Kushal Paudyal
 * Created on 11/29/2016
 * Last modified on 11/29/2016
 * 
 * This class demonstrate how you can connect to the Neo4j database using their JDBC driver
 * and create nodes/relationships from a Java Program.
 *
 */
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Label;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Relationship;
import org.neo4j.graphdb.RelationshipType;
import org.neo4j.graphdb.Transaction;
import org.neo4j.graphdb.factory.GraphDatabaseFactory;
public class Neo4jJDBC {

    
    /**
     * To avoid database lock errors, please run this program by shutting down the neo4j server.
     */

    public static void main(String[] args) {

        GraphDatabaseFactory dbFactory = new GraphDatabaseFactory();
        GraphDatabaseService db = dbFactory.newEmbeddedDatabase("C:/Users/adam/Desktop/Neo4jDatabaseJDBC");
        try {
            Transaction tx = db.beginTx();

            /**
             * Create an Employee node with some properties
             */
            Node person = db.createNode(Labels.EMPLOYEE);
            person.setProperty("WorkID", "1001");
            person.setProperty("FirstName", "James");
            person.setProperty("MiddleName", "A");
            person.setProperty("LastName", "Tyson");
            

            /**
             * Create a company
             */
            Node company = db.createNode(Labels.COMPANY);
            company.setProperty("CompanyName", "Sanjaal Corps");
            
            /**
             * Create relationship between the person and copany
             */
            Relationship relationship = person.createRelationshipTo(company,Relationships.WORKS_FOR);
            relationship.setProperty("Id", "r21109");
            relationship.setProperty("Since", "2005");

            tx.success();
            
            System.out.println("Successfully created nodes and relationships in the database");
        } finally {
            
        }

    }
    
    public enum Labels implements Label {
        EMPLOYEE, CONTRACTOR, COMPANY, SCHOOL
    }
    
    
    public enum Relationships implements RelationshipType {
        WORKS_FOR, CONTRACTS_FOR  
    }

}

How to load a local CSV file in Neo4j in Mac, Linux or Windows

Neo4j is pretty efficient loading a large amount of data. Whether you are loading a raw data or data that you extracted as CSV from another database, you can easily load those to Neo4j Graph Database and create Nodes and Relationships as the data is loaded.

In this tutorial, I am uploading a simple CSV file with headers, few lines from that CSV files are as listed below, for your reference.

Municipality,District
Kathmandu,Kathmandu
Pokhara,Kaski
Lalitpur,Lalitpur
Biratnagar,Morang

Here is a command I can run on the Neo4j console to load this file and then create relationships.

LOAD CSV WITH HEADERS FROM 'file:///Users/kushal/Desktop/Nepal Data/Municipalities_of_nepal.csv' AS line
MERGE(d:District{name:line.District})
CREATE (m:Municipality { name: line.Municipality})
CREATE (d-[:MUNICIPALITY]->(m)
return d,m;

If you are using windows, then you would have to provide the URL as, for example:

file://C:/Users/kushal/Desktop/Nepal Data/Municipalities_of_nepal.csv

The good thing is Neo4j also supports loading data from URLs. So let’s say the CSV file was on the internet, I could load it using the following Cipher.

LOAD CSV WITH HEADERS FROM 'http://www.icodejava.com/data/doesnotexist/Municipalities_of_nepal.csv' AS line
MERGE(d:District{name:line.District})
CREATE (m:Municipality { name: line.Municipality})
CREATE (d-[:MUNICIPALITY]->(m)
return d,m;

Neo4j Cheat Sheet – How to do certain things in Neo4j Graph Database

Add Stuffs:

  1. Create a simple node
    CREATE (n:NodeLabel) return n;
  2. Create a node with some node properties
    CREATE (n:NodeLabel{propertyName1:”propertyValue1″, propertyName2:”propertyValue2″}) return n
  3. Create a simple relationship between two nodes.
    Match (m:SomeNode),(n:SomeOtherNode) 
    CREATE (m)-[r:SOME_RELATION]->(n)
    return m,n
  4. Create a relationship between two nodes if the relationship already does not exist
    Match (m:SomeNode),(n:SomeOtherNode) 
    CREATE UNIQUE (m)-[r:SOME_RELATION]->(n)
    return m,n
  5. Create a relationship between two nodes with certain properties
    Match (m:SomeNode{someProperty:”SomePropertyValue”}),
    (n:SomeOtherNode{someProperty:”SomePropertyValue”}) 
    CREATE (m)-[r:SOME_RELATION]->(n)
    return m,n
  6. Add a property to a relationship
    Match g=()-[r:Some_Relationship]-()
    set r.some_property_name=”Some_Property_Name_Of_Relationship” return g;

Delete Stuffs:

  1. Delete all relationships for a node by node property
    MATCH (n:SomeLabel{ name: ”SomeNodeProperty” })-[r]->() DELETE r
  2. Delete all relationships by a relationship name
    MATCH (n:SomeNode)-[r:SomeRelationShip]->(a:OtherNode) DELETE r
  3. Delete a relationship by relationship ID
    start r=rel(someRelationshipID) delete r;
  4. Delete a node property
    MATCH(n:SomeNode) REMOVE n.someNodeProperty return n

Rename Stuffs:

  1. How to rename relationships
    MATCH (n1)-[r1:OldRelationShip]->(n2)
    CREATE (n1)-[r2:NewRelationship]->(n2)
    DELETE old
  2. How to rename Node labels
    MATCH (n) WHERE ID(n) = 14
    REMOVE n:Developers
    SET n:Developer

Plan Queries:

  1. How to see the query plan without committing
    EXPLAIN MATCH n RETURN n
  2. How to see the query plan with commit
    PROFILE MATCH n RETURN n