Dragonfly Cloud announces new enterprise security features - learn more

Redis XDEL in Golang (Detailed Guide w/ Code Examples)

Use Case(s)

The Redis XDEL command is used to delete one or more items from a stream by ID. Common use cases include:

  • Cleaning up old data from a stream that's no longer needed.
  • Removing erroneous entries in the stream.

Code Examples

Example 1: Deleting a Single Item

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).

Example 2: Deleting Multiple Items

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).

Best Practices

  • Only delete entries when needed to free up memory as it can be an expensive operation.
  • Validate the IDs before performing XDEL to avoid runtime errors.

Common Mistakes

  • Trying to delete non-existent IDs. This doesn't throw an error but returns 0 indicating that no entries were deleted.
  • Not handling the error properly that occurs during the execution of the XDel() function.

FAQs

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.

Was this content helpful?

Switch & save up to 80% 

Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement. Instantly experience up to a 25X boost in performance and 80% reduction in cost