Learn How To Use Neo4j With Node.js

In this tutorial you discover how to work with the Neo4j graph database in Node.js. Graph databases are very useful when you want to store and query highly connected data. Neo4j is a database that can efficiently store, handle and query highly connected elements in your data model. Neo4j has a powerful and flexible data model so you can represent your real-world, variably structured information without a loss of fidelity.

In this tutorial you will learn several methods for communicating with Neo4j in Node.js, including using: 1. Neo4j’s built-in REST interface 2. The node-neo4j(philippkueng) module

Communicating to Neo4j using the built-in REST API

The Neo4j database has an inbuilt HTTP REST interface that we can use to directly interface with the Neo4j database. You simply need to POST to a HTTP URL to send queries, and to receive responses from Neo4j. In this demo you will use the Node.JS request module to make the REST call because it is so easy to do that using request. You can read more about the request module in the blog “How to use request module.” To install the request module, run the following command:

> npm install request

Let’s create a blank file and write the following step-by-step instructions in it: Load the request module We will use require function to load the request module in our program:

//Let’s load the request module
var request = require("request");

Create the method which will fire the cypher query Next we will make a function that takes the cypher query as the input and fires it in the database using the HTTP interface. The endpoint protocol and formats are explained in detail in the Neo4j manual. It enables you to do much more; for example, sending many statements per request or keeping transactions open across multiple requests. Take a look at the Neo4j manual for more details. Define where database is hosted:

//Define your host and port. This is where your database is running. Here it is defined on localhost.
var host = 'localhost',
  port = 7474;

Define the URL we need to connect. It is specified in the Neo4j docs.

//This is the URL where we will POST our data to fire the cypher query. This is specified in Neo4j docs.
var httpUrlForTransaction = 'http://' + host + ':' + port + '/db/data/transaction/commit';

Next we’ll define the function that takes the parameters cypher, which is the query to be executed, params, which is any params for the cypher query, and the callback function, which needs to be triggered when we have a response from the database.

//Let’s define a function which fires the cypher query.
function runCypherQuery(query, params, callback) {
  request.post({
      uri: httpUrlForTransaction,
      json: {statements: [{statement: query, parameters: params}]}
    },
    function (err, res, body) {
      callback(err, body);
    })
}

Fire some queries Now that we have a method which will enable us to fire the queries in Neo4j, let’s use it by trying to save a node in Neo4j.

/**
 * Let’s fire some queries below.
 * */
runCypherQuery(
  'CREATE (somebody:Person { name: {name}, from: {company}, age: {age} }) RETURN somebody', {
    name: 'Ghuffran',
    company: 'Modulus',
    age: 44
  }, function (err, resp) {
    if (err) {
      console.log(err);
    } else {
      console.log(resp);
    }
  }
);

In the preceding example we used a cypher query to save the node. You can read about the cypher query language here on the docs page. Note: It’s good to use queries with parameters as described because in this case Neo4j caches the query execution path and then runs that with different parameters we pass. This helps increase the query execution speed. Now if we sum up all the above, our file should look like:

//Let’s load the request module
var request = require("request");

//Define your host and port. This is where your database is running. Here it’s on localhost.
var host = 'localhost',
  port = 7474;

//This is the url where we will POST our data to fire the cypher query. This is specified in Neo4j docs.
var httpUrlForTransaction = 'http://' + host + ':' + port + '/db/data/transaction/commit';

//Let’s define a function which fires the cypher query.
function runCypherQuery(query, params, callback) {
  request.post({
      uri: httpUrlForTransaction,
      json: {statements: [{statement: query, parameters: params}]}
    },
    function (err, res, body) {
      callback(err, body);
    })
}

/**
 * Let’s fire some queries as shown below.
 * */
runCypherQuery(
  'CREATE (somebody:Person { name: {name}, from: {company}, age: {age} }) RETURN somebody', {
    name: 'Ghuffran',
    company: 'Modulus',
    age: 44
  }, function (err, resp) {
    if (err) {
      console.log(err);
    } else {
      console.log(resp);
    }
  }
);

Hurray!! we just interfaced with the Neo4j database using the native HTTP REST API.

Communicating to Neo4j using the node-neo4j(philippkueng) Node.js module
You can use several modules to interface with the Neo4j in Node.js, but node-neo4j (Thingdom) and node-neo4j (philipkueng) are the ones which are most widely used. They both work well and it’s generally a personal choice between these two. But in the following examples, we will be using the node-neo4j (philippkueng) module because it seems to have better documentation.

We can install the module using npm by issuing the following command:

> npm install node-neo4j

