Redis XREVRANGE in PHP (Detailed Guide w/ Code Examples)

Use Case(s)

The XREVRANGE command in Redis is used to fetch data from a stream in a reverse order. Common use cases include:

  1. Retrieving the most recent N items from a stream.
  2. Paginating results in reverse order.

Code Examples

Here's an example using the Predis library in PHP:

<?php require "vendor/autoload.php"; $predis = new Predis\Client(); // Add messages to 'mystream' $predis->xadd('mystream', '*', 'field1', 'Hello'); // Fetch last 10 messages $messages = $predis->xrevrange('mystream', '+', '-', ['count' => 10]); foreach ($messages as $messageId => $message) { echo "ID: $messageId\n"; foreach($message as $key => $value){ echo "Field: $key, Value: $value\n"; } } ?>

In this code, we first create a connection with Redis using Predis and then add a message to our stream called 'mystream'. We then use XREVRANGE to fetch the last 10 messages from the stream.

Best Practices

  1. Be careful with the size of the range you're requesting. Requesting large ranges in production environments can lead to performance issues.
  2. Consider using XREAD instead of XREVRANGE if you’re primarily interested in new entries and want to avoid scanning through older ones.

Common Mistakes

  1. Not specifying a count or specifying too large a count can lead to slow commands because Redis needs to load all these elements to memory.
  2. Misunderstanding the '-' and '+' special IDs. Remember, '+' represents the highest possible ID and '-' the lowest possible ID.

FAQs

  1. Is XREVRANGE available in all versions of Redis? No, XREVRANGE is only available in Redis 5.0 and newer versions.

  2. Can I use XREVRANGE to fetch data in original order? No, you should use XRANGE for that purpose. XREVRANGE retrieves data in reverse order.

Was this content helpful?

Start building today

Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement.