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

  • A Comprehensive Guide to Sentiment Analysis Using NLP

    Businesses need to understand public interests, attitudes, behavior, and trigger points in today’s dynamic and competitive market. This enables them to efficiently serve their customers, grab opportunities, grow, and develop resilience in the face of a constantly shifting market. Many businesses find it challenging to process vast amounts of text-based data in order to get […]

  • How AI Is Revolutionizing Banking: Transforming Customer Experiences and Enhancing Financial Security

    Banking is a huge industry with a global Banking market likely to achieve a Net Interest Income of USD 10.34 trillion, with Traditional Banks holding a huge stake of USD 8.30 trillion. According to Statista’s projections suggest an annual growth rate of 4.82% (CAGR 2024-2028), culminating in a market volume of USD12.48 trillion by 2028. […]

  • Mastering Hyperparameter Tuning in Python: Strategies, Techniques, and Tools for Model Optimization

    Understanding various aspects of deep learning and machine learning can often feel like stepping into uncharted territory with no clue where to go. As you start exploring various algorithms and data, you realize that success is based on more than just building a raw model, it’s more about fine-tuning it to perfection. And when we […]

  • What is Transfer Learning? Exploring The Popular Deep Learning Approach

    Have you ever thought about how quickly your smartphone recognizes faces in photos or suggests text as you type? Behind these features, there’s a remarkable technique called Transfer Learning that expands the capabilities of Artificial Intelligence. Now you must be wondering- What is Transfer Learning ? Picture this: Instead of starting from the square from […]

  • 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 […]

Click to Copy