API with NestJS #12. Introduction to Elasticsearch

JavaScript NestJS TypeScript

This entry is part 12 of 85 in the API with NestJS

We can find some searching functionalities in a lot of web applications. While we might be fine when iterating through a small data set, the performance for more extensive databases can become an issue. Relational databases might prove to be relatively slow when searching through a lot of data.

A solution to the above problem might be Elasticsearch. It is a search engine that highly focuses on performance. When using it, we maintain a separate document-oriented database.

If you are familiar with MongoDB, document-oriented databases will ring a bell for you. In theory, we might use Elasticsearch as a general-purpose database. It wasn’t designed for this purpose, though. If you would like to read more about it, check out this question on Stackoverflow.

Running Elasticsearch

Running Elasticsearch includes maintaining a separate, search-optimized database. Because of that, we need to choose one of the ways to fire it up.

In the second part of this series, we’ve started using Docker Compose. Therefore, a fitting way to start using Elasticsearch would be to do so through Docker. When we go to the official Elasticsearch documentation, we can see an example using Docker Compose. It includes three nodes.

An Elasticsearch cluster is a group of one or more Elasticsearch nodes connected. Each node is an instance of Elasticsearch.

Let’s add the above official configuration to our existing file.


You might run into an issue when doing the above: . There is a high chance that increasing the   will help, as described here.

By default, the password for Elasticsearch is  . To set up a password, we can add it to our   file:


The default username is “elastic

Connecting to Elasticsearch in NestJS

To use Elasticsearch within our NestJS project, we can use the official @nestjs/elasticsearch library.

It wraps the @elastic/elasticsearch client. Since it is a peer dependency of @nestjs/elasticsearch, we need to install it.

Don’t confuse it with the “elasticsearch” client that will soon be deprecated.

Due to how we did set up Elesticsearch, our cluster is available at  . Our username is  , and the password is  . We need to add all of the above to our environment variables.


Now we can create our module that uses the above configuration.


We export the   above so that we are able to use some of its features when importing   as suggested here

Populating Elasticsearch with data

The first thing to consider when populating Elasticsearch with data is the concept of the index. In the context of Elasticsearch, we group similar documents by assigning them with the same index.

In the previous versions of Elasticsearch we also used types to group documents, but this concept is being abandoned

When populating the Elasticsearch database with data, we throw in only the parts that we later use when searching. Let’s create an interface for that purpose.


The TypeScript support with Elasticsearch is not that good, unfortunately. Following the official documentation, we can create a search response type for our posts.


When we’re done with the above, we can create a service that takes care of interacting with our Elasticsearch cluster.


Above we use   becase we want to search both through the title and the content of the posts

The crucial thing to acknowledge about   is that it returns just the properties that we’ve put into the Elasticsearch database. Since we save the ids of the posts, we can now get the whole documents from our Postgres database. Let’s put this logic into .


The last thing to do is to modify the controller so that it accepts a query parameter.


Don’t forget to import the  in the  .

Keeping Elasticsearch consistent with our database

Through our API, we can also edit and delete posts. Therefore, we need to put some effort into keeping the Elasticsearch database consistent with our Postgres instance.

Deleting documents

Since we save the id of the post in our Elasticsearch database, we can use it to find it and delete it. To do so, we can use the   function.


Let’s call the above method in   every time we delete a post.


Modifying documents

The other thing to make sure that the Elasticsearch database is consistent with our main database is to modify existing documents. To do that, we can use the  function.

Unfortunately, we need to write a script that updates all of the necessary fields. For example, to update the title and the content, we need:

We can create the above script dynamically.


Now we need to use the above method whenever we modify existing posts.


The Elasticsearch documents also have ids. An alternative to the above deletes and updates would be to store the Elasticsearch id in our Postgres database and use it when deleting and updating.


Today we’ve learned the very basics of Elasticsearch. When doing so, we’ve added it to our NestJS API. We’ve also created our documents and searched through them. All of that is the tip of the Elasticsearch iceberg. There is a lot more to learn here, so stay tuned!

Series Navigation<< API with NestJS #11. Managing private files with Amazon S3API with NestJS #13. Implementing refresh tokens using JWT >>
Notify of
Newest Most Voted
Inline Feedbacks
View all comments
Rafael Morales
Rafael Morales
1 year ago

Is there a way to implement tests for the PostsSearchService , since it will require you to instantiate the elasticsearchService dependency on its constructor?

Jean Bosco
Jean Bosco
1 year ago
Reply to  Rafael Morales

Hello. @Rafael,
Yes, you can be able to test this service with a help of TestingModule from @nestjs/testing, you can be able to override a provide and set its expected return values, or using the Jest library you can spy on the instance of that injected elastic search service.

1 year ago

How can I add/sync existing data to elasticsearch? So is there any package available for nestJS or I have to do it in another way? If that then can you please suggest me?

Marcelo Amorim
1 year ago
Reply to  rahsut

Hi @rasut,

Here we usually use two forms and it depends of your necessity:

  1. Use Logstash (another ELK service) to run ETL process scheduled at container like a cron;
  2. Create a NodeJS code to stream all the documents programatically using the Nest implementation as described by the author.

Best regards

10 months ago

Ehm, how do we use the elastic search in nestjs? 🙂

Akifcan Kara
Akifcan Kara
8 months ago

Thank you so much this article is very helpful. I want to share solution an error if someone faced unknown product error. you have to have same versions with elastic and client ex

image: docker.elastic.co/elasticsearch/elasticsearch:7.11.1
@elastic/elasticsearch: “^7.11.0”,

7 months ago

I am getting a error like this
“Cannot read property ‘cloud’ of undefined”
in my nestjs

7 months ago

Thank you it helped a lot!

7 months ago

“id” field is not showing up in the search result items. I’m using elasticsearch v8.1.3.
Is this only for me or anyone having the same issue?

Thanks in advance.

Last edited 7 months ago by crazyoptimist
7 months ago

Never mind, found out what I was doing wrong.
In order to index id of a post item, you need to save it into the db first and index the saved result, you won’t get id until it’s saved.
For more detailed one:

Last edited 7 months ago by crazyoptimist
6 months ago

If you are wondering how to set up the latest version (8.2.1 at this time) of ElasticSearch using docker and implement the above. You can follow this repo https://github.com/shamscorner/nest-stackter

By the way, body implementation on ElasticSearch is deprecated. So there are some changes to the latest versions. You will find everything on the mentioned repo.

Apisit Lee
Apisit Lee
4 months ago

What should I do if I have 3 modules (such as Books, Cars, Animals) and want to search them in one request? Just mix them.
The request may look like: https://api.xxx.com/search?fields=books,cars,animals&search=puma&offset=20&limit=20