Now let’s see how we can use the node-neo4j module to fire some cypher queries as well as use their object interface. Running Cypher queries using the node-neo4j module Let’s now try to run the same query we ran above using the node-neo4j module. Our code will look like:

//Require the Neo4J module
var neo4j = require('node-neo4j');

//Create a db object. We will using this object to work on the DB.
db = new neo4j('http://localhost:7474');

//Run raw cypher with params
db.cypherQuery(
  'CREATE (somebody:Person { name: {name}, from: {company}, age: {age} }) RETURN somebody',
  {
    name: 'Ghuffran',
    company: 'Modulus',
    age: ~~(Math.random() * 100) //generate random age
  }, function (err, result) {
    if (err) {
      return console.log(err);
    }
    console.log(result.data); // delivers an array of query results
    console.log(result.columns); // delivers an array of names of objects getting returned
  }
);

In the preceding code we used the method db.cypherQuery(query, [params|Optional], [include_stats|Optional], callback) provided by the module to run our cypher query.Using helper methods in the node-neo4j module The node-neo4j module provides a list of helper methods to work with neo4j. Let’s see how we can save our node using the helper method:

//Require the Neo4J module
var neo4j = require('node-neo4j');

//Create a db object. We will using this object to work on the DB.
db = new neo4j('http://localhost:7474');

//Let’s create a node
db.insertNode({
  name: 'Ghuffran',
  company: 'Modulus',
  age: ~~(Math.random() * 100)
}, function (err, node) {
  if (err) {
    return console.log(err);
  }

  // Output node data.
  console.log(node);
});

In the preceding code we used the db.insertNode method to help us create the specified node. There are methods to update, read, delete etc that you can use to perform your basic interactions with the Neo4J database without dealing with the cypher query. You can read in detail about them in the API Documentation.

Conclusion

In this tutorial you learned how to interact with the Neo4j database using the native REST API, as well as using the node-neo4j module. We also saw a basic cypher query to save a node. For next steps you can learn more about relationships within nodes and cypher queries to build/retrieve them.


Posted

in

by

Recent Post

  • Generative AI for IT: Integration approaches, use cases, challenges, ROI evaluation and future outlook

    Generative AI is a game-changer in the IT sector, driving significant cost reductions and operational efficiencies. According to a BCG analysis, Generative AI (GenAI) has the potential to deliver up to 10% savings on IT spending—a transformation that is reshaping multiple facets of technology. The impact is especially profound in application development, where nearly 75% […]

  • Generative AI in Manufacturing: Integration approaches, use cases and future outlook

    Generative AI is reshaping manufacturing by providing advanced solutions to longstanding challenges in the industry. With its ability to streamline production, optimize resource allocation, and enhance quality control, GenAI offers manufacturers new levels of operational efficiency and innovation. Unlike traditional automation, which primarily focuses on repetitive tasks, GenAI enables more dynamic and data-driven decision-making processes, […]

  • Generative AI in Healthcare: Integration, use cases, challenges, ROI, and future outlook

    Generative AI (GenAI) is revolutionizing the healthcare industry, enabling enhanced patient care, operational efficiency, and advanced decision-making. From automating administrative workflows to assisting in clinical diagnoses, GenAI is reshaping how healthcare providers, payers, and technology firms deliver services. A Q1 2024 survey of 100 US healthcare leaders revealed that over 70% have already implemented or […]

  • Generative AI in Hospitality: Integration, Use Cases, Challenges, and Future Outlook

    Generative AI is revolutionizing the hospitality industry, redefining guest experiences, and streamlining operations with intelligent automation. According to market research, the generative AI market in the hospitality sector was valued at USD 16.3 billion in 2023 and is projected to skyrocket to USD 439 billion by 2033, reflecting an impressive CAGR of 40.2% from 2024 […]

  • Generative AI for Contract Management: Overview, Use Cases, Implementation Strategies, and Future Trends

    Effective contract management is a cornerstone of business success, ensuring compliance, operational efficiency, and seamless negotiations. Yet, managing complex agreements across departments often proves daunting, particularly for large organizations. The TalkTo Application, a generative AI-powered platform, redefines contract management by automating and optimizing critical processes, enabling businesses to reduce operational friction and improve financial outcomes. […]

  • Generative AI in customer service: Integration approaches, use cases, best practices, and future outlook

    Introduction The rise of generative AI is revolutionizing customer service, heralding a new era of intelligent, responsive, and personalized customer interactions. As businesses strive to meet evolving customer expectations, these advanced technologies are becoming indispensable for creating dynamic and meaningful engagement. But what does this shift mean for the future of customer relationships? Generative AI […]

Click to Copy