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

  • LLMOps Essentials: A Practical Guide To Operationalizing Large Language Models

    When you engage with ChatGPT or any other Generative AI tool, you just type and enter your query and Tada!! You get your answer in seconds. Ever wondered how it happens and how it is so quick? Let’s peel back the curtain of the LLMs a bit. What actually happens behind the screen is a […]

  • Building Intelligent AI Models For Enterprise Success: Insider Strategies 

    Just picture a world where machines think and learn like us. It might sound like a scene straight out of a sci-fi movie, right? Well, guess what? We are already living in that world now. Today, data, clever algorithms, and AI models are changing the way businesses operate. AI models are serving as a brilliant […]

  • Introducing Google Vids in Workspace: Your Ultimate AI-Powered Video Creation Tool

    Hey there, fellow content creators and marketing gurus! Are you tired of drowning in a sea of emails, images, and marketing copy, struggling to turn them into eye-catching video presentations? Fear not, because Google has just unveiled its latest innovation at the Cloud Next conference in Las Vegas: Google Vids- Google’s AI Video Creation tool! […]

  • Achieve High ROI With Expert Enterprise Application Development

    Nowadays modern-day enterprises encounter no. of challenges such as communication breakdown, inefficient business processes, data fragmentation, data security risks, legacy system integration with modern applications, supply chain management issues, lack of data analytics and business intelligence, inefficient customer relationship management, and many more. Ignoring such problems within an organization can adversely impact various aspects of […]

  • State Management with Currying in React.js

    Dive into React.js state management made easy with currying. Say goodbye to repetitive code and hello to streamlined development. Explore the simplicity and efficiency of currying for your React components today!

  • How Much Does It Cost to Develop an App in 2024?

    The price of bringing your app to life typically ranges from $20,000 to $200,000. This cost varies based on factors like which platform you choose, the complexity of features you want, and the size of your intended audience. However, costs can climb even higher for more complex projects, reaching up to $350,000.