The XADD
command in Redis is used with streams, a type of data structure that was introduced in Redis 5.0. Streams are designed to hold a list of messages, where each message is a dictionary-like collection of fields and values. The common use case for the XADD
command is to push data to a Redis stream.
Example 1: Adding a single item to a stream.
import redis r = redis.Redis() stream_name = 'mystream' message = {'field1': 'value1', 'field2': 'value2'} # Add the message to the stream response = r.xadd(stream_name, message) print(f'Added message with ID: {response}')
In this example, we're creating a connection to a local Redis server using the redis.Redis()
function. Then, we define a stream name and a dictionary message. The xadd
method adds the message to the stream and returns the ID of the added message.
Example 2: Adding an item to a stream with a maximum length.
import redis r = redis.Redis() stream_name = 'mystream' message = {'field1': 'value1', 'field2': 'value2'} max_length = 1000 # Add the message to the stream response = r.xadd(stream_name, message, maxlen=max_length, approximate=False) print(f'Added message with ID: {response}')
In this second example, we're adding an optional maxlen
parameter which sets a limit to the number of items in the stream. If the limit is reached, older items will be removed.
XADD
with maxlen
, take into account that removing old items can be resource-intensive if a large number of deletions is needed. Consider setting approximate=True
to speed up this process.XADD
without first establishing a connection to the Redis server. Always ensure your Redis instance is running and accessible.What is the 'approximate' parameter in the xadd
command?
The 'approximate' parameter, when set to True, allows Redis to remove just enough elements to get close to the maxlen
.
Can I add multiple fields and values in a single xadd
operation?
Yes, the message in xadd
is a dictionary and can have multiple field-value pairs.
Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement.