Databases 24 min read

Master Redis: Explore Its 8 Core Data Types and Powerful Commands

This guide reviews Redis's eight fundamental data types—String, List, Set, Hash, Sorted Set, Geospatial, HyperLogLog, and Bitmap—explaining their commands, usage scenarios, and practical examples to help developers and interviewees master this popular NoSQL database.

ITFLY8 Architecture Home
ITFLY8 Architecture Home
ITFLY8 Architecture Home
Master Redis: Explore Its 8 Core Data Types and Powerful Commands

Redis's Eight Data Types

Redis is a popular in‑memory NoSQL database; its data structures are frequently asked in interviews. This guide reviews all eight core types with commands, usage scenarios, and practical examples.

Redis-key

127.0.0.1:6379> keys *
(empty list or set)
127.0.0.1:6379> set name xxx
OK
127.0.0.1:6379> keys *
1) "name"
127.0.0.1:6379> set age 1
OK
127.0.0.1:6379> keys *
1) "age"
2) "name"
127.0.0.1:6379> exists name   # check if key exists (integer) 1
127.0.0.1:6379> exists name1  # (integer) 0
127.0.0.1:6379> move name 1
(integer) 1
127.0.0.1:6379> keys *
1) "age"
127.0.0.1:6379> set name yyy
OK
127.0.0.1:6379> expire name 10   # set key expiration in seconds (integer) 1
127.0.0.1:6379> ttl name   # remaining TTL (integer) 7
127.0.0.1:6379> ttl name
(integer) -2
127.0.0.1:6379> type age   # show key type (string)
127.0.0.1:6379>

Redis provides the following eight data types:

1. String

127.0.0.1:6379> set key1 v1   # set value
OK
127.0.0.1:6379> get key1
"v1"
127.0.0.1:6379> append key1 "hello"   # append, creates key if missing (integer) 7
127.0.0.1:6379> get key1
"v1hello"
127.0.0.1:6379> strlen key1   # length of string (integer) 7

Auto‑increment / decrement:

127.0.0.1:6379> set views 0
OK
127.0.0.1:6379> get views
"0"
127.0.0.1:6379> incr views   # increment by 1 (integer) 1
127.0.0.1:6379> get views
"1"
127.0.0.1:6379> decr views   # decrement by 1 (integer) 0
127.0.0.1:6379> get views
"-1"
127.0.0.1:6379> incrby views 10   # increment by step (integer) 9
127.0.0.1:6379> decrby views 5   # decrement by step (integer) 4

String range operations:

127.0.0.1:6379> set key1 "hello,world!"
OK
127.0.0.1:6379> getrange key1 0 3   # get substring [0,3] -> "hell"
127.0.0.1:6379> getrange key1 0 -1   # get whole string, same as GET

Replace part of a string:

127.0.0.1:6379> set key2 abcdefg
OK
127.0.0.1:6379> get key2
"abcdefg"
127.0.0.1:6379> setrange key2 1 xx   # replace from offset 1, result length 7
(integer) 7
127.0.0.1:6379> get key2
"axxdefg"

Special commands:

setex key3 30 "hello"   # set with expiration (seconds)
setnx mykey "redis"      # set if not exists, useful for distributed locks

Multiple set/get:

mset k1 v1 k2 v2 k3 v3   # atomic multiple set
mget k1 k2 k3            # get multiple values
msetnx k1 v1 k4 v4       # atomic set if none exist (fails if any key exists)

Object storage (JSON string):

set user:1 {name:zhangsan, age:3}
mset user:1:name zhangsan user:1:age 2
mget user:1:name user:1:age

getset – get old value then set new one:

getset db redis   # returns nil if key does not exist
set db mongodb    # returns previous value "redis"

Typical String use cases: counters, multi‑unit statistics, follower counts, object cache.

2. List

Lists are basic ordered collections that can act as stacks, queues, or blocking queues. Most list commands start with l.

