NodeJS Elasticsearch FullText Search

·

2 min read

Continuing on some of the previous similiar integrations with Elasticsearch, Python and Spring. In this we will simply connect to Elasticsearch via NodeJS.

Pre-requistes:

NodeJS - You can download from https://nodejs.org/en/download

ElasticSearch - 7.X

Node: I am still using Elasticsearch(ES), newer version of ES is available.

Setup:

npm install elasticsearch

Edit app.js file

const { Client } = require('@elastic/elasticsearch');

// Create Elasticsearch client
const client = new Client({ node: 'http://localhost:9200' }); // Change the URL if your Elasticsearch instance is running on a different port or host

// Define the index and type you want to search in
const index = 'your_index_name';

Replace 'your_index_name' with your actual index name

You can provide authentication, if you are using,

// Create Elasticsearch client with API Key
const client = new Client({
  node: 'https://your-elasticsearch-url', // Replace with your Elasticsearch URL
  auth: {
    apiKey: 'your-api-key' // Replace with your actual API Key
  }
});

Now Lets create a method, that will perform a simple search:

// Perform a full-text search
async function searchDropdown(query) {
  try {
    const { body } = await client.search({
      index,
      body: {
        query: {
          match: {
            // Customize the field you want to search in
            fieldName: {
              query: query,
              fuzziness: 'auto' // You can adjust fuzziness for approximate matching
            }
          }
        }
      }
    });

    // Process the response and extract the relevant data for your dropdown
    const dropdownData = body.hits.hits.map(hit => ({
      id: hit._id,
      text: hit._source.fieldName // Customize this based on your Elasticsearch mapping
      // You can include more fields or modify the structure of dropdownData as needed
    }));

    return dropdownData;
  } catch (error) {
    console.error('Error performing search:', error);
    return [];
  }
}

Now lets call the method, to make it simple i am just making a method call, but you choose to make it in a API call, or other modes:

const searchTerm = 'search term'; 
searchDropdown(searchTerm)
  .then(results => {
    console.log('Dropdown data:', results);
  })
  .catch(err => {
    console.error('Error:', err);
  });

This summarises the simple ES integration with NodeJS, but this can be futher extended with functionalities, similar to what i have shared before.

You make find my previous articles:

https://shahsmit.hashnode.dev/?source=top_nav_blog_home