9 min read

Introduction to Elasticsearch

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…

September 7, 2020

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.

Since we’ve already set up Docker Compose, 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#
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#
(...)
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.

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#
(...)
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#
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#
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#
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#
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#
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#
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#
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#
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:

ctx._source.title='New title'; ctx._source.content= 'New content';

We can create the above script dynamically.

/src/posts/postsSearch.service.ts#
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#
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!

Introduction to Elasticsearch | NestJS.io