Getting type of field inside Redis hash

1.9k Views Asked by At

I was exploring Redis, I have created a key server and I can get type of the value stored here as follows:

> set server terver
OK
> get server
"terver"

> type server
"string"

But when I created hash myhash,

> hset myhash field1 lalalal
(integer) 1
> hset myhash field2 hahaha
(integer) 1
> type myhash
"hash"

I am unable to get the type of field inside hash

> type myhash field1
(error) wrong number of arguments (given 2, expected 1)
> type myhash.field1
"none"

Here if I query

>hincrby myhash field1 2
(error) ERR hash value is not an integer

This suggest that type exists for hash and matters for operation. type myhash.field1 showing "none" could not be the type because it is string.

So how can I get type of fields inside myhash ?

1

There are 1 best solutions below

2
On
  1. It is not possible to get types of fields inside hash, TYPE only works on parent keys.

  2. You can use Lua scripting to do what you want to do, but be very aware of how redis treats different datatypes and internal conversions, and based on that write logic in your Lua script.

    127.0.0.1:6379> set server terver
    OK
    127.0.0.1:6379> get server
    "terver"
    127.0.0.1:6379> type server
    string
    127.0.0.1:6379> hset myhash field1 lalala
    (integer) 1
    127.0.0.1:6379> hset myhash field2 hahaha
    (integer) 1
    127.0.0.1:6379> type myhash
    hash
    127.0.0.1:6379> type myhash.field1
    none
    127.0.0.1:6379> type NotExistingKey
    none
    127.0.0.1:6379>  eval "return redis.call('hget','myhash','field1')"  0 
    "lalala"
    127.0.0.1:6379>  eval "return type(redis.call('hget','myhash','field1'))"  0 
    "string"
    
    127.0.0.1:6379> hset myhash field3 42
    (integer) 1
    127.0.0.1:6379>  eval "return redis.call('hget','myhash','field3')"  0 
    "42"
    127.0.0.1:6379>  eval "return type(redis.call('hget','myhash','field3'))"  0 
    "string"
    127.0.0.1:6379> hget myhash field3
    "42"
    

So in your Lua script you will have to check for string patterns to be a number before classifying its type as Number.