Getting a Redis Key by Value in Node.js (Detailed Guide w/ Code Examples)

Use Case(s)

A common use case for getting a Redis key by its value is when you don't remember the key, but know the value stored. However, Redis does not natively support this feature as it's a key-value store designed for high-speed lookups by key, and not by value. To get a key by a value, you'll need to manually iterate over all keys and their values, which can be performance costly.

Code Examples

Let's consider an example using node_redis, a popular Node.js client for Redis. In this example, we will search keys by value '1234'.

const redis = require('redis'); const client = redis.createClient(); client.on('connect', function() { console.log('connected'); }); client.keys('*', function (err, keys) { if (err) return console.log(err); for(var i = 0, len = keys.length; i < len; i++) { client.get(keys[i], function (err, value) { if(value === '1234') console.log(keys[i]); }); } });

In the above example, we first connect to Redis, then use the keys command with wildcard '*' to get all keys, and finally check each key's value. If the value matches '1234', we log that key.

Best Practices

  • Since Redis isn’t designed for searching by value, avoid this operation in a large production database as it can cause performance issues.
  • Try to design your data in a way that you can use the key to access values as it was intended.
  • For a more efficient lookup, consider using 'secondary indexing' by storing the value you want to search for as a key linked to the actual key.

Common Mistakes

  • Using this approach on large datasets or in performance-critical paths can lead to slow responses or even timeouts, as it requires scanning through all keys.


  • Can Redis natively support getting keys by their values? No, Redis is a key-value store designed for quick retrieval by keys. Searching by values requires scanning all keys and should be avoided if possible.

Was this content helpful?

Start building today

Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement.