Using Elasticsearch in Node.js

Author - Webner
3.12.2020
|
0 Comments
||

What is elasticsearch?

Elasticsearch is a distributed, open-source search and analytics engine for all types of data, including textual, numerical, geospatial, structured, and unstructured. Elasticsearch is built on Apache Lucene and was first released in 2010 by Elasticsearch N.V. (now known as Elastic). Known for its simple REST APIs, distributed nature, speed, and scalability, Elasticsearch is the central component of the Elastic Stack, a set of open-source tools for data ingestion, enrichment, storage, analysis, and visualization. Commonly referred to as the ELK Stack (after Elasticsearch, Logstash, and Kibana), the Elastic Stack now includes a rich collection of lightweight shipping agents known as Beats for sending data to Elasticsearch.

Node.js, a popular JavaScript server-side solution based on event-driven architecture efficient for the development of fast servers, I/O heavy applications, and real-time applications (RTAs). Node.js ecosystem is one of the fastest-growing and it is now possible to interact with the Elasticsearch API using a Node.js client.
Elasticsearch.js is the official Elasticsearch client for Node.js that ships with:

  • one-to-one mapping with Elasticsearch REST API
  • intelligent handling of node/connection failures
  • support for load balancers
  • integration into modern browsers
  • efficient support for asynchronous operations with JavaScript Promises.

Installation
You can install the official elasticsearch.js module via npm (Node Package Manager) command:
npm install elasticsearch

Usage
Using the elasticsearch.js module in Node we can easily connect to and interact with our Elasticsearch cluster on Qbox.io:
var elasticsearch = require('elasticsearch');
var client = new elasticsearch.Client({
hosts: [ 'https://username:password@host:port'] });

The client constructor accepts a config object/hash where you can define defaults parameters, or even entire classes, for the client to use. In addition, our client variable inherits all methods of the elasticsearch.js Client constructor which corresponds to the official Elasticsearch API.
We can now ping to our Qbox.io cluster to check if everything is ok.
client.ping({
requestTimeout: 30000,
}, function(error) {
if (error) {
console.error('elasticsearch cluster is down!');
} else {
console.log('Everything is ok');
}
});

Features of Elasticsearch

Indexing
Unlike conventional databases, an Elasticsearch index is a place to store related documents. In this example, we’re going to create an index ‘blog’ to store ‘posts’ in it. With elasticsearch.js it can be done as easy as that:

client.indices.create({
index: 'blog'
}, function(err, resp, status) {
if (err) {
console.log(err);
} else {
console.log("create", resp);
}
});

If the index already exists, you get ‘index_already_exists_exception’. Otherwise, a new index ready to store your documents is created.

Search Documents using Query Param

Elasticsearch.js has mature search functionality that supports both simple queries and Elasticsearch Query DSL. To search documents using a simple query you need to specify a ‘q’ parameter in your request object. In this example, we are searching for all posts with “Node.js” in the post title.

client.search({
index: 'blog',
type: 'posts',
q: 'PostName:Node.js'
}).then(function(resp) {
console.log(resp);
}, function(err) {
console.trace(err.message);
});

Elasticsearch Query DSL

If you want to have fine-grained control over document search, Elasticsearch offers a query DSL.

client.search({
index: 'blog',
type: 'posts',
body: {
query: {
match: {
"PostName": 'Node.js'
}
}
}
}).then(function(resp) {
console.log(resp);
}, function(err) {
console.trace(err.message);
});

A successful response looks like this:
{ took: 407,
timed_out: false,
_shards: { total: 4, successful: 4, failed: 0 },
hits: { total: 1, max_score: 0.26742277, hits: [ [Object] ] } }

If no documents match the query, Qbox ElasticSearch returns:
{ took: 69,
timed_out: false,
_shards: { total: 4, successful: 4, failed: 0 },
hits: { total: 0, max_score: null, hits: [] } }

Elasticsearch.js supports all Query DSL features including leaf clauses and compound clauses.

Elasticsearch.js is a very mature Elasticsearch client for Node.js able to handle basic use cases and supporting many advanced ones. In addition to the aforementioned functionality, elasticsearch.js supports searching of shards, scrolling, bulk operations in a single API call, and more.

Webner Solutions is a Software Development company focused on developing Insurance Agency Management Systems, Learning Management Systems and Salesforce apps. Contact us at dev@webners.com for your Insurance, eLearning and Salesforce applications.

Leave a Reply

Your email address will not be published. Required fields are marked *