How to increase redis sort value

TL DR I'm looking for a way to store, increase, and retrieve event ranges per minute.

I am looking for a solution to create additional time periods in redis. I am looking to keep bills for up to a minute. My goal is to find the time range and get the values. Therefore, for instnace, if an event occurred for a particular key 30 times per minute. I would like to do something like zrange and get their key values. I also hope to use something like zincrby to increase the value. Of course, I looked at the sorted set, which would seem to be perfectly suitable, until I realized that I can only do a range scan, but not a value. The best solution would be to use the number of minutes as an estimate, and then use the value in the sorted set as the number of events for that minute. The problem I ran into is that zincrby only increases the score, not the value. I could not find a way to increase the value atomically. I also looked at the hash map using the current minute, since the key and event are counted as a value. I was able to increase the value with hincrby, but the problem is that it does not support key range selection.

Any help would be appreciated.

+6
source share
1 answer

You know, the question already has an answer. And you are already talking about how to solve your problem:

  • Use ZSET - enter the time and value as a counter.
  • Use HSET - enter the time and value as a counter.
  • Use string keys - key name as time and value as counter.

Why only these cases - only of these structures ( ZSET , HSET and string keys ) has atomic methods for increasing values.

So relevant:

  • You must choose the right data structure.
  • Fix the problem with the data selection.

The first question is the trade-off between memory and performance. From your question, you do not need to have any types if sorting such sorted sets is not the best solution - it consumes a lot of memory and ZINCRBY is the time complexity of O (log (N)) rather HINCRBY and INCRBY O (1) . Therefore, we must choose betweeh hashes and string keys. Look at the question and answer about the correct memory optimization in redis - according to this, I think you should use hashes as the data type for your solution.

The second question is common for all types of data structures, since all their types do not contain select by name functions or their analogues. And we can use HMGET or LUA Scripts to solve this problem. In any case, this solution will have a time complexity of O (n) .

Here is an example with Jedis (I'm not a Java programmer, sorry for possible errors):

 int fromMinute = 1; int toMinute = 10; List<String> list = new ArrayList<String>(); for(int i = fromMinute ; i < toMinute ; i++) { list.add(i.toString()); } Jedis jedis = new Jedis("localhost"); List<String> values = jedis.hmget("your_set_name", list); 

This solution is atomic, fast, has O (n) time complexity and consumes as little memory as possible in redis.

+4
source

All Articles