preface

This article will cover the sortedSet command in Redis, again through demo, and the rest will not be covered here.

Github address: github.com/rainbowda/l…

case

Demo functions are articles like ranking and so on, the general page of the demo is as follows.

The preparatory work

Start by defining a key to store the article

private static final String ZSET_KEY = "articleList";
Copy the code

Redis operates on objects

private RedisTemplate redisTemplate;
//string Command operation object
private ValueOperations valueOperations;
//zset manipulates objects
private ZSetOperations zSetOperations;
Copy the code

The structure of a sortedset in Redis can be seen below (image from Redis in Action).

A list of the query

@RequestMapping(value = "/getList/{sortType}", method = RequestMethod.GET)
public Set getList(@PathVariable String sortType) {
    If there is no data, add 10 data
    if (zSetOperations.size(ZSET_KEY) == 0) {for (int i = 1; i <= 10; i++) {
            zSetOperations.add(ZSET_KEY,"Article:"+i, (int)(Math.random()*10+i)); }}//ASC sorts the score from lowest to highest and vice versa
    if ("ASC".equals(sortType)){
        return zSetOperations.rangeWithScores(ZSET_KEY, 0, -1);
    } else {
        return zSetOperations.reverseRangeWithScores(ZSET_KEY, 0, -1); }}Copy the code

To save you the trouble of adding data one by one, we add a judgment to the list data. When the article data is 0, the default add 10 data, set random score plus the index. The parameter sortType in the URL is then used to determine whether the returned data is sorted in fractional ascending or descending order. Function effects are as follows

Command to introduce

The command Use cases describe
ZADD ZADD key [NX|XX][CH] [INCR] score member [score member …] Adds all specified members to the keykeySorted set
ZRANGE ZRANGE key start stop [WITHSCORES] Returns a member of the ordered set key within the specified range. Members are ranked in descending order of score (from small to large).
ZREVRANGE ZREVRANGE key start stop [WITHSCORES] Returns a member of the ordered set key within the specified range. Members are placed in descending order of score (from highest to lowest).

Praise or trample

The Java code is as follows

@RequestMapping(value = "/star", method = RequestMethod.POST)
public boolean starOrUnStar(String member, String type) {
    if ("UP".equals(type)){
        zSetOperations.incrementScore(ZSET_KEY, member, 1);
    } else {
        zSetOperations.incrementScore(ZSET_KEY, member, -1);
    }
    return true;
}
Copy the code

Decide whether to add or subtract the score according to type. When type is UP, it means like; when type is other, it means stamp. Function effects are as follows

Command to introduce

The command Use cases describe
ZINCRBY ZINCRBY key increment member Add increment to score value of member of ordered set key

Ascending ranking

The Java code is as follows

@RequestMapping(value = "/rank/{type}/{member}", method = RequestMethod.GET)
public Long rank(@PathVariable String member, @PathVariable String type) {
    Long rank = null;
    if ("ASC".equals(type)){
        rank = zSetOperations.rank(ZSET_KEY, member);
    } else {
        rank = zSetOperations.reverseRank(ZSET_KEY, member);
    }

    return rank;
}
Copy the code

The ascending or descending ranking is determined by type. In the case of ASC, the ascending or descending ranking is obtained by calling the Rank method. In the case of other ASC, the descending ranking is obtained by calling reverseRank. This is similar to the redis command below

ZRANK articleList Article 1 ""
ZREVRANK articleList Article 1 ""
Copy the code

The page rendering is shown below

Command to introduce

The command Use cases describe
ZRANK ZRANK key member Returns the ranking of members in the ordered set key. Members of the ordered set are arranged in ascending order (from small to large) by score value. The ranking is based on 0, which means that the member with the lowest score is ranked 0.
ZREVRANK ZREVRANK key member Return the ranking of members in the ordered set key, where the ordered set members are ranked according to the score value from the largest to the smallest.

Other commands

Retrieve attributes

The command Use cases describe
ZCARD ZCARD key Returns the number of ordered set elements for key.
ZCOUNT ZCOUNT key min max Returns the number of members of an ordered set key whose score is between min and Max (default includes score equal to min or Max).
ZLEXCOUNT ZLEXCOUNT key min max Used to count the number of members between specified members in an ordered collection.
ZSCORE ZSCORE key member Return score of member in ordered set key.
ZCARD command

Returns the number of ordered set elements for key. ZCARD Key return value: if key exists, the number of elements in the ordered set is returned, otherwise 0 is returned.

The redis client executes the following command

zadd zCardKey 1 one
zcard zCardKey
Copy the code

Here is the Java code

@Test
public void zCard(a) {
    jedis.zadd("zCardKey".1."one");
    jedis.zadd("zCardKey".2."two");

    System.out.println(jedis.zcard("zCardKey"));

    System.out.println(zSetOperations.size("zCardKey"));
}
Copy the code
ZCOUNT command

Returns the number of members in the ordered set key whose score is between min and Max (including score equal to min or Max by default). ZCOUNT Key min Max Returns the number of elements in the fraction range.

The redis client executes the following command

zadd zCountKey 1 one 2 two 3 three 4 four
zcount zCountKey 2 3
Copy the code

The result is as follows

Here is the Java code

@Test
public void zCount(a) {
    jedis.zadd("zCountKey".1."one");
    jedis.zadd("zCountKey".2."two");
    jedis.zadd("zCountKey".3."three");
    jedis.zadd("zCountKey".4."four");

    System.out.println(jedis.zcount("zCountKey".2.3));

    System.out.println(zSetOperations.count("zCountKey".2.3));
}
Copy the code
ZLEXCOUNT command

Calculate the number of members between the specified members in an ordered set (sorted in positive order by the member dictionary). You can use – and + to indicate the minimum and maximum score values ZLEXCOUNT key min Max

The redis client executes the following command

