Building a voice-activated movie search app powered by Amazon Lex, Lambda, and MongoDB Atlas - Part 3
Tags: aws, node, nosql, serverless
Published: 2018-02-27 21:06:58

---
title: "Building a voice-activated movie search app powered by Amazon Lex, Lambda, and MongoDB Atlas - Part  3"
published: true
tags: #aws #node #nosql #serverless
canonical_url: https://www.mongodb.com//blog/post/aws-lex-lambda-mongodb-atlas-movie-search-app-part-3
---

### Introduction

This is Part 3 of our Amazon Lex blog post series. This tutorial is divided into 3 parts:

- 

[Part 1: Lex overview, demo scenario and data layer setup](https://www.mongodb.com/blog/post/aws-lex-lambda-mongodb-atlas-movie-search-app-part-1?utm_medium=dev-synd&utm_source=dev&utm_content=lex3&jmp=dev-ref)

- 

[Part 2: Set up and test an Amazon Lex bot](https://www.mongodb.com/blog/post/aws-lex-lambda-mongodb-atlas-movie-search-app-part-2?utm_medium=dev-synd&utm_source=dev&utm_content=lex3&jmp=dev-ref)

- 

Part 3: Deploy a Lambda function as our Lex bot fulfillment (this blog post)

In this last blog post, we will deploy our Lambda function using the AWS Command Line Interface and verify that the bot fully works as expected. We’ll then review the code that makes up our Lambda function and explain how it works.

### Let’s deploy our AWS Lambda function

Please follow the deployment steps available in [this GitHub repository](https://github.com/rlondner/mongodb-awslex-searchmovies#aws-lambda-function). I have chosen to use Amazon’s [SAM Local](https://github.com/awslabs/aws-sam-local) tool to showcase how you can test your Lambda function locally using [Docker](https://www.docker.com/), as well as package it and deploy it to an AWS account in just a few commands. However, if you’d like to deploy it manually to the AWS Console, you can always use [this zip script](https://github.com/rlondner/mongodb-awslex-searchmovies/blob/master/code/zip.sh) to deploy it in pretty much the same way I did in this [MongoDB Atlas with Lambda tutorial](https://www.mongodb.com/blog/post/serverless-development-with-nodejs-aws-lambda-mongodb-atlas?utm_medium=dev-synd&utm_source=dev&utm_content=lex3&jmp=dev-ref).

### Let’s test our Lex bot (end-to-end)

Now that our Lambda fulfillment function has been deployed, let’s test our bot again in the Amazon Lex console and verify that we get the expected response. For instance, we might want to search for all the romance movies Jennifer Aniston starred in, a scenario we can test with the following bot conversation:

![Amazon Lex Test Bot UI](https://webassets.mongodb.com/_com_assets/cms/Amazon_Lex_Bot_Prompt1-s3mh080kx8.png)

![Amazon Lex Test Bot UI](https://webassets.mongodb.com/_com_assets/cms/Amazon_Lex_Bot_Prompt2-dwb1k7ezzg.png)

![Amazon Lex Test Bot UI](https://webassets.mongodb.com/_com_assets/cms/Amazon_Lex_Bot_Prompt3-wf8n3qlx9x.png)

As the screenshot above testifies, the Lex bot replies with the full list of Jennifer Aniston’s romance movies retrieved from our movies MongoDB database through our Lambda function. But how does our Lambda function process that request? We’ll dig deeper into our [Lambda function code](https://github.com/rlondner/mongodb-awslex-searchmovies/blob/master/code/lambda.js) in the next section.

### Let's dive into the Lambda function code

Our Lambda function always receives a JSON payload with a structure compliant with Amazon Lex’ [input event format](http://docs.aws.amazon.com/lex/latest/dg/lambda-input-response-format.html#using-lambda-input-event-format) (as this [event.json](https://github.com/rlondner/mongodb-awslex-searchmovies/blob/master/code/event.json) file is):

```
{
  "messageVersion": "1.0",
  "invocationSource": "FulfillmentCodeHook",
  "userId": "user-1",
  "sessionAttributes": {},
  "bot": {
    "name": "SearchMoviesBot",
    "alias": "$LATEST",
    "version": "$LATEST"
  },
  "outputDialogMode": "Text",
  "currentIntent": {
    "name": "SearchMovies",
    "slots": {
      "castMember": "jennifer aniston",
      "year": "0",
      "genre": "Romance"
    }
  }
}
```

Note that the request contains the bot’s name (_SearchMoviesBot_) and the slot values representing the answers to the bot’s questions provided by the user.

The Lambda function starts with the [exports.handler method](https://github.com/rlondner/mongodb-awslex-searchmovies/blob/master/code/lambda.js#L13) which validates the bot’s name and performs some additional processing if the payload is received through Amazon API Gateway (this is only necessary if you want to test your Lambda function through Amazon API Gateway but is not relevant in an Amazon Lex context). It then calls the [dispatch()](https://github.com/rlondner/mongodb-awslex-searchmovies/blob/master/code/lambda.js#L33) method, which takes care of connecting to our MongoDB Atlas database and passing on the bot’s intent to the [query()](https://github.com/rlondner/mongodb-awslex-searchmovies/blob/master/code/lambda.js#L67) method, which we’ll explore in a second. Note that the dispatch() method uses the performance optimization technique I highlighted in [Optimizing AWS Lambda performance with MongoDB Atlas and Node.js](https://www.mongodb.com/blog/post/optimizing-aws-lambda-performance-with-mongodb-atlas-and-nodejs?utm_medium=dev-synd&utm_source=dev&utm_content=lex3&jmp=dev-ref), namely not closing the database connection and using the _callbackWaitsForEmptyEventLoop_ Lambda context property. This allows our bot to be more responsive after the first query fulfilled by the Lambda function.

Let’s now take a closer look at the query() method, which is the soul and heart of our Lambda function. First, that method retrieves the cast member, movie genre, and movie release year. Because these values all come as strings and the movie release year is stored as an integer in MongoDB, the function must [convert that value to an integer](https://github.com/rlondner/mongodb-awslex-searchmovies/blob/master/code/lambda.js#L71).

We then build the query we will run against MongoDB:

```
var castArray = [castMember];

var matchQuery = {
    Cast: { $in: castArray },
    Genres: { $not: { $in: ["Documentary", "News", ""] } },
    Type: "movie"
  };

  if (genre != undefined && genre != allGenres) {
    matchQuery.Genres = { $in: [genre] };
    msgGenre = genre.toLowerCase();
  }

  if ((year != undefined && isNaN(year)) || year > 1895) {
    matchQuery.Year = year;
    msgYear = year;
  }
```

We first restrict the query to items that are indeed movies (since the database also stores TV series) and we exclude some irrelevant movie genres such as the documentary and news genres. We also make sure we only query movies in which the cast member starred. Note that the **_[$in](https://docs.mongodb.com/manual/reference/operator/query/in?jmo=adref)_** operator expects an array, which is why we have to wrap our unique cast member into the **_castArray_** array. Since the cast member is the only mandatory query parameter, we add it first and then optionally add the `Genres` and `Year` parameters if the code determines that they were provided by the user (i.e. the user did not use the `All` and/or `0` escape values).

The query() method then goes on to define the default response message based on the user-provided parameters. This default response message is used if the query doesn’t return any matching element:

```
var resMessage = undefined;
  if (msgGenre == undefined && msgYear == undefined) {
    resMessage = `Sorry, I couldn't find any movie for ${castMember}.`;
  }
  if (msgGenre != undefined && msgYear == undefined) {
    resMessage = `Sorry, I couldn't find any ${msgGenre} movie for ${castMember}.`;
  }
  if (msgGenre == undefined && msgYear != undefined) {
    resMessage = `Sorry, I couldn't find any movie for ${castMember} in ${msgYear}.`;
  }
  if (msgGenre != undefined && msgYear != undefined) {
    resMessage = `Sorry, ${castMember} starred in no ${msgGenre} movie in ${msgYear}.`;
  }
```

The meat of the query() method happens next as the code performs the database query using 2 different methods: the classic [db.collection.find()](https://docs.mongodb.com/manual/reference/method/db.collection.find/) method and the [db.collection.aggregate()](https://docs.mongodb.com/manual/reference/method/db.collection.aggregate?jmp=adref) method. The default method used in this Lambda function is the aggregate one, but you can easily test the find() method by setting the _[aggregationFramewor_k]([https://github.com/rlondner/mongodb-awslex-searchmovies/blob/master/code/lambda.js#L112](https://github.com/rlondner/mongodb-awslex-searchmovies/blob/master/code/lambda.js#L112)) variable to _false_.

In our specific use case scenario (querying for one single cast member and returning a small amount of documents), there likely won’t be any noticeable performance or programming logic impact. However, if we were to query for all the movies multiple cast members each starred in (i.e. the union of these movies, not the intersection), the aggregation framework query is a clear winner. Indeed, let’s take a closer look at the find() query the code runs:

```
cursor = db.collection(moviesCollection)
      .find(matchQuery, { _id: 0, Title: 1, Year: 1 })
      .collation(collation)
      .sort({ Year: 1 });
```

It’s a fairly simple query that retrieves the movie’s title and year, sorted by year. Note that we also use the same { locale: "en", strength: 1 } collation we used to create the case-insensitive index on the Cast property in [Part 2 of this blog post series](https://www.mongodb.com/blog/post/aws-lex-lambda-mongodb-atlas-movie-search-app-part-2?utm_medium=dev-synd&utm_source=dev&utm_content=lex3&jmp=dev-ref). This is critical since the end user might not [title case](https://en.wikipedia.org/wiki/Capitalization#Title_case) the cast member’s name (and Lex won’t do it for us either).

The simplicity of the query is in contrast to the relative complexity of the app logic we have to write to process the result set we get with the find() method:

```
var maxYear, minYear;
for (var i = 0, len = results.length; i < len; i++) { 
    castMemberMovies += `${results[i].Title} (${results[i].Year}), `;
}

 //removing the last comma and space
castMemberMovies = castMemberMovies.substring(0, castMemberMovies.length - 2);

moviesCount = results.length;
var minYear, maxYear;
minYear = results[0].Year;
maxYear = results[results.length-1].Year;
yearSpan = maxYear - minYear;
```

First, we have to iterate over all the results to concatenate its `Title` and `Year` properties into a legible string. This might be fine for 20 items, but if we had to process hundreds of thousands or millions of records, the performance impact would be very noticeable. We further have to remove the last period and white space characters of the concatenated string since they’re in excess. We also have to manually retrieve the number of movies, as well as the low and high ends of the movie release years in order to compute the time span it took the cast member to shoot all these movies. This might not be particularly difficult code to write, but it’s clutter code that affects app clarity. And, as I wrote above, it definitely doesn’t scale when processing millions of items.

Contrast this app logic with the succinct code we have to write when using the aggregation framework method:

```
for (var i = 0, len = results.length; i < len; i++) { 
    castMemberMovies = results[i].allMovies;
    moviesCount = results[i].moviesCount;
    yearSpan = results[i].timeSpan;
}
```

The code is not only much cleaner and concise now, it’s also more generic, as it can handle the situation where we want to process movies for each of multiple cast members. You can actually test this use case by uncommenting the following line earlier in [the source code](https://github.com/rlondner/mongodb-awslex-searchmovies/blob/master/code/lambda.js#L78):

`castArray = [castMember, "Angelina Jolie"]`

and by testing it using this [SAM script](https://github.com/rlondner/mongodb-awslex-searchmovies/blob/master/code/sam-invoke.sh).

With the aggregation framework, we get the correct raw and final results without changing a single line of code:

![MongoDB Aggregation Framework Query Response](https://webassets.mongodb.com/_com_assets/cms/MongoDB_AggregateResponse-x4u6m0bxt6.png)

However, the find() method’s post-processing requires some significant effort to fix this incorrect output (the union of comedy movies in which Angelina Jolie or Brad Pitt starred in, all incorrectly attributed to Brad Pitt):

![MongoDB Find Query Response](https://webassets.mongodb.com/_com_assets/cms/MongoDB_FindResponse-y8s3psxbpa.png)

We were able to achieve this code conciseness and correctness by moving most of the post-processing logic to the database layer using a MongoDB [aggregation pipeline](https://docs.mongodb.com/manual/core/aggregation-pipeline?jmp=adref):

```
cursor = db.collection(moviesCollection).aggregate(
      [
        { $match: matchQuery },
        { $sort: { Year: 1 } },
        unwindStage,
        castFilterStage,
        { $group: {
            _id: "$Cast",
            allMoviesArray: {$push: {$concat: ["$Title", " (", { $substr: ["$Year", 0, 4] }, ")"] } },
            moviesCount: { $sum: 1 },
            maxYear: { $last: "$Year" },
            minYear: { $first: "$Year" }
          }
        },
        {
          $project: {
            moviesCount: 1,
            timeSpan: { $subtract: ["$maxYear", "$minYear"] },
            allMovies: {
              $reduce: {
                input: "$allMoviesArray",
                initialValue: "",
                in: {
                  $concat: [
                    "$$value",
                    {
                      $cond: {
                        if: { $eq: ["$$value", ""] },
                        then: "",
                        else: ", "
                      }
                    },
                    "$$this"
                  ]
                }
              }
            }
          }
        }
      ],
      {collation: collation}

);
```

This aggregation pipeline is arguably more complex than the find() method discussed above, so let’s try to explain it one stage at a time (since an aggregation pipeline consists of stages that transform the documents as they pass through the pipeline):

1. [$match stage](https://github.com/rlondner/mongodb-awslex-searchmovies/blob/master/code/lambda.js#L125): performs a filter query to only return the documents we’re interested in (similarly to the find() query above).
2. [$sort stage](https://github.com/rlondner/mongodb-awslex-searchmovies/blob/master/code/lambda.js#L126): sorts the results by year ascending.
3. [$unwind stage](https://github.com/rlondner/mongodb-awslex-searchmovies/blob/master/code/lambda.js#L113): splits each movie document into multiple documents, one for each cast member in the original document. For each original document, this stage unwinds the Cast array of cast members and creates separate, unique documents with the same values as the original document, except for the Cast property which is now a string value (equal to each cast member) in each unwinded document. This stage is necessary to be able to group by only the cast members we’re interested in (especially if there are more than one). The output of this stage may contain documents with other cast members irrelevant to our query, so we must filter them out in the next stage.
4. [$match stage](https://github.com/rlondner/mongodb-awslex-searchmovies/blob/master/code/lambda.js#L114): filters the deconstructed documents from the $unwind stage by only the cast members we’re interested in. This stage essentially removes all the documents tagged with cast members irrelevant to our query.
5. [$group stage](https://github.com/rlondner/mongodb-awslex-searchmovies/blob/master/code/lambda.js#L129): groups movies by cast member (for instance, all movies with Brad Pitt and all movies with Angelina Jolie, separately). This stage also concatenates each movie title and release year into the _Title (Year)_ format and adds it to an array called _allMoviesArray_ (one such array for each cast member). This stage also computes a count of all movies for each cast member, as well as the earliest and latest year the cast member starred in a movie (of the requested movie genre, if any). This stage essentially performs most of the post-processing we previously had to do in our app code when using the find() method. Because that post-processing now runs at the database layer, it can take advantage of the database server’s computing power along with the distributed system nature of MongoDB (in case the collection is partitioned across multiple shards, each shard performs this stage independently of the other shards).
6. [$project stage](https://github.com/rlondner/mongodb-awslex-searchmovies/blob/master/code/lambda.js#L138): last but not least, this stage performs a [$reduce operation](https://docs.mongodb.com/manual/reference/operator/aggregation/reduce?jmp=adref) (new in MongoDB 3.4) to concatenate our array of ‘_Title (Year)_’ strings into one single string we can use as is in the response message sent back to the bot.

Once the matching movies have been retrieved from our MongoDB Atlas database, the code generates the proper response message and sends it back to the bot according to the expected [Amazon Lex response format](http://docs.aws.amazon.com/lex/latest/dg/lambda-input-response-format.html#using-lambda-response-format):

```
if (msgGenre != allGenres) {
                resMessage = `${toTitleCase(castMember)} starred in 
                the following ${moviesCount>1?moviesCount+" ":""}
                ${msgGenre.toLowerCase()} movie(s)${yearSpan>0?" over " 
                + yearSpan +" years":""}: ${castMemberMovies}`;
} else {
    resMessage = `${toTitleCase(castMember)} starred in the following 
    ${moviesCount>1?moviesCount+" ":""}movie(s)${yearSpan>0?" over " 
    + yearSpan +" years":""}: ${castMemberMovies}`;
}
if (msgYear != undefined) {
    resMessage = `In ${msgYear}, ` + resMessage;

callback(
    close(sessionAttributes, "Fulfilled", {
        contentType: "PlainText",
        content: resMessage
    })
);
```

Our Jennifer Aniston fan can now be wowed by the completeness of our bot's response!

![Amazon Lex MongoDB response](https://webassets.mongodb.com/_com_assets/cms/Amazon_Lex_Bot_Response-1x76of69xk.png)

### Wrap-up and next steps

This completes our Lex blog post series and I hope you enjoyed reading it as much as I did writing it.

In this final blog post, we tested and deployed a Lambda function to AWS using the [SAM Local tool](https://github.com/awslabs/aws-sam-local).

We also learned:

- 

How a Lambda function processes a Lex request and responds to it using [Amazon Lex’ input and out event format](http://docs.aws.amazon.com/lex/latest/dg/lambda-input-response-format.html).

- 

How to use a case-insensitive index in a find() or aggregate() query

- 

How to make the most of MongoDB’s aggregation framework to move complexity from the app layer to the database layer

As next steps, I suggest you now take a look at the AWS documentation to learn how to [deploy your bot to Facebook Messenger](http://docs.aws.amazon.com/lex/latest/dg/fb-bot-association.html) , [Slack](http://docs.aws.amazon.com/lex/latest/dg/slack-bot-association.html) or [to your own web site](https://aws.amazon.com/blogs/ai/greetings-visitor-engage-your-web-users-with-amazon-lex/).

Happy Lex-ing!

_About the Author - **Raphael Londner** _

Raphael Londner is a Principal Developer Advocate at MongoDB, focused on cloud technologies such as Amazon Web Services, Microsoft Azure and Google Cloud Engine. Previously he was a developer advocate at Okta as well as a startup entrepreneur in the identity management space. You can follow him on Twitter at _**[@rlondner](https://www.twitter.com/rlondner)**_