skip to Main Content

Good afternoon everyone, I want to get all objects from Redis by mask or template. I know that I can use KEYS, but it is very slow, because it works for O(n), where n is the size of all keys in the database, and returns only keys without data. Can you offer me a good solution?

2

Answers


  1. You can use SCAN https://redis.io/commands/scan or HGETALL command and store your objects in a hash table for details, I advise you to look at the documentation https://redis.io/commands/hgetall.

    Login or Signup to reply.
  2. SCAN is the suitable option for replacement of KEYS * coz of time complexity. But you can’t get the value of the key using this option. As you can use hash structure for this coz by using HGETALLyou can retrieve all keys and values in a single call. These are the two options available for your case as @Qwe said. However I personally use bash script to get rid of these coz I don’t want to change my structure to hash. Like this.,

    #Default to '*' key pattern, meaning all redis keys in the namespace
    REDIS_KEY_PATTERN="${REDIS_KEY_PATTERN:-*}"
    for key in $(redis-cli --scan --pattern "$REDIS_KEY_PATTERN")
    
    do
    type=$(redis-cli type $key)
    if [ $type = "list" ]
    then
        printf "$key => n$(redis-cli lrange $key 0 -1 | sed 's/^/  /')n"
    elif [ $type = "hash" ]
    then
        printf "$key => n$(redis-cli hgetall $key | sed 's/^/  /')n"
    else
        printf "$key => $(redis-cli get $key)n"
    fi
    done
    

    I hope this will be heplfull.

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