ZADD zLexCountKey 2 "b" 1 "a" 3 "c" 5 "e" 4 "d"
ZLEXCOUNT zLexCountKey - +
ZLEXCOUNT zLexCountKey [b [d
Copy the code

The result is as follows

Here is the Java code

@Test
public void zLexCount(a) {
    zSetOperations.add("zLexCountKey"."b".2);
    zSetOperations.add("zLexCountKey"."a".1);
    zSetOperations.add("zLexCountKey"."c".3);
    zSetOperations.add("zLexCountKey"."e".5);
    zSetOperations.add("zLexCountKey"."d".4);

    System.out.println(jedis.zlexcount("zLexCountKey"."-"."+"));

    System.out.println(jedis.zlexcount("zLexCountKey"."[b"."[d"));
}
Copy the code
ZSCORE command

Return score of member in ordered set key. ZSCORE key member Return value: score value of a member member

The redis client executes the following command

zadd zScoreKey 1 one
ZSCORE zScoreKey one
Copy the code

Here is the Java code

@Test
public void zScore(a) {
    jedis.zadd("zScoreKey".1."one");

    System.out.println(jedis.zscore("zScoreKey"."one"));

    System.out.println(zSetOperations.score("zScoreKey"."one"));
}
Copy the code

Get member

The command Use cases describe
ZRANGEBYLEX ZRANGEBYLEX key min max [LIMIT offset count] Returns the members of the specified member range, sorted by the member dictionary.
ZRANGEBYSCORE ZRANGEBYSCORE key min max [WITHSCORES]``[LIMIT offset count] Returns all members that meet the score criteria
ZREVRANGEBYLEX ZREVRANGEBYLEX key max min [LIMIT offset count] Returns the members of the specified member range, sorted in reverse order by member dictionary.
ZREVRANGEBYSCORE ZREVRANGEBYSCORE key max min [WITHSCORES]``[LIMIT offset count] Returns the members of the ordered collection within the specified range of scores, sorted from highest to lowest.
ZSCAN ZSCAN key cursor [MATCH pattern]``[COUNT count] Please refer to the SCAN
ZRANGEBYLEX command

Returns the members of the specified member range, sorted by the member dictionary. https://redis.io/commands/zrangebylex ZRANGEBYLEX key min Max [LIMIT offset count] return values: members of the specified range of elements.

The redis client executes the following command

ZADD zRangeByLexKey 0 ba 0 a 0 ab 0 aa 0 b
ZRANGEBYLEX zRangeByLexKey - +
ZRANGEBYLEX zRangeByLexKey [aa (ba
Copy the code

The result is as follows

Here is the Java code

@Test
public void zRangeByLex(a) {
    zSetOperations.add("zRangeByLexKey"."ba".0);
    zSetOperations.add("zRangeByLexKey"."a".0);
    zSetOperations.add("zRangeByLexKey"."ab".0);
    zSetOperations.add("zRangeByLexKey"."aa".0);
    zSetOperations.add("zRangeByLexKey"."b".0);

    System.out.println(jedis.zrangeByLex("zRangeByLexKey"."-"."+"));

    RedisZSetCommands.Range range = new RedisZSetCommands.Range();
    range.gte("aa");
    range.lt("ba");
    System.out.println(zSetOperations.rangeByLex("zRangeByLexKey",range));
}
Copy the code
ZRANGEBYSCORE command

Get the data within the score range. -inf/inf ZRANGEBYSCORE key min Max [WITHSCORES] ‘ ‘[LIMIT offset count]

The redis client executes the following command

ZADD zRangeByScoreKey 1 ba 2 a 3 ab 4 aa 5 b
ZRANGEBYSCORE zRangeByScoreKey -inf +inf
ZRANGEBYSCORE zRangeByScoreKey 2 4
Copy the code

The result is as follows

Here is the Java code

@Test
public void zRangeByScore(a) {
    zSetOperations.add("zRangeByScoreKey"."ba".1);
    zSetOperations.add("zRangeByScoreKey"."a".2);
    zSetOperations.add("zRangeByScoreKey"."ab".3);
    zSetOperations.add("zRangeByScoreKey"."aa".4);
    zSetOperations.add("zRangeByScoreKey"."b".5);

    System.out.println(jedis.zrangeByScore("zRangeByScoreKey"."-inf"."+inf"));

    RedisZSetCommands.Range range = new RedisZSetCommands.Range();
    System.out.println(zSetOperations.rangeByScore("zRangeByScoreKey".2.4));
}
Copy the code

Remove related commands

The command Use cases describe
ZREM ZREM key member [member …] Deletes a member of an ordered collection
ZREMRANGEBYLEX ZREMRANGEBYLEX key min max Deletes all members between members whose names are sorted lexicographically from lowest to highest
ZREMRANGEBYRANK ZREMRANGEBYRANK key start stop Removes all members of the ordered set key from the specified rank range.
ZREMRANGEBYSCORE ZREMRANGEBYSCORE key min max Remove all members of ordered set key whose score is between min and Max (including those whose score is equal to min or Max)
ZREM command

ZREM key member [member …] Return value: The number of members removed from the ordered collection

The redis client executes the following command

ZADD zRemKey 1 "one" 2 "two" 3 "three"
ZREM zRemKey one
ZRANGE zRemKey 0 -1
Copy the code

The result is as follows

Here is the Java code

@Test
public void zRem(a) {
    zSetOperations.add("zRemKey"."one".1);
    zSetOperations.add("zRemKey"."two".2);
    zSetOperations.add("zRemKey"."three".3);

    //jedis.zrem("zRemKey", "one");
    zSetOperations.remove("zRemKey"."one");

    System.out.println(zSetOperations.range("zRemKey".0 , -1));
}
Copy the code

Occurring simultaneously set

The command Use cases describe
ZINTERSTORE ZINTERSTORE destination numkeys key [key ...] ``[WEIGHTS weight] [SUM\|MIN\|MAX] Computes the intersection of the ordered set of the given Numkeys and places the result in destination
ZUNIONSTORE ZUNIONSTORE destination numkeys key [key ...] ``[WEIGHTS weight] [SUM\|MIN\|MAX] Computes the union of the given ordered set of Numkeys and places the result in destination
ZINTERSTORE command

Computes the intersection of the ordered set of the given Numkeys and places the result in destination. The number of keys must be given before the key and other parameters to be evaluated are given. By default, the score of an element in the result is the sum of the scores of that element in the ordered set, provided that the element exists in all of those ordered sets. Because intersection requires that its members be members of each ordered set given, the fraction of each element in the result set is equal to the number of ordered sets input. For a description of WEIGHTS and AGGREGATE parameters, see the ZUNIONSTORE command. If the destination exists, override it.

ZINTERSTORE destination numkeys key [key …] [WEIGHTS weight [weight…]] [AGGREGATE SUM | MIN | MAX] return values: results of an ordered set the number of elements in destination. The redis client executes the following command

ZADD zInterStoreKey1 1 "one" 2 "two"
ZADD zInterStoreKey2 1 "one" 2 "two" 3 "three"
ZINTERSTORE zInterStoreSumResult 2 zInterStoreKey1 zInterStoreKey2 WEIGHTS 2 3

ZRANGE zInterStoreSumResult 0 -1 WITHSCORES
Copy the code

The result is as follows

Here is the Java code

@Test
public void zInterStore(a) {
    zSetOperations.add("zInterStoreKey1"."one".1);
    zSetOperations.add("zInterStoreKey1"."two".2);

    zSetOperations.add("zInterStoreKey2"."one".1);
    zSetOperations.add("zInterStoreKey2"."two".2);
    zSetOperations.add("zInterStoreKey2"."three".3);


    ZParams zParams = new ZParams();
    zParams.weightsByDouble(2.3);
    zParams.aggregate(ZParams.Aggregate.SUM);
    jedis.zinterstore("zInterStoreSumResult", zParams, "zInterStoreKey1"."zInterStoreKey2");

    printTuple("zInterStoreSumResult", jedis.zrangeWithScores("zInterStoreSumResult".0, -1));
}
Copy the code
ZUNIONSTORE command

Computes the union of the given ordered set of Numkeys and places the result in destination. WEIGHTS are equal to WEIGHTS. The default value is 1. You can set different WEIGHTS for different keys. ZUNIONSTORE destination numKeys key [key…] ZUNIONSTORE destination numkeys key [key…] [WEIGHTS weight [weight …] ] [AGGREGATE SUM|MIN|MAX]

The redis client executes the following command

ZADD zUnionStoreKey1 1 "one" 2 "two"
ZADD zUnionStoreKey2 1 "one" 2 "two" 3 "three"
ZUNIONSTORE zUnionStoreSumResult 2 zUnionStoreKey1 zUnionStoreKey2 WEIGHTS 2 3
ZUNIONSTORE zUnionStoreMinResult 2 zUnionStoreKey1 zUnionStoreKey2 WEIGHTS 2 3 AGGREGATE MIN
ZUNIONSTORE zUnionStoreMaxResult 2 zUnionStoreKey1 zUnionStoreKey2 WEIGHTS 2 3 AGGREGATE MAX
     *
ZRANGE zUnionStoreSumResult 0 -1 WITHSCORES
ZRANGE zUnionStoreMinResult 0 -1 WITHSCORES
ZRANGE zUnionStoreMaxResult 0 -1 WITHSCORES
Copy the code

The result is as follows

Here is the Java code

@Test
public void zUnionStore(a) {
    zSetOperations.add("zUnionStoreKey1"."one".1);
    zSetOperations.add("zUnionStoreKey1"."two".2);

    zSetOperations.add("zUnionStoreKey2"."one".1);
    zSetOperations.add("zUnionStoreKey2"."two".2);
    zSetOperations.add("zUnionStoreKey2"."three".3);


    ZParams zParams = new ZParams();
    zParams.weightsByDouble(2.3);
    zParams.aggregate(ZParams.Aggregate.SUM);
    jedis.zunionstore("zUnionStoreSumResult", zParams, "zUnionStoreKey1"."zUnionStoreKey2");

    // Find the minimum value
    zParams.aggregate(ZParams.Aggregate.MIN);
    jedis.zunionstore("zUnionStoreMinResult", zParams, "zUnionStoreKey1"."zUnionStoreKey2");

    // Find the maximum value
    zParams.aggregate(ZParams.Aggregate.MAX);
    jedis.zunionstore("zUnionStoreMaxResult", zParams, "zUnionStoreKey1"."zUnionStoreKey2");

    //spring
    zSetOperations.unionAndStore("zUnionStoreKey1"."zUnionStoreKey2"."zUnionStoreResult");


    printTuple("zUnionStoreSumResult", jedis.zrangeWithScores("zUnionStoreSumResult".0, -1));
    printTuple("zUnionStoreMinResult", jedis.zrangeWithScores("zUnionStoreMinResult".0, -1));
    printTuple("zUnionStoreMaxResult", jedis.zrangeWithScores("zUnionStoreMaxResult".0, -1));
    printTuple("zUnionStoreResult", jedis.zrangeWithScores("zUnionStoreResult".0, -1));
}
Copy the code

It is also suggested that learners should type every command to make a deeper impression.

The paper come zhongjue shallow, and must know this to practice. ———— from Reading a Book on a Winter Night