lpush list one          # push to head
lpush list two
lpush list three
lrange list 0 -1        # view all elements -> "three","two","one"
rpush list right        # push to tail
lpop list               # pop from head
rpop list               # pop from tail
lindex list 1           # get element by index
llen list               # length of list
lrem list 1 world       # remove first occurrence of "world"
ltrim mylist 1 2        # keep only elements with indexes 1‑2
rpoplpush mylist myotherlist   # move last element to another list
lset list 0 item        # set element at index
linsert mylist before "hello2" hello   # insert before a value

Key points:

List is a linked list; insertions at both ends are O(1).

If the key does not exist, a new list is created.

An empty list is considered non‑existent.

Modifying at the ends is most efficient.

3. Set

Sets store unique, unordered elements.

sadd myset "hello"
sadd myset "world"
smembers myset          # list all members
sismember myset hello  # check membership (integer) 1
scard myset             # cardinality
srem myset hello        # remove element
srandmember myset       # random member
spop myset              # random removal
smove myset myset2 "kkk"   # move element to another set
sdiff key1 key2        # difference
sinter key1 key2       # intersection
sunion key1 key2        # union

4. Hash

Hashes are maps of field‑value pairs.

hset myhash field xxx
hget myhash field
hmset myhash field1 hello field2 world
hmget myhash field field1 field2
hgetall myhash
hdel myhash field1
hlen myhash               # number of fields
hexists myhash field1    # check field existence
hkeys myhash
hvals myhash
hincrby myhash field3 1   # increment numeric field
hsetnx myhash field4 hello   # set if field does not exist

Hashes are suitable for frequently changing objects; strings are better for plain text.

5. Sorted Set (zset)

Sorted sets associate a score with each member, enabling range queries by score.

zadd myset 1 one
zadd myset 2 two 3 three
zrange myset 0 -1       # get members in score order
zadd salary 2500 xiaohong
zadd salary 5000 xiaoming
zadd salary 500 xaiozhang
zrangebyscore salary -inf +inf
zrevrange salary 0 -1    # descending order
zrem salary xiaohong
zcard salary             # number of elements
zcount myset 1 3         # count members with scores between 1 and 3

6. Geospatial

Redis 3.2 introduced geo commands for storing longitude/latitude and calculating distances.

geoadd china:city 116.40 39.90 beijing
geoadd china:city 121.47 31.23 shanghai
geoadd china:city 106.50 29.53 chongqing 114.05 22.52 shenzhen
geopos china:city beijing
geodist china:city beijing shanghai km
georadius china:city 110 30 1000 km
georadiusbymember china:city shanghai 1000 km

Units: m, km, mi, ft. Default unit is meters.

7. HyperLogLog

HyperLogLog provides approximate cardinality counting with fixed 12 KB memory.

pfadd mykey a b c d e f g h i j
pfcount mykey          # approx. 10
pfadd mykey2 i j z x c v b n m
pfcount mykey2         # approx. 9
pfmerge mykey3 mykey mykey2
pfcount mykey3         # approx. 15

8. Bitmap

Bitmaps store bits (0/1) and are useful for flags such as daily check‑ins.

setbit sign 0 1   # Monday checked in
setbit sign 1 0   # Tuesday not checked
setbit sign 2 0   # Wednesday not checked
setbit sign 3 1   # Thursday checked
setbit sign 4 1   # Friday checked
setbit sign 5 1   # Saturday checked
setbit sign 6 0   # Sunday not checked
getbit sign 3    # returns 1
getbit sign 6    # returns 0
bitcount sign    # total checked days -> 4

These eight structures cover most use cases in NoSQL development and are essential knowledge for Redis interviews.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

redisData TypesNoSQL
ITFLY8 Architecture Home
Written by

ITFLY8 Architecture Home

ITFLY8 Architecture Home - focused on architecture knowledge sharing and exchange, covering project management and product design. Includes large-scale distributed website architecture (high performance, high availability, caching, message queues...), design patterns, architecture patterns, big data, project management (SCRUM, PMP, Prince2), product design, and more.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.