Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Introduction to Neo4j OGM

DZone's Guide to

Introduction to Neo4j OGM

View this sample project that creates family members as Neo4j nodes and establishes marriage and parent-child between them.

· Database Zone ·
Free Resource

Built by the engineers behind Netezza and the technology behind Amazon Redshift, AnzoGraph is a native, Massively Parallel Processing (MPP) distributed Graph OLAP (GOLAP) database that executes queries more than 100x faster than other vendors.  

Overview

Neo4j Object-Graph Mapping, or Neo4j OGM, is a library for modifying and querying Neo4j databases without directly using Cypher.

Conceptually similar to Java Persistence API for relational databases, OGM annotations are added to plain-old Java objects, identifying them as Neo4j nodes or relationships. New objects for nodes or relationships are created and added to the Neo4j session, which OGM persists by creating and then executing the appropriate Cypher statements.

Using OGM to manipulate your Neo4j data gives you compile-time checks of nodes, relationships, labels, and properties that you don't have when working directly with Cypher but still allows your data model to evolve naturally as other NoSQL databases.

Prerequisites

  • Neo4j Server. Either Community or Enterprise, this intro tested with v3.3.1.
  • Neo4j OGM Libraries. Latest version today is v3.1.0, accessible via Maven, Gradle, and Ivy.

Sample Project

This sample project creates family members as Neo4j nodes and establishes marriage and parent-child between them. Objects are created and loaded into Neo4j via OGM without writing any Cypher.

Create Domain Objects

Nodes

A Neo4j node, also known in graph theory as a vertex, is a data record containing a random set of properties. Each POJO class is a distinct node type within the Neo4j database. They are conceptually similar to a relational database table, except they are not predefined in Neo4j before being used.

Node entity objects have a class-level annotation identifying the class as a node and an annotated member indicating the internally-generated identifier. Other properties do not require annotations if OGM can derive them automatically.

@NodeEntity
public class Person {
    @Id
    @GeneratedValue
    private Long id;

    /**
     * person's year of birth
     */
    private int birthYear;

    /**
     * Person name
     */
    private String name;
    .
    .
    .
}

Relationships

A Neo4j relationship, also known in graph theory as an arc or an edge, identifies a meaningful, directed relationship between two nodes in a graph. Neo4j OGM provides two techniques for creating relationships.

When relationship-specific properties are required to provide additional definition to the relationship, a Relationship entity object is created. Annotations define starting and ending nodes in the relationship; other properties do not require annotations if OGM can derive them automatically.

@RelationshipEntity(type = "MARRIED")
public class Married {

    /**
     * Internal Neo4J id of the node
     */
    @Id
    @GeneratedValue
    private Long id;

    /**
     * If divorced, what year was the divorce finalized
     */
    private Integer yearDivorced;

    /**
     * the year married
     */
    private Integer yearMarried;

    /**
     * the wife in the marriage
     */
    @StartNode
    private Person wife;

    /**
     * the husband in the marriage
     */
    @EndNode
    private Person husband;
    .
    .
    .
}

Relationships can also be identified in the Node class if no relationship-specific properties are required using a collection of Nodes. Multiple relationships of different types can be defined this way.

@NodeEntity
public class Person {
    @Id
    @GeneratedValue
    private Long id;
    .
    .
    .
    @Relationship(type = "PARENT")
    private List<Person> children = null;
    .
    .
    .
}

Load Data

Configure Session

A session is configured by declaring how to connect and authenticate to your Neo4j database and identifying the packages containing the domain objects. Domain objects in other packages are not recognized by OGM and are not persisted to the database.

public class Loader {

    /**
     * Session factory for connecting to Neo4j database
     */
    private final SessionFactory sessionFactory;

    //  Configuration info for connecting to the Neo4J database
    static private final String SERVER_URI = "bolt://localhost";
    static private final String SERVER_USERNAME = "neo4j";
    static private final String SERVER_PASSWORD = "password";


    /**
     * Constructor
     */
    public Loader() {
        //  Define session factory for connecting to Neo4j database
        Configuration configuration = new Configuration.Builder().uri(SERVER_URI).credentials(SERVER_USERNAME, SERVER_PASSWORD).build();
        sessionFactory = new SessionFactory(configuration, "com.buddhadata.sandbox.neo4j.ogm.intro.node", "com.buddhadata.sandbox.neo4j.ogm.intro.relationship");
    }
    .
    .
    .
}

Open Session and Transaction

Similar to JPA, you open a new session to Neo4j database and create a transaction in which your work exists.

Warning: For demo purposes, this demo project purges the database in each run; obviously you wouldn't do this in a production environment!

public class Loader {
    .
    .
    .
    private void process () {

        //  For demo purposes, create session and purge to cleanup whatever you have
        Session session = sessionFactory.openSession();
        session.purgeDatabase();

        //  All work done in single transaction.
        Transaction txn = session.beginTransaction();
        .
        .
        .
    }
}

Persist Data

Create the needed Node and Relationship objects and save them in the OGM session. Once all objects are passed to the session, commit the transaction.

public class Loader {
    .
    .
    .
    private void process () {
        .
        .
        .
        Person Carol = new Person ("Carol Maureen", 1945);
        Person Courtney = new Person ("Courtney Janice", 1945);
        Person Jeremy = new Person ("Jeremy Douglas", 1969);
        Person Mike = new Person ("Michael Blevins", 1945);
        Person Scott = new Person ("Scott Christoper", 1965);

        List<Person> children = Carol.getChildren();
        children.add (Scott);
        children.add (Courtney);
        children.add (Jeremy);
        children = Mike.getChildren();
        children.add (Scott);
        children.add (Courtney);
        children.add (Jeremy);

        session.save (Carol);
        session.save (Courtney);
        session.save (Jeremy);
        session.save (Mike);
        session.save (Scott);

        session.save (new Married(Carol, Mike, 1964, 1973));

        txn.commit();
    }
}

Check Work

In your browser, navigate to your Neo4j server and execute the following Cypher statement to return all nodes created.

MATCH (s) RETURN s

Conclusion

Hopefully, you now understand the basic concepts of Neo4j OGM and can use it in your own use cases.

The complete demo project can be downloaded from here.

Download AnzoGraph now and find out for yourself why it is acknowledged as the most complete all-in-one data warehouse for BI style and graph analytics.  

Topics:
neo4j ,jpa ,java ,introduction ,nosql ,graph theory ,database ,tutorial

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}