skip to Main Content

Currently I have created a NestJS application with a Redis Cache. I want to be able to get multiple keys from my Redis Cache by using a pattern where I can get all the keys that include some string.

Currently I am using cache-manager and cache-manager-redis-store as my client to be able to connect and access my Redis Cache. I have gone through the documentation to try and use the .mget() function but I am not able to figure out if I can somehow pass a string and get all the keys that include that string.

Im thinking I might have to go with a different Redis client but just wanted to see if anyone had any other ideas.

2

Answers


  1. There are two ways you can accomplish this

    1. keep a SET of keys that you want to retrieve and do SMEMBERS. However, you will have to manually maintain the SET and add and remove.

    2. Redisearch allows you to create secondary indices around data for full text search etc

    Login or Signup to reply.
  2. There is property named store in cache-manager from which you can get all keys by calling keys() method.

    This is example redisService

    import { Injectable, Inject, CACHE_MANAGER } from '@nestjs/common';
    import { Cache } from 'cache-manager';
    
    @Injectable()
    export class RedisCacheService {
        constructor(@Inject(CACHE_MANAGER) private readonly cache: Cache) {}
    
        async getKeys(key: string): Promise<any> {
            return await this.cache.store.keys(key);
        }
    
        async getValue(key: string): Promise<string> {
            return await this.cache.get(key);
        }
    
        async save(key: string, value: any, ttl: number): Promise<any> {
            return await this.cache.set(key, value, {
                ttl: ttl,
            });
        }
    
        async delete(key: string): Promise<void> {
            return await this.cache.del(key);
        }
    
        async getMultipleKeydata(key: string): Promise<any> {
            const redisKeys = await this.getKeys(key);
            const data: { [key: string]: any } = {};
            for (const key of redisKeys) {
                data[key] = await this.getValue(key);
            }
            return allData;
        }
    }
    

    Then you can use this service to get multiple keys or can get values of multiple keys

    await this.redisService.getKeys('*' + email + '*');

    Also you can get values of multiple keys

    await this.redisService.getMultipleKeydata('*' + email + '*');

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search