Search code examples
javaredislettuce

Add custom object list to Redis


I am a newbie to Redis. I want to store and search over a list of custom objects in Redis cache. custom object has 4 attribute

  1. configKey
  2. configScope
  3. valueType
  4. configValue

Sample custom object

{"configScope":"country","configValue":"india","configKey":"country","valueType":"string"}
{"configScope":"integer","configValue":"3","configKey":"integer","valueType":"string"}
{"configScope":"sport","configValue":"sport","configKey":"sport","valueType":"string"}
{"configScope":"country","configValue":"india","configKey":"country","valueType":"string"}

couldn't understand how to store these object as i can efficiently search the string based configKey or configScope or configValue.

have written sample code but it is only giving result based on exact key

for (CustomObject model : list) {
    CustomObject ec = (CustomObject) model;
    syncCommands.lpush("orgId:EC:"+count++, ec.toString());
}

KeyScanCursor<String> cursor = syncCommands.scan(ScanArgs.Builder.limit(50).match("orgId:EC:10"));

while (!cursor.isFinished()) {
    for (String key : cursor.getKeys()) {
        List<String> value = syncCommands.lrange(key, 0, 50);
        System.out.println(key + " - " + value);
    }
   cursor = syncCommands.scan(cursor, 
   ScanArgs.Builder.limit(50).match("orgId:EC:10"));
}

Any idea or reference will be helpful.


Solution

  • You may try and see if redis Lexicographical indexes may help in your case, for example the sample document below can be stored in redis sorted set and do Lex search on it.

    {"configScope":"country","configValue":"india","configKey":"country","valueType":"string"}
    
    {"configScope":"country","configValue":"russia","configKey":"country","valueType":"string"}
    
    127.0.0.1:6379> zadd cs:country 0 cv:russia:ck:country:vt:string 0 ck:country:cv:russia:vt:string
    (integer) 2
    127.0.0.1:6379> zadd cs:country 0 cv:india:ck:country:vt:string 0 ck:country:cv:india:vt:string
    (integer) 2
    

    Now to search configScope country and configValue india, you can do the following search

    127.0.0.1:6379> zrangebylex cs:country "[cv:india" "(cv:india~"
    1) "cv:india:ck:country:vt:string"
    

    And Similarly to search configScope country with configKey country

    127.0.0.1:6379> zrangebylex cs:country "[ck:country" "(ck:country~"
    1) "ck:country:cv:india:vt:string"
    2) "ck:country:cv:russia:vt:string"
    

    I hope this will help you in getting started with this approach, for more information of lexicographical indexes in redis Secondary Indexing with Redis