DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Enterprise AI Trend Report: Gain insights on ethical AI, MLOps, generative AI, large language models, and much more.

2024 Cloud survey: Share your insights on microservices, containers, K8s, CI/CD, and DevOps (+ enter a $750 raffle!) for our Trend Reports.

PostgreSQL: Learn about the open-source RDBMS' advanced capabilities, core components, common commands and functions, and general DBA tasks.

AI Automation Essentials. Check out the latest Refcard on all things AI automation, including model training, data security, and more.

Related

  • How Milvus Realizes the Delete Function
  • See What's New in Neo4j 4.0
  • Neo4J and Virtual Nodes/Relationships
  • Loading US Lobbying Data Into Neo4J

Trending

  • The Impact of Biometric Authentication on User Privacy and the Role of Blockchain in Preserving Secure Data
  • Spring Boot 3.2: Replace Your RestTemplate With RestClient
  • Types of Data Breaches in Today’s World
  • AI-Driven API and Microservice Architecture Design for Cloud
  1. DZone
  2. Data Engineering
  3. Databases
  4. Intro to Querying Neo4j Using OGM

Intro to Querying Neo4j Using OGM

Let's take a look at how to add examples of querying the data that was loaded in the previous article.

By 
Scott Sosna user avatar
Scott Sosna
DZone Core CORE ·
Aug. 15, 18 · Tutorial
Like (3)
Save
Tweet
Share
8.6K Views

Join the DZone community and get the full member experience.

Join For Free

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 blog extends my Introduction to Neo4J OGM by adding examples of querying the data previously loaded.

Single Filter

A single filter is a conditional used to evaluate nodes or relationships to return as the results in a query, identical to a SQL WHERE clause.

A filter is composed of a property name, a , and - if the application for boolean operation provided - a comparison value.

The session object defines methods for applying the filter against a specific node or relationship type.

In the example project, the filter is querying for a specific birth year.

    private Iterable<Person> queryByFilter (int birthYear,
                                            Session session) {

        //  Create an OGM filter for the birthYear property.
        Filter filter = new Filter ("birthYear", ComparisonOperator.EQUALS, birthYear);

        //  Load all Persons with the given birth year.
        return session.loadAll (Person.class, filter);
    }

Composite Filter

A composite filter contains one or more filters connected by a boolean relationship.  The contained filters may be either a single filter or another composite filter, in this case, a SQL WHERE clause surrounded by parentheses.

In the example, the composite filter is querying for a specific birth year or for a Person's name greater than a starting letter provided.

    private Iterable<Person> queryByMultipleFilters (int birthYear,
                                                     String startingLetter,
                                                     Session session) {

        //  Filter either by the birth year or name greater than the starting letter
        Filters composite = new Filters();
        Filter filter = new Filter ("birthYear", ComparisonOperator.EQUALS, birthYear);
        composite.add(filter);
        filter = new Filter ("name", ComparisonOperator.GREATER_THAN, startingLetter);
        filter.setBooleanOperator(BooleanOperator.OR);
        composite.add(filter);

        //  Load all Persons which match the composite filter.
        return session.loadAll (Person.class, composite);
    }

A composite filter composed of other composite filters represent multiple levels of parentheses for more complicated comparisons.

Cypher Queries

When your query needs are more complicated than can be represented by filters, you can define the specific Cypher statement and provide the parameters to substitute into the statement.

In this example, the query returns the Person nodes for those married to the target of the relationship, as specified by name.

    private Iterable<Person> queryByCypher (String marriedTo,
                                            Session session) {

        //  Create/load a map to hold the parameter
        Map<String, Object> params = new HashMap<>(1);
        params.put ("name", marriedTo);

        //  Execute query and return the other side of the married relationship
        String cypher = "MATCH (w:Person)-[:MARRIED]->(h:Person {name:$name}) RETURN w";
        return session.query (Person.class, cypher, params);
    }

Instead of hard-coding the specific name being queried on, the $name parameter is substituted at runtime with whatever value has been put into the parameter map.  Parameters allow the Cypher statement to be reused without having to do a bunch of string building for each time called.

And similar to relational databases, using substitution parameters allow the Cypher query to be parsed once and the execution plan cached, leading to faster execution times.

Conclusion

Granted, the examples are very simple, but hopefully, you can apply this to your own OGM projects and query and get the data returned as objects.

The complete demo project can be downloaded from here.

Neo4j Filter (software) Relational database

Opinions expressed by DZone contributors are their own.

Related

  • How Milvus Realizes the Delete Function
  • See What's New in Neo4j 4.0
  • Neo4J and Virtual Nodes/Relationships
  • Loading US Lobbying Data Into Neo4J

Partner Resources


Comments

ABOUT US

  • About DZone
  • Send feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: