bitop.3valkey - Man Page

Performs bitwise operations on multiple strings, and stores the result.

Synopsis

BITOP <AND | OR | XOR | NOT> destkey key [key...]

Description

Perform a bitwise operation between multiple keys (containing string values) and store the result in the destination key.

The BITOP command supports four bitwise operations: AND, OR, XOR and NOT, thus the valid forms to call the command are:

As you can see NOT is special as it only takes an input key, because it performs inversion of bits so it only makes sense as a unary operator.

The result of the operation is always stored at destkey.

Handling of strings with different lengths

When an operation is performed between strings having different lengths, all the strings shorter than the longest string in the set are treated as if they were zero-padded up to the length of the longest string.

The same holds true for non-existent keys, that are considered as a stream of zero bytes up to the length of the longest string.

Reply

valkey-protocol(7) Integer reply: the size of the string stored in the destination key is equal to the size of the longest input string.

Complexity

O(N)

Acl Categories

@bitmap @slow @write

History

Examples

127.0.0.1:6379> SET key1 "foobar"
OK
127.0.0.1:6379> SET key2 "abcdef"
OK
127.0.0.1:6379> BITOP AND dest key1 key2
(integer) 6
127.0.0.1:6379> GET dest
"`bc`ab"

Pattern: real time metrics using bitmaps

BITOP is a good complement to the pattern documented in the BITCOUNT command documentation. Different bitmaps can be combined in order to obtain a target bitmap where the population counting operation is performed.

See the article called “http://blog.getspool.com/2011/11/29/fast-easy-realtime-metrics-using-redis-bitmaps Fast easy realtime metrics using Valkey bitmaps\c ” for an interesting use cases.

Performance considerations

BITOP is a potentially slow command as it runs in O(N) time. Care should be taken when running it against long input strings.

For real-time metrics and statistics involving large inputs a good approach is to use a replica (with replica-read-only option enabled) where the bit-wise operations are performed to avoid blocking the master instance.

See Also

bitcount(3valkey), bitfield(3valkey), bitfield_ro(3valkey), bitpos(3valkey), getbit(3valkey), setbit(3valkey)

Info

2024-09-23 8.0.0 Valkey Command Manual