Bitfields let you set, increment, and get integer values of arbitrary bit length. For example, you can operate on anything from unsigned 1-bit integers to signed 63-bit integers.
These values are stored using binary-encoded Strings. Bitfields support atomic read, write and increment operations, making them a good choice for managing counters and similar numerical values.
BITFIELD
atomically sets, increments and reads one or
more values.BITFIELD_RO
is a read-only variant of
BITFIELD
.Suppose you want to maintain two metrics for various bicycles: the current price and the number of owners over time. You can represent these counters with a 32-bit wide bitfield per for each bike.
127.0.0.1:6379> BITFIELD bike:1:stats SET u32 #0 1000
1) (integer) 0
127.0.0.1:6379> BITFIELD bike:1:stats INCRBY u32 #0 -50 INCRBY u32 #1 1
1) (integer) 950
2) (integer) 1
127.0.0.1:6379> BITFIELD bike:1:stats INCRBY u32 #0 500 INCRBY u32 #1 1
1) (integer) 1450
2) (integer) 2
127.0.0.1:6379> BITFIELD bike:1:stats GET u32 #0 GET u32 #1
1) (integer) 1450
2) (integer) 2
BITFIELD
is O(n), where n is the number of
counters accessed.