How to Implement Autocomplete Using Redis Efficiently
To implement autocomplete in
Redis, use ZADD to store searchable terms in a sorted set and ZRANGEBYLEX to fetch terms matching a prefix. This approach leverages Redis' fast lexicographical range queries for instant autocomplete suggestions.Syntax
Autocomplete in Redis typically uses sorted sets with lexicographical ordering. The main commands are:
ZADD key score member: Adds a member with a score to a sorted set.ZRANGEBYLEX key min max [LIMIT offset count]: Retrieves members in lexicographical order betweenminandmax.
Use ZADD to add terms, and ZRANGEBYLEX with prefix ranges to find matching autocomplete entries.
redis
ZADD autocomplete 0 "apple" ZRANGEBYLEX autocomplete [app [app\xff]
Example
This example shows how to add terms to a sorted set and query autocomplete suggestions for the prefix "app".
redis
127.0.0.1:6379> ZADD autocomplete 0 "apple" 0 "application" 0 "appetite" 0 "banana" 0 "apricot" (integer) 5 127.0.0.1:6379> ZRANGEBYLEX autocomplete [app [app\xff LIMIT 0 5 1) "appetite" 2) "apple" 3) "application"
Output
1) "appetite"
2) "apple"
3) "application"
Common Pitfalls
Common mistakes when implementing autocomplete with Redis include:
- Not using lexicographical range queries (
ZRANGEBYLEX) and trying to filter results client-side, which is inefficient. - Using scores incorrectly; for autocomplete, scores can be the same (e.g., 0) since sorting is lexicographical.
- Not appending
\xffto the prefix max range, which is needed to include all terms starting with the prefix.
Always use [prefix as min and [prefix\xff as max in ZRANGEBYLEX to get correct prefix matches.
redis
Wrong: ZRANGEBYSCORE autocomplete 0 1000 Right: ZRANGEBYLEX autocomplete [app [app\xff]
Quick Reference
| Command | Purpose | Example |
|---|---|---|
| ZADD | Add terms to sorted set | ZADD autocomplete 0 "apple" |
| ZRANGEBYLEX | Get terms by prefix range | ZRANGEBYLEX autocomplete [app [app\xff LIMIT 0 5 |
| LIMIT | Limit number of results | ZRANGEBYLEX autocomplete [app [app\xff LIMIT 0 5 |
Key Takeaways
Use Redis sorted sets with ZADD to store autocomplete terms.
Fetch autocomplete suggestions with ZRANGEBYLEX using prefix ranges.
Append \xff to the prefix max range to include all matching terms.
Scores can be the same since sorting is lexicographical for autocomplete.
Avoid filtering results client-side; leverage Redis commands for efficiency.