Alvaro Alday
Alvaro Alday

Reputation: 363

Redis: How do I calculate time differences in a sorted list time-series?

I'm trying to calculate the response times between messages stored in Redis. But I have no clue how to do this.

First I have to store the time-stream of chat_messages like this

ZADD conversation:CONVERSATION_ID:chat_messages TIMESTAMP CHAT_MESSAGE_ID
ZADD conversation:9:chat_messages 1511533205001 2583
ZADD conversation:9:chat_messages 1511533207057 732016

Afterward, I need the application to be able to calculate the time difference between timestamps using Redis because I need the extra speed of doing it without another (potentially slower) technology.

Is there a way of achieving this using plain Redis or Lua?

Upvotes: 1

Views: 556

Answers (1)

LeoMurillo
LeoMurillo

Reputation: 6764

The timestamp you are using seems to be in milliseconds, so you only need to substract and convert to your desired units.

You can get the score using ZSCORE for each message. Or use one of the ZRANGE methods to get multiple messages at once: ZRANGEBYSCORE ... WITHSCORES.

You can use a Lua script to get the time difference:

local t1 = redis.call('ZSCORE', KEYS[1], ARGV[1])
local t2 = redis.call('ZSCORE', KEYS[1], ARGV[2])
return tonumber(t2) - tonumber(t1)

Here the full EVAL command:

EVAL "local t1 = redis.call('ZSCORE', KEYS[1], ARGV[1]) local t2 = redis.call('ZSCORE', KEYS[1], ARGV[2]) return tonumber(t2) - tonumber(t1)" 1 conversation:9:chat_messages 2583 732016

Upvotes: 1

Related Questions