How to get Redis Hash Length?

For the length as disk space you can use DEBUG OBJECT as it returns several information items for each key.

redis 127.0.0.1:50001> hset myhash field1 'hello'
(integer) 1
redis 127.0.0.1:50001> hset myhash field2 'world'
(integer) 1
redis 127.0.0.1:50001> DEBUG OBJECT myhash
Value at:0x7fb8de4ad590 refcount:1 encoding:zipmap serializedlength:31 lru:696871 lru_seconds_idle:0

Hope it helps


Depends on what you want to do with the length of the hash.

If you want the length to do some diagnostics or monitoring, like finding the memory consumed, then I'd suggest you do it offline using a tool like redis-rdb-tools (disclaimer: I am the author of this tool). The csv dump file will get you statistics about each key - including total size, total memory consumed and so on.

But if you want the size to implement some application feature, then there isn't a readymade solution. HGETALL plus client size calculation of the length is the way to go. You can perhaps optimize by writing a lua script so that the length calculation happens on the redis server itself.


Just use HLEN.

redis> HSET myhash field1 "Hello"
(integer) 1
redis> HSET myhash field2 "World"
(integer) 1
redis> HLEN myhash
(integer) 2

EDIT: The question was clarified to be that the OP wants the size on disk of a hash for active monitoring. In that case, I'd definitely go with a Lua script that calculates the size of a hash on your server and returns the value back to you. Do not use HGETALL if you're expecting big hashes, because you'll need to transfer that entire hash from your server to your client computer, and that's going to become your bottleneck really quickly. Just doing this calculation on the Redis server with Lua means you get to just transfer an int of the number of bytes of your network instead of possibly mb of data for your entire hash.

Tags:

Redis