Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return all keys from jedis that match a partial key

Tags:

java

redis

jedis

In Redis cache I have 3 keys

1111-2222-4444 1111-2222-3333 1112-2222-3333

I have a partial key 1111, and I want to return the two keys 1111-2222-4444, 1111-2222-3333

I have the following code

public List<String> getKeys(String partialkey) {
        ScanParams scanParams = new ScanParams();
        scanParams.match("*");
        String cur = redis.clients.jedis.ScanParams.SCAN_POINTER_START;
        Jedis jedis = jedisPool.getResource();

        List<String> keys = new ArrayList<String>();
        boolean cycleIsFinished = false;
        while (!cycleIsFinished) {
            ScanResult<String> scanResult = jedis.scan(cur, scanParams);
            cur = scanResult.getCursor();
            for(String key :scanResult.getResult()) {
                if(isKey(key, partialkey) ) {
                    keys.add(key);
                }
            }
            if (cur.equals("0")) {
                cycleIsFinished = true;
            }
        }
        return keys;
    }

And a method to match for partial key

    private boolean isKey(String key, String match) {
        String[] fields = key.split("-");
        if(match.equals(fields[0])) {
            return true;
        }
        return false;
    }

Now this works, but it seems very clunky, there could be thousands of keys, to search through. My question is, is there a pure redis way to do this. Where it only returns the two keys, that the partial key matches to.

like image 937
Tony Avatar asked Oct 19 '25 02:10

Tony


1 Answers

With thanks to shmosel

public List<String> getKeys(String partialkey) {
        ScanParams scanParams = new ScanParams();
        scanParams.match(partialkey+"-*");
        String cur = redis.clients.jedis.ScanParams.SCAN_POINTER_START;
        Jedis jedis = jedisPool.getResource();

        List<String> keys = new ArrayList<String>();
        boolean cycleIsFinished = false;
        while (!cycleIsFinished) {
            ScanResult<String> scanResult = jedis.scan(cur, scanParams);
            cur = scanResult.getCursor();
            for(String key :scanResult.getResult()) {
                //if(isKey(key, partialkey) ) {
                    keys.add(key);
                //}
            }
            if (cur.equals("0")) {
                cycleIsFinished = true;
            }
        }
        return keys;
    }
like image 121
Tony Avatar answered Oct 20 '25 16:10

Tony