Redis data structure and operation


Two kinds of objects

When creating a new key-value pair in redis, two new objects are created, one is a key object and the other is a value object.

Key object

Common key objects are string objects

Value object

Value objects are divided into

  • String objects (int, embstr, raw encoding),

  • List objects (ziplist, linkedlist encoding),

  • Zset object (ziplist, skiplist code)

  • Hash objects (ziplist, ht code),

  • Set object (intset, ht encoding)

RedisObject is a larger object. The assembly refers to the above data object, and also adds information such as type and encoding

Object encoding

Each type of object uses at least two different codes instead of a fixed one, thus greatly improving the flexibility and efficiency of redis.
For example, the list object, when it contains fewer elements, the redis bottom layer uses ziplist coding to implement:
1)ziplist saves more memory than linkedlist, and when there are fewer elements, it is saved in memory as continuous blocks, which can be loaded into memory more easily.
2) With more and more list elements, the advantages of using ziplist gradually disappear, and the bottom layer of the object will realize the conversion from ziplist to linkedlist.

View Value Object Types

With the type variable name, you can view the type of the value object
With the object encoding variable name, you can view the data structure code of the data actually stored in the value object.

Such as int(long integer),
Embstr (simple dynamic string encoded embstr(embstr),
Raw (Simple Dynamic String),
Ht (dictionary),
Ziplist (compressed list),
Intset (set of integers),


set/get var
incr/decr var


insert:lpush list a b c d,linsert list after d e
delete:rpop list,lrem list 1 a
update:lset list 1 g
search:lrange list 0 -1,lindex list 1,llen list

Main operations:


insert:sadd users linda persia jack
delete:srem users linda
search:smembers users,scard users,spop,sismember users casesar

sdiff sa sb
sinter sa sb
sunion sa sb

Main operations


insert:zadd scores 70 linda 100 persia 90 jack
update:zadd scores 88 linda,zincrby scores -3 persia
delete:zrem scores linda,zremrangebyscore scores (60 80,zremrangebyrank scores 0 1

   zrange scores 0 -1 withscores
   zrevrange scores 0 -1 withscores
   zrangebyscore scores (10 +inf

   zcount scores (90 100
   zcard scores
   zscore scores persia
   zrank scores persia
   zrevrank scores persia


insert:hset kv t1 linda,hsetnx kv t4 houhou,hmset kv t2 hah t3 xixi
update:hset kv t1 linda1,hincrby kv t5 1
delete:hdel kv t1
search:hget kv t1

   hmget kv t2 t3
   hkeys kv
   hvals kv
   hlen kv 
   hexists kv t6  

Operations on keys:

del key1
expire key2 900
rename key3 key33
type key4
object encoding key5