Autocomplete API with Serverless Redis
This tutorial implements an autocomplete API powered by serverless Redis. See the demo and API endpoint and the source code.
We will keep country names in a Redis Sorted set. In Redis sorted set, elements with the same score are sorted lexicographically. So in our case, all country names will have the same score, 0. We keep all prefixes of country and use ZRANK to find the terms to suggest. See this blog post for the details of the algorithm.
Step 1: Project Setup
I will use Serverless framework for this tutorial. You can also use AWS SAM
If you do not have it already install serverless framework via:
npm install -g serverless
In any folder run serverless
as below:
Inside the project folder create a node project with the command:
Then install the redis client with:
Step 2: API Implementation
Edit handler.js file as below. See the blog post for the details of the algorithm.
Step 3: Create database on Upstash
If you do not have one, create a database following this
guide. Copy the Redis URL by clicking Redis Connect
button inside database page. Copy the URL for ioredis as we use ioredis in our
application. Create .env file and paste your Redis URL:
This example uses ioredis, you can copy the connection string from the Node tab in the console.
Step 4: Initialize Database
We will initialize the database with country names. Copy and run initdb.js script from here.
We simply put the country names and all their prefixes to the sorted set.
Step 5: Deploy Your Function
Edit serverless.yml
as below and replace your Redis URL:
In the project folder run:
Now you can run your function with:
It should give the following output:
You can also test your function using AWS console. In your AWS Lambda section,
click on your function. Scroll down to the code sections and click on the Test
button on the top right. Use { "queryStringParameters": {"term":"ar"}}
as your
event data.
Step 6: Run Your Function Locally
In your project folder run:
It should give the following output: