Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to search by element value in the list of Redis cache?

We are using the redis cache and below the sample type of data we are storing

LLPUSH mylist "abc" "xyx" "awe" "wwqw"

Now I am want to search in the redis from Spring project. For example my Spring project class receives one element from some external client "abc". How can search the Redis list by value? Something like below:

ListOperations<String, Object> listOperations = redisTemplate.opsForList();

listOperations.get(key,"abc"); // returns abc

Or at least I want confirmation that this element is present in the list of Redis cache:

listOperations.contains(key, "abc"); // returns either true or false, based on the value presence

Can someone please suggest of this type of client lib is present for Redis from Java side and that we can use in the Spring boot project?

like image 359
Bravo Avatar asked Oct 28 '25 01:10

Bravo


1 Answers

Redis lists are implemented as linked lists.

  • Hence, you will either have to get all elements of the list using LRANGE and iterate to find a particular element.
  • If the list does not contain multiple entries and the order is not relevant, we can use LREM to remove the particular element and if there is a difference in list size, the element exists. Later, the removed element can be re-inserted if exists.

    Long initialSize = redisTemplate.opsForList().size(key);
    redisTemplate.opsForList().remove(key,0, value);
    Long finalSize = redisTemplate.opsForList().size(key);
    if(finalSize - initialSize > 0){
        redisTemplate.opsForList().rightPush(key,value);
        return true;     //Element exists
    }
    return false;    //Does not exist
    

Consider making the operations atomic.

You can get the other spring redis list operations from here.

like image 131
coder_r Avatar answered Oct 29 '25 18:10

coder_r



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!