Elasticsearch + Nodejs Server Example

We are going to create a node server will acts as middle layer for Elasticsearch server. Before downloading require packages from NPM, we are going to download Elasticsearch executable file.

If you prefer video explanation then you can watch on YouTube (in English or in Hindi). 

I'm on my windows machine, so I would download a 64-bit windows' version of Elasticsearch, i.e https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-7.8.1-windows-x86_64.zip

You are free to download Elasticsearch as per your OS. Instructions would little different based on your OS. So, windows guys, we can extract the zip after our download. Now, we will go to bin folder of it and then run elasticsearch.bat. After few seconds, it will be up and running, then you can browse to http://localhost:9200/ Or you can do curl on PowerShell to see its health => 

curl -X GET "localhost:9200/_cat/health?v&pretty"

We are going to have bulk import a JSON file (accounts.json), which can be downloaded from github/elasticsearch

Then execute below command:

curl -H "Content-Type: application/json" -XPOST "localhost:9200/bank/_bulk?pretty&refresh" --data-binary "@accounts.json"

Now, we got the Elasticsearch server up and running with some data to play around. Lets' create a node server and do some full-text searching.

Create a folder named 'Search service' and open command line to install some NPM packages.

npm i express body-parser @elastic/elasticsearch --save

Create a js file name, name it 'server.js'. We will be importing express and creating a route to do full-text search. Write below code in the file.

const express = require('express');
const bodyParser = require('body-parser');
const app = express();

app.use(bodyParser.json());
app.use(
  bodyParser.urlencoded({
    extended: true,
  })
);


// searching on query
app.get('/search/:index/:type'async (reqres=> {
  const { phraseSearch } = require('./SearchEngine');
  const data = await phraseSearch(req.params.indexreq.params.typereq.query.q);
  res.json(data);
});

app.listen(3333, () => console.log('server running at 3333'));

You can see that we have imported a file 'SearchEngine.js' in the server.js. Lets create the file and import @elastic/elasticsearch and we will using multi_match in qyery params to get desired search result(s). Write below code in the file.

const { Client } = require('@elastic/elasticsearch');
const client = new Client({ node: 'http://localhost:9200' });

const phraseSearch = async (_index_typephrase=> {
  const hits = [];

  // only string values are searchable
  const searchResult = await client
    .search({
      index: _index,
      type: _type,
      body: {
        query: {
          multi_match: {
            fields: [
              'firstname',
              'lastname',
              'gender',
              'employer',
              'email',
              'city',
              'state',
              'address',
            ],
            query: phrase,
            type: 'phrase_prefix',
            //lenient: true
          },
        },
        highlight: {
          fields: {
            firstname: {},
            lastname: {},
            gender: {},
            employer: {},
            email: {},
            city: {},
            state: {},
            address: {},
          },
        },
      },
    })
    .catch((e=> console.log('errr'e));
  if (
    searchResult &&
    searchResult.body &&
    searchResult.body.hits &&
    searchResult.body.hits.hits &&
    searchResult.body.hits.hits.length > 0
  ) {
    hits.push(...searchResult.body.hits.hits);
  }

  return {
    hitsCount: hits.length,
    hits,
  };
};

module.exports = {
  phraseSearch
};

We are all set to start the node server. Open command line and run npm start.

Then you can use any browser or postman to hits an endpoint to do full-text searching. e.g. http://localhost:3333/search/bank/_doc?q=mill




Comments

Popular Posts