The Redis XDEL
command is used to delete one or more items from a stream by ID. Common use cases include:
package main import ( "fmt" "github.com/go-redis/redis/v8" "context" ) func main() { // Establish a connection to your Redis server rdb := redis.NewClient(&redis.Options{ Addr: "localhost:6379", }) ctx := context.TODO() // Delete a message from the stream 'mystream' with ID '123-0' result, err := rdb.XDel(ctx, "mystream", "123-0").Result() if err != nil { fmt.Printf("Error: %v\n", err) } else { fmt.Printf("Number of Deleted Entries: %v\n", result) } }
This example deletes a single item from the stream 'mystream' with the ID '123-0'. It then prints the number of deleted entries (should be 1 if the specified entry exists).
package main import ( "fmt" "github.com/go-redis/redis/v8" "context" ) func main() { // Establish a connection to your Redis server rdb := redis.NewClient(&redis.Options{ Addr: "localhost:6379", }) ctx := context.TODO() // Delete multiple messages from the stream 'mystream' with IDs '123-0', '124-0' result, err := rdb.XDel(ctx, "mystream", "123-0", "124-0").Result() if err != nil { fmt.Printf("Error: %v\n", err) } else { fmt.Printf("Number of Deleted Entries: %v\n", result) } }
This example deletes two items from the stream 'mystream' with the IDs '123-0' and '124-0'. It then prints the number of deleted entries (should be 2 if both the specified entries exist).
XDEL
to avoid runtime errors.XDel()
function.1. What happens if I try to delete an ID that doesn't exist in the stream? If you try to delete a non-existent ID, Redis doesn't throw an error. Instead, it returns 0 indicating that no entries were deleted.
2. Is there a way to delete all entries from a stream?
Yes, you could use the XTRIM
command with the MAXLEN set to 0 to delete all entries in a stream. However, be careful when using this command as data once deleted cannot be recovered.
Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement.