AskHandle

AskHandle Blog

How Do I Implement Text Search with Elasticsearch in a Node.js Application?

December 7, 2025Lillian Kim3 min read

How Do I Implement Text Search with Elasticsearch in a Node.js Application?

Text search is a common requirement in many web applications. When working with Node.js and Elasticsearch, you can create powerful search features that perform well even with large amounts of data. This article shows you how to set up and use Elasticsearch with Node.js to add text search to your application.

Setting Up the Environment

First, make sure you have Elasticsearch installed and running on your system. You'll also need to install the official Elasticsearch client for Node.js. In your project directory, run:

bash
1npm install @elastic/elasticsearch

Create a connection to your Elasticsearch instance using the client:

javascript
1const { Client } = require('@elastic/elasticsearch')
2const client = new Client({
3  node: 'http://localhost:9200'
4})

Creating an Index

Before you can search for documents, you need to create an index and define its mapping. The mapping tells Elasticsearch how to handle different fields in your documents:

javascript
1async function createIndex() {
2  await client.indices.create({
3    index: 'products',
4    body: {
5      mappings: {
6        properties: {
7          name: { type: 'text' },
8          description: { type: 'text' },
9          price: { type: 'float' },
10          category: { type: 'keyword' }
11        }
12      }
13    }
14  })
15}

Adding Documents

You can add documents to your index using the index API:

javascript
1async function addDocument(product) {
2  await client.index({
3    index: 'products',
4    body: product
5  })
6}

A basic search implementation might look like this:

javascript
1async function searchProducts(searchTerm) {
2  const result = await client.search({
3    index: 'products',
4    body: {
5      query: {
6        multi_match: {
7          query: searchTerm,
8          fields: ['name', 'description']
9        }
10      }
11    }
12  })
13  
14  return result.hits.hits
15}

Advanced Search Features

You can enhance your search functionality with additional features:

Fuzzy Matching

Fuzzy matching helps catch spelling mistakes and variations:

javascript
1async function fuzzySearch(searchTerm) {
2  const result = await client.search({
3    index: 'products',
4    body: {
5      query: {
6        fuzzy: {
7          name: {
8            value: searchTerm,
9            fuzziness: 2
10          }
11        }
12      }
13    }
14  })
15}

Filtering Results

You can add filters to narrow down search results:

javascript
1async function filteredSearch(searchTerm, minPrice, maxPrice) {
2  const result = await client.search({
3    index: 'products',
4    body: {
5      query: {
6        bool: {
7          must: {
8            multi_match: {
9              query: searchTerm,
10              fields: ['name', 'description']
11            }
12          },
13          filter: {
14            range: {
15              price: {
16                gte: minPrice,
17                lte: maxPrice
18              }
19            }
20          }
21        }
22      }
23    }
24  })
25}

Error Handling

Always include error handling in your search implementation:

javascript
1async function safeSearch(searchTerm) {
2  try {
3    const result = await client.search({
4      index: 'products',
5      body: {
6        query: {
7          multi_match: {
8            query: searchTerm,
9            fields: ['name', 'description']
10          }
11        }
12      }
13    })
14    return result.hits.hits
15  } catch (error) {
16    console.error('Search error:', error)
17    throw new Error('Search failed')
18  }
19}

Performance Tips

To get the best performance from your Elasticsearch implementation:

  1. Use batch operations when indexing multiple documents
  2. Set proper field types in your mappings
  3. Use filter contexts when possible instead of query contexts
  4. Limit the number of fields you search across
  5. Use pagination to limit result sizes

Implementing text search with Elasticsearch in Node.js requires proper setup and configuration, but the