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

  • How to Implement In-Order, Pre-Order, and Post-Order Tree Traversal in Python?

    Tree traversal is an essential operation in many tree-based data structures. In binary trees, the most common traversal methods are in-order traversal, pre-order traversal, and post-order traversal. Understanding these tree traversal techniques is crucial for tasks such as tree searching, tree printing, and more complex operations like tree serialization. In this detailed guide, we will […]

  • Mastering Merge Sort: A Comprehensive Guide to Efficient Sorting

    Are you eager to enhance your coding skills by mastering one of the most efficient sorting algorithms? If so, delve into the world of merge sort in Python. Known for its powerful divide-and-conquer strategy, merge sort is indispensable for efficiently handling large datasets with precision. In this detailed guide, we’ll walk you through the complete […]

  • Optimizing Chatbot Performance: KPIs to Track Chatbot Accuracy

    In today’s digital age, chatbots have become integral to customer service, sales, and user engagement strategies. They offer quick responses, round-the-clock availability, and the ability to handle multiple users simultaneously. However, the effectiveness of a chatbot hinges on its accuracy and conversational abilities. Therefore, it is necessary to ensure your chatbot performs optimally, tracking and […]

  • Reinforcement Learning: From Q-Learning to Deep Q-Networks

    In the ever-evolving field of artificial intelligence (AI), Reinforcement Learning (RL) stands as a pioneering technique enabling agents (entities or software algorithms) to learn from interactions with an environment. Unlike traditional machine learning methods reliant on labeled datasets, RL focuses on an agent’s ability to make decisions through trial and error, aiming to optimize its […]

  • Understanding AI Predictions with LIME and SHAP- Explainable AI Techniques

    As artificial intelligence (AI) systems become increasingly complex and pervasive in decision-making processes, the need for explainability and interpretability in AI models has grown significantly. This blog provides a comprehensive review of two prominent techniques for explainable AI: Local Interpretable Model-agnostic Explanations (LIME) and Shapley Additive Explanations (SHAP). These techniques enhance transparency and accountability by […]

  • Building and Deploying a Custom Machine Learning Model: A Comprehensive Guide

    Machine Learning models are algorithms or computational models that act as powerful tools. Simply put, a Machine Learning model is used to automate repetitive tasks, identify patterns, and derive actionable insights from large datasets. Due to these hyper-advanced capabilities of Machine Learning models, it has been widely adopted by industries such as finance and healthcare.  […]

Click to Copy