'What is optimal way to search Redis keys by prefix?

For example, I have stored a value under some keys in redis with prefix doc:

doc:office:room_1
doc:office:room_2
doc:reception

Let's say I want to find key prefix doc:office:

How can I fastly search keys by prefix beside KEYS, SCAN command?

I have checked Redis Search, but it works only on fields not on the keys itself. Can I add index keys somehow?



Solution 1:[1]

You could manage an index yourself. For example, you could have a Set called doc:office. Whenever you add or remove a key that starts with doc:office, you could add or remove that string from the Set. Then, if you need all the keys with that prefix, just get the members of the Set.

Like this:

> SET doc:office:room_1 data
> SADD doc:office doc:office:room_1

> SET doc:office:room_2 moardata
> SADD doc:office doc:office:room_2

> SMEMBERS doc:office
1) doc:office:room_1
2) doc:office:room_2

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Guy Royse