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

  • Future Trends in AI Chatbots: What to Expect in the Next Decade

    Artificial Intelligence (AI) chatbots have become indispensable across industries. The absolute conversational capabilities of AI chatbots are enhancing customer engagement, streamlining operations, and transforming how businesses interact with users. As technology evolves, the future of AI chatbots holds revolutionary advancements that will redefine their capabilities. So, let’s start with exploring the AI chatbot trends: Future […]

  • Linguistics and NLP: Enhancing AI Chatbots for Multilingual Support

    In today’s interconnected world, businesses and individuals often communicate across linguistic boundaries. The growing need for seamless communication has driven significant advancements in artificial intelligence (AI), particularly in natural language processing (NLP) and linguistics. AI chatbots with multilingual support, are revolutionizing global customer engagement and service delivery. This blog explores how linguistics and NLP are […]

  • How Reinforcement Learning is Shaping the Next Generation of AI Chatbots?

    AI chatbots are no longer just about answering “What are your working hours?” or guiding users through FAQs. They’re becoming conversation partners, problem solvers and even reporting managers and sales agents. What’s driving this transformation? Enter Reinforcement Learning (RL)—a type of machine learning that’s changing the way chatbots think, learn, and respond. At Codalien Technologies, […]

  • AI Chatbots for Sales Team Automation: The Critical Role of AI Sales Assistants in Automating Your Sales Team

    Sales teams are the heart of any successful business, but managing them effectively can often feel like trying to juggle flaming swords. The constant pressure to generate leads, maintain relationships, and close deals leaves your team overwhelmed, spending more time on administrative tasks than actual selling. Here’s where AI-powered sales assistants step in to completely […]

  • Transforming HR with AI Assistants: The Comprehensive Guide

    The role of Human Resources (HR) is critical for the smooth functioning of any organization, from handling administrative tasks to shaping workplace culture and driving strategic decisions. However, traditional methods often fall short of meeting the demands of a modern, dynamic workforce. This is where our Human Resource AI assistants enter —a game-changing tool that […]

  • How Conversational AI Chatbots Improve Conversion Rates in E-Commerce?

    The digital shopping experience has evolved, with Conversational AI Chatbots revolutionizing customer interactions in e-commerce. These AI-powered systems offer personalized, real-time communication with customers, streamlining the buying process and increasing conversion rates. But how do Conversational AI Chatbots improve e-commerce conversion rates, and what are the real benefits for customers? In this blog, we’ll break […]

Click to Copy