In this post, we’ll walk through a NestJS application that tracks your favorite movie titles, which also happen to be the set of movie titles uploaded to Kaggle by Cornell University in their Movie Dialog Corpus.
Throughout this series, we'll walk through some of the problems that you'll encounter as you deploy and manage a growing search database: things like keeping your search database in-sync with your relational database, creating pipelines, and more.
If you're here, you already know that search is essential to delivering a fast and intuitive experience for your users. Whether you're handling product catalogs, user-generated content, or large datasets, adding search to your NestJS application can take your app to the next level. Finding the right tools to get started can be a little time-consuming, though, so we're working on a series of tutorials to help navigate the path from zero to one.
We're going to start at day 0: demonstrating how to easily integrate Elasticsearch or OpenSearch into your NestJS app and seed it with a static dataset from your application.
Day 0: Getting started with the Bonsai Movie App
Today, we'll be working with a back-end Node.js application built with the progressive NestJS framework. For those unfamiliar, NestJS has grown in popularity in-part due to its opinionated and modular nature. While we'll cover other back-end frameworks in the future, Nest's opinionated nature also lends itself to being a fantastic starting point for our series.
Getting the code
To get started, you'll need to clone our example code repository at https://github.com/omc/bonsai-examples!
Once you've cloned the repository, check out the nestjs/pre-search branch -
we'll work our way forwards to parity with
the nestjs/with-elasticsearch branch in the coming sections!
# Fetch the remote git branches
# Switch to the nestjs/pre-search branch
Finally, enter the back-end/nestjs directory: this appropriately named
directory is where we'll spend the duration
of the tutorial in!
A tour of the movies module
Our simple application is primarily, and only, responsible for serving up details about our favorite movies. We can find an individual movie's metadata if we know its exact title, or we can see all of the movies' data if we paginate over a series of responses.
The code responsible for handling this functionality lives within the movies module.
What we're interested in, specifically, is the fact that our
movies.controller.ts currently only supports two actions to fetch our movies:
- Get by
title(GET /api/v1/movies/:title) - Get all movies (
GET /api/v1/movies)
Our goal is simple, yet powerful: augment our application to allow us to search for a partial title match!
Set up and run the application locally
Now that we've got a little familiarity with the application's structure, let's go ahead and configure our development environment and start running the development server.
-
First, we'll need to copy the
env-examplefile to.env: -
Next, we'll install our application's dependencies:
-
Now we're ready to run a PostgreSQL database locally, via docker
# To run this detached, run `docker compose up -d postgres`, but beware of silent failures! -
Open another terminal, and run the database migrations:
-
Seed the database with our favorite movie titles. We'll revisit this piece in the next section!
-
And finally, start our development server:
Phew! After all of that, you should see terminal output similar to:
To confirm that your application is serving up the data we expect, try issuing a request to list a page of all of our favorite movies:
You should see a response like the following:
Which is great, because I need to pull up the details on a really great movie. But, I just can't seem to find it via exact-search. I think it's called, "The Third Element":
We'll see that it's either not there (unlikely), or I've misremembered the name (likely):
If only there was a way to get a search integrated into my application to help me remember some of my favorite movie titles...
Adding Elasticsearch/OpenSearch
With our application running, it's time to supercharge our application with a bit of search magic.
Setting up a local Elasticsearch/OpenSearch cluster
We'll be using Docker again to host the latest addition to our application stack: Elasticsearch.
From the following snippet of code, add the Elasticsearch service definition to
your docker-compose.yml file:
# Apache License v2.0, January 2004
# Courtesy of the CNCF project, Jaeger @ https://github.com/jaegertracing/jaeger
elasticsearch:
image: docker.elastic.co/elasticsearch/elasticsearch:7.10.2
environment:
- discovery.type=single-node
- http.host=0.0.0.0
- transport.host=127.0.0.1
- xpack.security.enabled=false # Disable security features
- xpack.security.http.ssl.enabled=false # Disable HTTPS
- action.destructive_requires_name=false
- xpack.monitoring.collection.enabled=false # Disable monitoring features
ports:
- "9200:9200"
Once you've saved that file, start both the postgres and elasticsearch
services:
And add these environment variables to your .env file:
ELASTICSEARCH_NODE=http://localhost:9200
ELASTICSEARCH_USERNAME=elastic
ELASTICSEARCH_PASSWORD=
Seeding Elasticsearch/OpenSearch with Movie Data
Since, at this stage of our application, we know all of our favorite movies
ahead-of-time, we're going to pursue a
straight-forward approach to synchronizing our search and relational databases:
after we've inserted all of our favorite
movies into the relational database, we'll turn-around and insert them into our
search database as well - the catch
being that they'll hold the same id attribute in both databases, making our
search query results directly
referential in our relational database!
Configuring Elasticsearch in the NestJS Application
Before we move into code, let's add a couple of relevant dependencies to our application:
And, we'll add relevant Elasticsearch connection configuration in
src/database/, alongside our PostgreSQL configuration, by creating a few
files:
src/database/config/search-config.type.ts
// src/database/config/search-config.type.ts
;
;
src/database/config/search.config.ts
// src/database/config/search.config.ts
;
;
;
;
;
;
;
src/database/search/search.module.ts
// src/database/search/search.module.ts
;
;
;
;
And, last but not least for configuration, we'll need to add the search configuration to our App's module:
// src/app.module.ts
;
;
;
;
;
;
;
;
;
;
;
;
Using Elasticsearch in the NestJS Application
Now that our application is configured to use Elasticsearch, we can get start
writing in our search features. We'll
begin by adding an interface that describes our movie-search-response items, in
src/movies/interfaces/movie-search-document.interface.ts.
// src/movies/interfaces/movie-search-document.interface.ts
Followed by a MoviesSearchService service in
src/movies/movies-search.service.ts file, which will encapsulate our
application's interactions with the
search database:
// src/movies/movies-search.service.ts
;
;
;
;
;
;
The MoviesSearchService currently provides a just a few of functions that will
enable us to load our
search database with movies, along with
some others that will help us determine the status of our index:
-
createIndex: to create our new inex. -
indexMovies: to bulk-add movies to the search index. -
count: to discover how many matches we have for a given query. -
search: to search for our document, with optional arguments like document offset, etc. -
existsIndex,statusIndex: to determine whether the index exists, and its status.
To use this new functionality, we'll take a detour out of our NestJS application
modules, and head over to src/database/seeds/, where we'll create a new directory: search.
This new search directory will hold the scripts responsible for seeding our
search database with
indexes after we've loaded our
relational database with movies.
We'll be adding similar files as to what's contained in the
src/database/seeds/relational directory, so let's also
create a sub-directory within search: src/database/seeds/search/movie.
Add these files in:
-
src/database/seeds/search/run-seed.ts- this file orchestrates our search-seeding routines// src/database/seeds/search/run-seed.ts ; ; ; ; void ; -
src/database/seeds/search/seed.module.ts// src/database/seeds/search/seed.module.ts ; ; ; ; ; ; ; ; ; -
src/database/seeds/search/movie/movie-seed.service.ts// src/database/seeds/search/movie/movie-seed.service.ts ; ; ; ; ; -
To support the newly used
findmethod, we'll add that method into ourMovieRepository:-
Add the abstract definition to
src/movies/infrastructure/persistence/movie.repository.ts:// src/movies/infrastructure/persistence/movie.repository.ts ... abstract options?: FindManyOptions: Promise; ... -
And add the implementation to
src/movies/infrastructure/persistence/relational/repositories/movie.repository.ts:// src/movies/infrastructure/persistence/relational/repositories/movie.repository.ts ... async options?: FindManyOptions: Promise ...
-
-
And we'll configure the
MovieSeedModulelocated atsrc/database/seeds/search/movie/movie-seed.module.ts// src/database/seeds/search/movie/movie-seed.module.ts ; ; ; ; ;
Once we've added this, we'll also add a command-line interface command to our
package.json, allowing us to trigger the seeding of our search database from
the command-line: add the following line to the scripts section of your
package.json:
And finally, let's go ahead and run that command to seed our search cluster with movie data!
We won't see much output at the command's terminal, but we can check via the Elasticsearch API to see that our favorite movies have been indexed:
Which responds something like the below (some metrics and IDs may be different)!
Unlocking Movie Search, our killer feature!
Now that our search database is loaded-up with our favorite movie details, we're ready to create a public interface to that functionality in our application!
Re-open the MoviesService service in the src/movies/movies.service.ts
file, because we're going to be adding one new, important, service:
search: to, well, search for a movie!
You'll note that the updated MoviesService class has a new constructor and
some additional imports - update yours to match
the below.
// src/movies/movies.service.ts
;
;
;
;
;
;
Next, since we want to provide the option of using a search query, but we still want our movies index response to be paginated either way, the query and response types will need to be tweaked slightly:
-
In the
src/utils/dto/infinity-pagination-response.dto.tsfile, we'll need to make thehasNextPagemember optional. Update that entry to reflect this diff (add the question mark inhasNextPage?:)export class InfinityPaginationResponseDto { data: T[]; - hasNextPage: boolean; + hasNextPage?: boolean; } -
Then, we'll update our
QueryMovieDtoinsrc/movies/dto/query-movie.ts, which handles pagination options. We're going to add support for an offset-based pagination for Elasticsearch queries! Update yourQueryMovieDtodefinition to the below.// src/movies/dto/query-movie.ts -
To handle this sort of pagination, we're going to return a new type for requests that hit the search database - one that contains the data and a count of the items returned. Create a new file,
src/utils/dto/search-response.dto.tswith contents// src/utils/dto/search-response.dto.ts ; ; -
Finally, we're ready to update our controller's
findAllmethod, which is responsible for the index action, and now - search queries! Ensure your method looks like the below, including the annotations!
// src/movies/movies.controller.ts
async
@'search'
search: string,
@
query: QueryMovieDto,
:
Promise | SearchResponseDto >,
);
}
Now, blessedly, let's go ahead and run a query for that favorite movie of mine again, "The Third Element,"
Start our dev server
Query for our movie
Lo and behold, it's not, "The Third Element,", it's, "The Fifth Element!"
Next steps for your newly supercharged NestJS application
Now that you've added search to your NestJS Application, you're ready to deploy into production! Check out our post, "Heroku and Bonsai, a Winning Search Combination", for a detailed tutorial on how to launch this application onto Heroku, using the Bonsai Heroku Addon!
There are a number of day-1 and day-2 features that we'll want to add into our application to get the most out of the newly-added search capabilities that we'll cover in future posts, so stay tuned for part 2 of this series!
Ready to power your search with AI?
Launch a fully managed Elasticsearch or OpenSearch cluster, with built-in vector search and AI capabilities.
Learn how a managed service works and why it’s valuable
You won’t be pressured or used in any manipulative sales tactics
We’ll get a deep understanding of your current tech stack and needs
Get the information you need to decide whether to go with Bonsai
Or, schedule a consultation:
Form not loading? Contact our engineers directly.