API with NestJS #12. Introduction to Elasticsearch

JavaScript NestJS TypeScript

This entry is part 12 of 177 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.

docker-compose.yml

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:

docker-compose.yml

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.

.env

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

/src/search/search.module.ts

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.

/src/posts/types/postSearchBody.interface.ts

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

/src/posts/types/postSearchBody.interface.ts

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

/src/posts/postsSearch.service.ts

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 .

/src/posts/posts.service.ts

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

/src/posts/posts.controller.ts

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.

/src/posts/postsSearch.service.ts

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

/src/posts/posts.service.ts

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.

/src/posts/postsSearch.service.ts

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

/src/posts/posts.service.ts

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.

Summary

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 >>
Subscribe
Notify of
guest
15 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Rafael Morales
Rafael Morales
3 years 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
3 years 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.

rahsut
rahsut
3 years 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
3 years 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

Stephanie
Stephanie
2 years ago

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

Akifcan Kara
Akifcan Kara
2 years 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

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

Harsh
Harsh
2 years ago

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

Endress
Endress
1 year ago
Reply to  Harsh

Hi did you find a solution about this issue ? I’m currently facing the same issue :/

ChauVanLoc
ChauVanLoc
6 months ago
Reply to  Endress

Ensure elasticsearch in source and docker same version

crazyoptimist
2 years ago

Thank you it helped a lot!

crazyoptimist
2 years 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 2 years ago by crazyoptimist
crazyoptimist
2 years 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:
https://stackoverflow.com/questions/72063044/id-field-is-missing-from-search-result-in-elasticsearch

Last edited 2 years ago by crazyoptimist
Shamim
2 years 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
2 years 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

Rajasekhar
Rajasekhar
1 year ago

What is there inside post.entity??