Bravo
Bravo

Reputation: 9047

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?

Upvotes: 3

Views: 9357

Answers (3)

Nikita Koksharov
Nikita Koksharov

Reputation: 10803

You can easily do this with Redisson Redis client and Redis based List object:

List<String> list = redisson.getList("myList");

list.add("aaa");
list.add("bbb");
list.add("ccc");

// returns true
list.contains("aaa");

Upvotes: 0

donm
donm

Reputation: 1210

You can use Redis Set which has sismember(keyForSet,valueToSearch) to search element by value with O(1) complexity which is efficient, In order to use with redisTemplate you can use redisTemplate.opsForSet.isMember(keyForSet,valueToSearch)

While inserting you can insert list like jedis.sadd(keyForSet, myList.toArray(new String[myList.size()])); Or with redisTemplate redisTemplate.opsForSet.add(keyForSet, myList.toArray(new String[myList.size()]));

Upvotes: 1

coder_r
coder_r

Reputation: 90

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.

Upvotes: 2

Related Questions