Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Redis Get Values by Wildcard Keys

I am using Spring Data RedisTemplate (not Repository). Everything works fine with

template.opsForValues().get("mykey:1")

But I have some more complex keys such as "myobject:somesituation:1" and "myobject:anothersituation:2" and so on. I need to do something like:

template.opsForValues().get("myobject:somesituation:*")

With the wildcard, I would like to get all values in the "somesituation", no matter what is its id.

Using redis command line, I have no problem.

Obs.: I am using reactive template, don't know(believe) if this could be the problem. Obs2: After a research, I have just found posts about Spring Repository, get all keys, get by command line, etc. But not about my specific problem.

like image 547
Igor Veloso Avatar asked May 25 '17 18:05

Igor Veloso


2 Answers

The solution is to use:

enter image description here

In the red rectangle, i marked the method you should use in order to achieve your goal.

You can do something like:

Set<String> keys = template.keys("myobject:somesituation:*")

and then query your set of keys.

Hope this helps.

like image 89
Moshe Arad Avatar answered Oct 24 '22 00:10

Moshe Arad


Would a redis hash better model your data? https://redis.io/topics/data-types

instead of top level keys

myobject:somesituation:1
myobject:somesituation:2
myobject:somesituation:3

at the top level you have one key

myobject:somesituation

and the value itself has key/value pairs

Object value = template.opsForHash().get("myobject:somesituation", "1");

OR

Map<Object,Object> map = template.opsForHash().entries("myobject:somesituation");
value = map.get("1");

Avoid using redis KEYS command, as it blocks all redis clients while it executes. SCAN is not much better, if you have allot of keys it can require hundreds of roundtrips to redis to scan the whole keyspace.

like image 3
dan carter Avatar answered Oct 24 '22 01:10

dan carter