0
0
RedisHow-ToBeginner · 3 min read

How to Use XADD Command in Redis Streams

Use the XADD command in Redis to add new entries to a stream. It requires the stream key, an entry ID (or * for auto-generated), and field-value pairs to store data in the stream.
📐

Syntax

The XADD command adds a new entry to a Redis stream. It requires the stream key, an entry ID, and one or more field-value pairs.

  • key: The name of the stream.
  • id: The entry ID, usually * to auto-generate.
  • field value: One or more pairs representing the data to store.
plaintext
XADD key id field value [field value ...]
💻

Example

This example shows how to add an entry to a stream named mystream with two fields: temperature and humidity. The * lets Redis create a unique ID automatically.

plaintext
XADD mystream * temperature 22.5 humidity 60
Output
1609459200000-0
⚠️

Common Pitfalls

Common mistakes include:

  • Using a fixed ID instead of *, which can cause errors if the ID already exists.
  • Not providing field-value pairs, which makes the command invalid.
  • Confusing streams with lists or sets; XADD only works with streams.
plaintext
XADD mystream 1609459200000-0 temperature 22.5 humidity 60  # May fail if ID exists

XADD mystream *  # Invalid, missing field-value pairs

# Correct usage:
XADD mystream * temperature 22.5 humidity 60
📊

Quick Reference

ParameterDescription
keyName of the stream to add entry to
idEntry ID, use '*' for auto-generated
fieldField name for the data
valueValue for the field
field value ...Additional field-value pairs

Key Takeaways

Use XADD to add entries to Redis streams with field-value pairs.
Use * as the ID to let Redis auto-generate unique entry IDs.
Always provide at least one field-value pair; otherwise, the command fails.
Avoid using fixed IDs unless you are sure they don't exist to prevent errors.
Remember XADD works only with streams, not other Redis data types.