- 1. API with NestJS #1. Controllers, routing and the module structure
- 2. API with NestJS #2. Setting up a PostgreSQL database with TypeORM
- 3. API with NestJS #3. Authenticating users with bcrypt, Passport, JWT, and cookies
- 4. API with NestJS #4. Error handling and data validation
- 5. API with NestJS #5. Serializing the response with interceptors
- 6. API with NestJS #6. Looking into dependency injection and modules
- 7. API with NestJS #7. Creating relationships with Postgres and TypeORM
- 8. API with NestJS #8. Writing unit tests
- 9. API with NestJS #9. Testing services and controllers with integration tests
- 10. API with NestJS #10. Uploading public files to Amazon S3
- 11. API with NestJS #11. Managing private files with Amazon S3
- 12. API with NestJS #12. Introduction to Elasticsearch
- 13. API with NestJS #13. Implementing refresh tokens using JWT
- 14. API with NestJS #14. Improving performance of our Postgres database with indexes
- 15. API with NestJS #15. Defining transactions with PostgreSQL and TypeORM
- 16. API with NestJS #16. Using the array data type with PostgreSQL and TypeORM
- 17. API with NestJS #17. Offset and keyset pagination with PostgreSQL and TypeORM
- 18. API with NestJS #18. Exploring the idea of microservices
- 19. API with NestJS #19. Using RabbitMQ to communicate with microservices
- 20. API with NestJS #20. Communicating with microservices using the gRPC framework
- 21. API with NestJS #21. An introduction to CQRS
- 22. API with NestJS #22. Storing JSON with PostgreSQL and TypeORM
- 23. API with NestJS #23. Implementing in-memory cache to increase the performance
- 24. API with NestJS #24. Cache with Redis. Running the app in a Node.js cluster
- 25. API with NestJS #25. Sending scheduled emails with cron and Nodemailer
- 26. API with NestJS #26. Real-time chat with WebSockets
- 27. API with NestJS #27. Introduction to GraphQL. Queries, mutations, and authentication
- 28. API with NestJS #28. Dealing in the N + 1 problem in GraphQL
- 29. API with NestJS #29. Real-time updates with GraphQL subscriptions
- 30. API with NestJS #30. Scalar types in GraphQL
- 31. API with NestJS #31. Two-factor authentication
- 32. API with NestJS #32. Introduction to Prisma with PostgreSQL
- 33. API with NestJS #33. Managing PostgreSQL relationships with Prisma
- 34. API with NestJS #34. Handling CPU-intensive tasks with queues
- 35. API with NestJS #35. Using server-side sessions instead of JSON Web Tokens
- 36. API with NestJS #36. Introduction to Stripe with React
- 37. API with NestJS #37. Using Stripe to save credit cards for future use
- 38. API with NestJS #38. Setting up recurring payments via subscriptions with Stripe
- 39. API with NestJS #39. Reacting to Stripe events with webhooks
- 40. API with NestJS #40. Confirming the email address
- 41. API with NestJS #41. Verifying phone numbers and sending SMS messages with Twilio
- 42. API with NestJS #42. Authenticating users with Google
- 43. API with NestJS #43. Introduction to MongoDB
- 44. API with NestJS #44. Implementing relationships with MongoDB
- 45. API with NestJS #45. Virtual properties with MongoDB and Mongoose
- 46. API with NestJS #46. Managing transactions with MongoDB and Mongoose
- 47. API with NestJS #47. Implementing pagination with MongoDB and Mongoose
- 48. API with NestJS #48. Definining indexes with MongoDB and Mongoose
- 49. API with NestJS #49. Updating with PUT and PATCH with MongoDB and Mongoose
- 50. API with NestJS #50. Introduction to logging with the built-in logger and TypeORM
- 51. API with NestJS #51. Health checks with Terminus and Datadog
- 52. API with NestJS #52. Generating documentation with Compodoc and JSDoc
- 53. API with NestJS #53. Implementing soft deletes with PostgreSQL and TypeORM
- 54. API with NestJS #54. Storing files inside a PostgreSQL database
- 55. API with NestJS #55. Uploading files to the server
- 56. API with NestJS #56. Authorization with roles and claims
- 57. API with NestJS #57. Composing classes with the mixin pattern
- 58. API with NestJS #58. Using ETag to implement cache and save bandwidth
- 59. API with NestJS #59. Introduction to a monorepo with Lerna and Yarn workspaces
- 60. API with NestJS #60. The OpenAPI specification and Swagger
- 61. API with NestJS #61. Dealing with circular dependencies
- 62. API with NestJS #62. Introduction to MikroORM with PostgreSQL
- 63. API with NestJS #63. Relationships with PostgreSQL and MikroORM
- 64. API with NestJS #64. Transactions with PostgreSQL and MikroORM
- 65. API with NestJS #65. Implementing soft deletes using MikroORM and filters
- 66. API with NestJS #66. Improving PostgreSQL performance with indexes using MikroORM
- 67. API with NestJS #67. Migrating to TypeORM 0.3
- 68. API with NestJS #68. Interacting with the application through REPL
- 69. API with NestJS #69. Database migrations with TypeORM
- 70. API with NestJS #70. Defining dynamic modules
- 71. API with NestJS #71. Introduction to feature flags
- 72. API with NestJS #72. Working with PostgreSQL using raw SQL queries
- 73. API with NestJS #73. One-to-one relationships with raw SQL queries
- 74. API with NestJS #74. Designing many-to-one relationships using raw SQL queries
- 75. API with NestJS #75. Many-to-many relationships using raw SQL queries
- 76. API with NestJS #76. Working with transactions using raw SQL queries
- 77. API with NestJS #77. Offset and keyset pagination with raw SQL queries
- 78. API with NestJS #78. Generating statistics using aggregate functions in raw SQL
- 79. API with NestJS #79. Implementing searching with pattern matching and raw SQL
- 80. API with NestJS #80. Updating entities with PUT and PATCH using raw SQL queries
- 81. API with NestJS #81. Soft deletes with raw SQL queries
- 82. API with NestJS #82. Introduction to indexes with raw SQL queries
- 83. API with NestJS #83. Text search with tsvector and raw SQL
- 84. API with NestJS #84. Implementing filtering using subqueries with raw SQL
- 85. API with NestJS #85. Defining constraints with raw SQL
- 86. API with NestJS #86. Logging with the built-in logger when using raw SQL
- 87. API with NestJS #87. Writing unit tests in a project with raw SQL
- 88. API with NestJS #88. Testing a project with raw SQL using integration tests
- 89. API with NestJS #89. Replacing Express with Fastify
- 90. API with NestJS #90. Using various types of SQL joins
- 91. API with NestJS #91. Dockerizing a NestJS API with Docker Compose
- 92. API with NestJS #92. Increasing the developer experience with Docker Compose
- 93. API with NestJS #93. Deploying a NestJS app with Amazon ECS and RDS
- 94. API with NestJS #94. Deploying multiple instances on AWS with a load balancer
- 95. API with NestJS #95. CI/CD with Amazon ECS and GitHub Actions
- 96. API with NestJS #96. Running unit tests with CI/CD and GitHub Actions
- 97. API with NestJS #97. Introduction to managing logs with Amazon CloudWatch
- 98. API with NestJS #98. Health checks with Terminus and Amazon ECS
- 99. API with NestJS #99. Scaling the number of application instances with Amazon ECS
- 100. API with NestJS #100. The HTTPS protocol with Route 53 and AWS Certificate Manager
- 101. API with NestJS #101. Managing sensitive data using the AWS Secrets Manager
- 102. API with NestJS #102. Writing unit tests with Prisma
- 103. API with NestJS #103. Integration tests with Prisma
- 104. API with NestJS #104. Writing transactions with Prisma
- 105. API with NestJS #105. Implementing soft deletes with Prisma and middleware
- 106. API with NestJS #106. Improving performance through indexes with Prisma
- 107. API with NestJS #107. Offset and keyset pagination with Prisma
- 108. API with NestJS #108. Date and time with Prisma and PostgreSQL
- 109. API with NestJS #109. Arrays with PostgreSQL and Prisma
- 110. API with NestJS #110. Managing JSON data with PostgreSQL and Prisma
- 111. API with NestJS #111. Constraints with PostgreSQL and Prisma
- 112. API with NestJS #112. Serializing the response with Prisma
- 113. API with NestJS #113. Logging with Prisma
- 114. API with NestJS #114. Modifying data using PUT and PATCH methods with Prisma
- 115. API with NestJS #115. Database migrations with Prisma
- 116. API with NestJS #116. REST API versioning
- 117. API with NestJS #117. CORS – Cross-Origin Resource Sharing
- 118. API with NestJS #118. Uploading and streaming videos
- 119. API with NestJS #119. Type-safe SQL queries with Kysely and PostgreSQL
- 120. API with NestJS #120. One-to-one relationships with the Kysely query builder
- 121. API with NestJS #121. Many-to-one relationships with PostgreSQL and Kysely
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 |
version: "3" services: postgres: container_name: postgres image: postgres:latest ports: - "5432:5432" volumes: - /data/postgres:/data/postgres env_file: - docker.env networks: - postgres pgadmin: links: - postgres:postgres container_name: pgadmin image: dpage/pgadmin4 ports: - "8080:80" volumes: - /data/pgadmin:/root/.pgadmin env_file: - docker.env networks: - postgres es01: image: docker.elastic.co/elasticsearch/elasticsearch:7.9.1 container_name: es01 environment: - node.name=es01 - cluster.name=es-docker-cluster - discovery.seed_hosts=es02,es03 - cluster.initial_master_nodes=es01,es02,es03 - bootstrap.memory_lock=true - "ES_JAVA_OPTS=-Xms512m -Xmx512m" ulimits: memlock: soft: -1 hard: -1 volumes: - data01:/usr/share/elasticsearch/data ports: - 9200:9200 networks: - elastic es02: image: docker.elastic.co/elasticsearch/elasticsearch:7.9.1 container_name: es02 environment: - node.name=es02 - cluster.name=es-docker-cluster - discovery.seed_hosts=es01,es03 - cluster.initial_master_nodes=es01,es02,es03 - bootstrap.memory_lock=true - "ES_JAVA_OPTS=-Xms512m -Xmx512m" ulimits: memlock: soft: -1 hard: -1 volumes: - data02:/usr/share/elasticsearch/data networks: - elastic es03: image: docker.elastic.co/elasticsearch/elasticsearch:7.9.1 container_name: es03 environment: - node.name=es03 - cluster.name=es-docker-cluster - discovery.seed_hosts=es01,es02 - cluster.initial_master_nodes=es01,es02,es03 - bootstrap.memory_lock=true - "ES_JAVA_OPTS=-Xms512m -Xmx512m" ulimits: memlock: soft: -1 hard: -1 volumes: - data03:/usr/share/elasticsearch/data networks: - elastic volumes: data01: driver: local data02: driver: local data03: driver: local networks: postgres: driver: bridge elastic: driver: bridge |
You might run into an issue when doing the above: es01 exited with code 78. There is a high chance that increasing the vm.max_map_count will help, as described here.
By default, the password for Elasticsearch is changeme. To set up a password, we can add it to our docker.env file:
docker-compose.yml
1 2 |
(...) ELASTIC_PASSWORD=admin |
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.
1 |
npm install @nestjs/elasticsearch @elastic/elasticsearch |
Due to how we did set up Elesticsearch, our cluster is available at http://localhost:9200. Our username is elastic, and the password is admin. We need to add all of the above to our environment variables.
.env
1 2 3 4 |
(...) ELASTICSEARCH_NODE=http://localhost:9200 ELASTICSEARCH_USERNAME=elastic ELASTICSEARCH_PASSWORD=admin |
Now we can create our module that uses the above configuration.
/src/search/search.module.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
import { Module } from '@nestjs/common'; import { ConfigModule, ConfigService } from '@nestjs/config'; import { ElasticsearchModule } from '@nestjs/elasticsearch'; @Module({ imports: [ ConfigModule, ElasticsearchModule.registerAsync({ imports: [ConfigModule], useFactory: async (configService: ConfigService) => ({ node: configService.get('ELASTICSEARCH_NODE'), auth: { username: configService.get('ELASTICSEARCH_USERNAME'), password: configService.get('ELASTICSEARCH_PASSWORD'), } }), inject: [ConfigService], }), ], exports: [ElasticsearchModule] }) export class SearchModule {} |
We export the ElasticsearchModule above so that we are able to use some of its features when importing SearchModule 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
1 2 3 4 5 6 |
interface PostSearchBody { id: number, title: string, content: string, authorId: number } |
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
1 2 3 4 5 6 7 8 9 10 |
import PostSearchBody from './postSearchBody.interface'; interface PostSearchResult { hits: { total: number; hits: Array<{ _source: PostSearchBody; }>; }; } |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
import { Injectable } from '@nestjs/common'; import { ElasticsearchService } from '@nestjs/elasticsearch'; import Post from './post.entity'; import PostSearchResult from './types/postSearchResponse.interface'; import PostSearchBody from './types/postSearchBody.interface'; @Injectable() export default class PostsSearchService { index = 'posts' constructor( private readonly elasticsearchService: ElasticsearchService ) {} async indexPost(post: Post) { return this.elasticsearchService.index<PostSearchResult, PostSearchBody>({ index: this.index, body: { id: post.id, title: post.title, content: post.content, authorId: post.author.id } }) } async search(text: string) { const { body } = await this.elasticsearchService.search<PostSearchResult>({ index: this.index, body: { query: { multi_match: { query: text, fields: ['title', 'content'] } } } }) const hits = body.hits.hits; return hits.map((item) => item._source); } } |
Above we use multi_match becase we want to search both through the title and the content of the posts
The crucial thing to acknowledge about elasticsearchService.search 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 PostsService.
/src/posts/posts.service.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
import { Injectable } from '@nestjs/common'; import CreatePostDto from './dto/createPost.dto'; import Post from './post.entity'; import { InjectRepository } from '@nestjs/typeorm'; import { Repository, In } from 'typeorm'; import User from '../users/user.entity'; import PostsSearchService from './postsSearch.service'; @Injectable() export default class PostsService { constructor( @InjectRepository(Post) private postsRepository: Repository<Post>, private postsSearchService: PostsSearchService ) {} // (...) async createPost(post: CreatePostDto, user: User) { const newPost = await this.postsRepository.create({ ...post, author: user }); await this.postsRepository.save(newPost); this.postsSearchService.indexPost(newPost); return newPost; } async searchForPosts(text: string) { const results = await this.postsSearchService.search(text); const ids = results.map(result => result.id); if (!ids.length) { return []; } return this.postsRepository .find({ where: { id: In(ids) } }); } } |
The last thing to do is to modify the controller so that it accepts a query parameter.
/src/posts/posts.controller.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
import { Controller, Get, UseInterceptors, ClassSerializerInterceptor, Query, } from '@nestjs/common'; import PostsService from './posts.service'; @Controller('posts') @UseInterceptors(ClassSerializerInterceptor) export default class PostsController { constructor( private readonly postsService: PostsService ) {} @Get() async getPosts(@Query('search') search: string) { if (search) { return this.postsService.searchForPosts(search); } return this.postsService.getAllPosts(); } // (...) } |
Don’t forget to import the SearchModule in the PostsModule.
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 deleteByQuery function.
/src/posts/postsSearch.service.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
import { Injectable } from '@nestjs/common'; import { ElasticsearchService } from '@nestjs/elasticsearch'; @Injectable() export default class PostsSearchService { index = 'posts' constructor( private readonly elasticsearchService: ElasticsearchService ) {} // (...) async remove(postId: number) { this.elasticsearchService.deleteByQuery({ index: this.index, body: { query: { match: { id: postId, } } } }) } } |
Let’s call the above method in PostsService every time we delete a post.
/src/posts/posts.service.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
import { Injectable } from '@nestjs/common'; import Post from './post.entity'; import { InjectRepository } from '@nestjs/typeorm'; import { Repository, In } from 'typeorm'; import PostNotFoundException from './exceptions/postNotFound.exception'; import PostsSearchService from './postsSearch.service'; @Injectable() export default class PostsService { constructor( @InjectRepository(Post) private postsRepository: Repository<Post>, private postsSearchService: PostsSearchService ) {} // (...) async deletePost(id: number) { const deleteResponse = await this.postsRepository.delete(id); if (!deleteResponse.affected) { throw new PostNotFoundException(id); } await this.postsSearchService.remove(id); } } |
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 updateByQuery 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:
1 |
ctx._source.title='New title'; ctx._source.content= 'New content'; |
We can create the above script dynamically.
/src/posts/postsSearch.service.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
import { Injectable } from '@nestjs/common'; import { ElasticsearchService } from '@nestjs/elasticsearch'; import Post from './post.entity'; import PostSearchBody from './types/postSearchBody.interface'; @Injectable() export default class PostsSearchService { index = 'posts' constructor( private readonly elasticsearchService: ElasticsearchService ) {} // (...) async update(post: Post) { const newBody: PostSearchBody = { id: post.id, title: post.title, content: post.content, authorId: post.author.id } const script = Object.entries(newBody).reduce((result, [key, value]) => { return `${result} ctx._source.${key}='${value}';`; }, ''); return this.elasticsearchService.updateByQuery({ index: this.index, body: { query: { match: { id: post.id, } }, script: { inline: script } } }) } } |
Now we need to use the above method whenever we modify existing posts.
/src/posts/posts.service.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
import { Injectable } from '@nestjs/common'; import Post from './post.entity'; import UpdatePostDto from './dto/updatePost.dto'; import { InjectRepository } from '@nestjs/typeorm'; import { Repository, In } from 'typeorm'; import PostNotFoundException from './exceptions/postNotFound.exception'; import PostsSearchService from './postsSearch.service'; @Injectable() export default class PostsService { constructor( @InjectRepository(Post) private postsRepository: Repository<Post>, private postsSearchService: PostsSearchService ) {} async updatePost(id: number, post: UpdatePostDto) { await this.postsRepository.update(id, post); const updatedPost = await this.postsRepository.findOne(id, { relations: ['author'] }); if (updatedPost) { await this.postsSearchService.update(updatedPost); return updatedPost; } throw new PostNotFoundException(id); } } |
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!
Is there a way to implement tests for the PostsSearchService , since it will require you to instantiate the elasticsearchService dependency on its constructor?
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.
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?
Hi @rasut,
Here we usually use two forms and it depends of your necessity:
Best regards
Ehm, how do we use the elastic search in nestjs? 🙂
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”,
Hi
I am getting a error like this
“Cannot read property ‘cloud’ of undefined”
in my nestjs
Thank you it helped a lot!
“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.
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
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.
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
What is there inside post.entity??