3

How do we find memory occupied by individual key in Redis using Jedis?jedis.info("memory") provides only the total memory used by the redis server.

3 Answers3

2

After installing the redis-rdb-tools as described here, we can use it to find out the memory used by a key.

finding out memory for a key from running redis.

redis-3.2.4 $ redis-memory-for-key -s localhost -p 6379 mystringkey
Key    "mystringkey"
Bytes    88
Type    string
redis-3.2.4 $ redis-memory-for-key -s localhost -p 6379 myhashkey
Key    "myhashkey"
Bytes    115
Type    hash
Encoding   ziplist
Number of Elements  2
Length of Largest Element 6

finding out memory for a key from a rdb file.

redis-3.2.4 $ rdb -c memory dump.rdb -k mystringkey
database,type,key,size_in_bytes,encoding,num_elements,len_largest_element

0,string,"mystringkey",88,string,13,13

finding out memory for all keys for a pattern.

redis-3.2.4 $ rdb -c memory dump.rdb -k my.*
database,type,key,size_in_bytes,encoding,num_elements,len_largest_element
0,list,"mylistkey",219,quicklist,7,6
0,sortedset,"mysortedsetkey",143,ziplist,6,5
0,hash,"myhashkey",115,ziplist,2,6
0,string,"mystringkey",88,string,13,13
0,string,"myhllkey",168,string,90,90

0,set,"mysetkey",452,hashtable,4,6

finding out memory for all keys for a pattern and exporting to a csv file.

redis-3.2.4 $ rdb -c memory dump.rdb -k my.* -f memory.csv
redis-3.2.4 $ head memory.csv 
database,type,key,size_in_bytes,encoding,num_elements,len_largest_element
0,list,"mylistkey",219,quicklist,7,6
0,sortedset,"mysortedsetkey",143,ziplist,6,5
0,hash,"myhashkey",115,ziplist,2,6
0,string,"mystringkey",88,string,13,13
0,string,"myhllkey",168,string,90,90
0,set,"mysetkey",452,hashtable,4,6
Abhishek
  • 688
  • 6
  • 21
1

As of Redis v4, you can call the MEMORY USAGE to obtain an accurate measurement of a specific key-value.

Looking at the Jedis javadocs (http://xetorthio.github.io/jedis/), I can't find a suitable wrapper method to invoke this but you should be able to use the sendCommand() method of the Connection class to work around that.

Itamar Haber
  • 47,336
  • 7
  • 91
  • 117
-1

From my answer here: Is there a way to pass redis commands in jedis, without using the functions?

import redis.clients.jedis.util.SafeEncoder;
// ... Jedis setup code ...
byteSize = (Long) jedis.sendCommand(new ProtocolCommand() {
                                        @Override
                                        public byte[] getRaw() {
                                          return SafeEncoder.encode("memory");
                                        }}, 
                                    SafeEncoder.encode("usage"), 
                                    SafeEncoder.encode(key));

... please click on my original answer link above for more information about this as I'm not sure if SO would flag me if I just pasted it here completely.

Antony Nguyen
  • 179
  • 1
  • 5