RediSearch: My autocomplete hero
For a long time, I've been looking for a system that is easy to integrate and allows for straightforward data updates. Although there are alternatives like Kbar and Algolia, I wanted to create something that I could customize myself. Of course, for this, I needed a fast indexing infrastructure.
ElasticSearch was naturally a perfect fit for this, but I was looking for something faster. While exploring full-text search architectures with Redis, I soon came across RediSearch. RediSearch, an official module of Redis, is something I'll try to set up an example of using Docker.
I will explain this without installing other modules like RedisGraph.
First, we pull the docker image.
docker run -p 6379:6379 redislabs/redisearch:latest
If you are doing this on Docker Desktop, don't forget to set the port.
Creating an INDEX
Creating a RediSearch index doesn't actually mean creating a new key or schema. We make an existing key prefix searchable. You can create a search index for the data you have previously added.
For example, let's create a search index for our keys with the prefix products:
FT.CREATE products ON HASH PREFIX 1 product: SCHEMA name TEXT SORTABLE quantity NUMERIC SORTABLE description TEXT
Creating New Documents
HMSET product:1 name "Orange" quantity 12 description "Orange juice"
HMSET product:2 name "Lime and Mint" quantity 4 description "Lime with mint juice"
HMSET product:3 name "Juice Book" quantity 1 description "Thro's drinks"
HMSET is a standard command in Redis's core module. It's not actually related to RediSearch.
FT.SEARCH products ora* // Returns product with the name Orange Juice
FT.SEARCH products lim* // Returns product with the name Lime and Mint
FT.SEARCH products @name=jui* // You can also search by specifying a specific field name
LIMIT and SORTING
FT.SEARCH products {term}* LIMIT #{OFFSET} #{LIMIT} SORTBY #{sort_field} #{sort_direction}
FT.SEARCH products jui* LIMIT 0 10 SORTBY quantity desc
CONCLUSION
By investing some effort into RediSearch, you can effectively handle even complex queries. While it may not yet be on par with architectures like ElasticSearch, its rapid integration and fast indexing capabilities make it exceptionally adept at meeting needs such as autocomplete, offering significant advantages in specific use cases.