Redis supports several different data types that allow you to store a variety of data structures. As of the latest Redis versions, the primary data types include:
-
Strings:
- The simplest type, storing text or binary data up to 512 MB in size.
- Examples:
"Hello, World!"
,"12345"
,"\x00\x01\x02"
-
Lists:
- Ordered collections of strings.
- Implemented as linked lists, allowing operations like
LPUSH
,RPUSH
,LPOP
,RPOP
, andLRANGE
. - Example:
["apple", "banana", "cherry"]
-
Sets:
- Unordered collections of unique strings.
- Support operations like
SADD
,SREM
,SPOP
,SMEMBERS
, and set operations likeSINTER
,SUNION
,SDIFF
. - Example:
{"apple", "banana", "cherry"}
-
Sorted Sets (ZSets):
- Similar to Sets but with an associated score for each member, allowing the members to be ordered.
- Support operations like
ZADD
,ZREM
,ZRANGE
,ZRANGEBYSCORE
,ZINCRBY
. - Example:
{("apple", 1), ("banana", 2), ("cherry", 3)}
-
Hashes:
- Maps of fields and values, similar to dictionaries or hash tables.
- Useful for storing objects.
- Support operations like
HSET
,HGET
,HMSET
,HGETALL
. - Example:
{"name": "Alice", "age": "30", "city": "Wonderland"}
-
Bitmaps:
- Strings that can be used as bit arrays.
- Allow bit-level operations.
- Support operations like
SETBIT
,GETBIT
,BITCOUNT
.
-
HyperLogLogs:
- Probabilistic data structure used for counting unique items with high efficiency.
- Support operations like
PFADD
,PFCOUNT
,PFMERGE
. - Useful for approximate distinct counting.
-
Geospatial Indexes:
- Specialized form of sorted sets for storing geospatial data.
- Support operations like
GEOADD
,GEORADIUS
,GEODIST
,GEOPOS
. - Example: Store locations with latitude and longitude.
-
Streams:
- Log-based data structure for storing an append-only series of messages.
- Support operations like
XADD
,XRANGE
,XREAD
,XGROUP
. - Useful for real-time data processing and message brokering.
Additional Features and Data Structures
-
Modules:
- Redis can be extended with custom modules that provide new data types and functionalities.
-
Keys and Keyspace Notifications:
- Although not a data type, Redis provides notifications for events related to keys.
Example Commands for Each Type
- String:
SET key "value"
,GET key
- List:
LPUSH mylist "world"
,RPUSH mylist "hello"
,LRANGE mylist 0 -1
- Set:
SADD myset "hello"
,SADD myset "world"
,SMEMBERS myset
- Sorted Set:
ZADD myzset 1 "one"
,ZADD myzset 2 "two"
,ZRANGE myzset 0 -1 WITHSCORES
- Hash:
HSET myhash field1 "foo"
,HSET myhash field2 "bar"
,HGETALL myhash
- Bitmap:
SETBIT mybitkey 7 1
,GETBIT mybitkey 7
,BITCOUNT mybitkey
- HyperLogLog:
PFADD myhll "foo" "bar" "baz"
,PFCOUNT myhll
- Geospatial:
GEOADD mygeo 13.361389 38.115556 "Palermo"
,GEORADIUS mygeo 15 37 200 km
- Stream:
XADD mystream * name Alice
,XRANGE mystream - +
Redis's diverse data types make it a versatile tool for various use cases, from simple caching to complex data structures and real-time data processing.