Jedis Operation Redis--sortedset Type

Source: Internet
Author: User

/ **
 * SortedSet (sorted set)
 * ZADD, ZCARD, ZCOUNT, ZINCRBY, ZRANGE, ZRANGEBYSCORE, ZRANK, ZREM, ZREMRANGEBYRANK, ZREMRANGEBYSCORE, ZREVRANGE
 * ZREVRANGEBYSCORE, ZREVRANK, ZSCORE, ZUNIONSTORE, ZINTERSTORE, ZSCAN, ZRANGEBYLEX, ZLEXCOUNT, ZREMRANGEBYLEX
 * /
public class SortedSetTypeTest {

    private Jedis jedis;

    private static final String KEY = "sorted_set";

    private static final String VALUE = "layman";

    @Before
    public void setUp () {
        this.jedis = new Jedis (new JedisShardInfo ("192.168.133.188", 6379));
    }

    / **
     * ZADD key score member [[score member] [score member] ...]
     * Add one or more member elements and their score values to the ordered set key.
     * If a member is already a member of an ordered set, update the score value of the member and reinsert the member element to ensure that the member is in the correct position.
     * The score value can be an integer value or a double-precision floating-point number.
     * If key does not exist, an empty ordered set is created and a ZADD operation is performed.
     * When key exists but is not an ordered set type, an error is returned.
     * /
    @Test
    public void ZADD () {
        Map <String, Double> sourceMember = new HashMap <String, Double> ();
        for (int i = 0; i <3; i ++) {
            double score = getRandomInt ();
            sourceMember.put (VALUE + score, score);
        }
        jedis.zadd (KEY, sourceMember);
        ZRANGE ();
    }

    / **
     * ZCARD key
     * Returns the cardinality of the ordered set key.
     * /
    @Test
    public void ZCARD () {
        System.out.println (jedis.zcard (KEY));
    }

    / **
     * ZCOUNT key min max
     * Returns the number of members in the ordered set key with score values between min and max (the default includes score values equal to min or max).
     * For detailed usage of the parameters min and max, please refer to the ZRANGEBYSCORE command.
     * /
    @Test
    public void ZCOUNT () {
        System.out.println (jedis.zcount (KEY, "-inf", "+ inf"));
        System.out.println (jedis.zcount (KEY, 24, 45));
    }

    / **
     * ZINCRBY key increment member
     * Add the increment value to the score value of the member member of the ordered set key.
     * You can subtract a corresponding value from the score by passing a negative increment, such as ZINCRBY key -5 member, which is to subtract 5 from the member's score.
     * When key does not exist, or member is not a member of key, ZINCRBY key increment member is equivalent to ZADD key increment member.
     * When key is not an ordered set type, an error is returned.
     * The score value can be an integer value or a double-precision floating-point number.
     * /
    @Test
    public void ZINCRBY () {
        ZRANGE ();
// jedis.zincrby (KEY, getRandomInt (), VALUE + 10);
// ZRANGE ();
        jedis.zincrby (KEY, 20, VALUE + 10);
        ZRANGE ();

    }

    / **
     * ZRANGE key start stop [WITHSCORES]
     * Returns the members of the ordered set key within the specified interval.
     * The positions of members are sorted by increasing score values (from small to large).
     * Members with the same score value are sorted in lexicographical order.
     * If you need the members to be sorted by decreasing score (large to small), use the ZREVRANGE command.
     * The subscript parameters start and stop both have 0 as the base, that is, 0 represents the first member of the ordered set, 1 represents the second member of the ordered set, and so on.
     * You can also use negative subscripts, with -1 for the last member, -2 for the penultimate member, and so on.
     * Subscripts outside the range will not cause errors.
     * For example, when the value of start is greater than the maximum index of the ordered set, or when start> stop, the ZRANGE command simply returns an empty list.
     * On the other hand, if the value of the stop parameter is greater than the maximum index of the ordered set, Redis treats stop as the maximum index.
     * You can use the WITHSCORES option to return a member with its score value. The returned list is represented in the format value1, score1, ..., valueN, scoreN.
     * The client library may return some more complex data types, such as arrays, tuples, etc.
     * <p />
     * ZREVRANGE key start stop [WITHSCORES]
     * Returns the members of the ordered set key within the specified interval.
     * The positions of the members are arranged in descending order of score (large to small).
     * Members with the same score are sorted in reverse lexicographical order.
     * The ZREVRANGE command is the same as the ZRANGE command except that the members are arranged in descending order of score values.
     * /
    @Test
    public void ZRANGE () {
// System.out.println (jedis.zrange (KEY, 0, -1));
        Set <Tuple> tuples = jedis.zrangeWithScores (KEY, 0, -1);
        for (Tuple tuple: tuples) {
            System.out.println (tuple.getElement () + ":" + tuple.getScore ());
        }
    }

    / **
     * ZRANGEBYSCORE key min max [WITHSCORES] [LIMIT offset count]
     * Returns all members in the ordered set key whose score values are between min and max (including equal to min or max). The members of an ordered set are ranked in ascending (small to large) score values.
     * Members with the same score value are arranged in lexicographical order (this attribute is provided by an ordered set, no additional calculation is required).
     * The optional LIMIT parameter specifies the number and interval of returned results (like SELECT LIMIT offset, count in SQL). Note that when the offset is large, the operation of positioning the offset may need to traverse the entire ordered set. This process is the worst complicated The degree is O (N) time.
     * The optional WITHSCORES parameter determines whether the result set returns only members of the ordered set, or returns members of the ordered set together with their score values.
     * This option is available since Redis 2.0.
     * Interval and unlimited
     * min and max can be -inf and + inf, so that you can use commands such as ZRANGEBYSCORE without knowing the minimum and maximum score values of the ordered set.
     * By default, the interval value uses a closed interval (less than or equal to or greater than or equal to). You can also use an optional open interval (less than or greater than) by adding (before the parameter.
     * <p />
     * ZREVRANGEBYSCORE key max min [WITHSCORES] [LIMIT offset count]
     * Returns all members of the ordered set key with a score value between max and min (including equal to max or min by default). The ordered set members are arranged in descending order of score values (large to small).
     * Members with the same score are sorted in reverse lexicographical order.
     * The ZREVRANGEBYSCORE command is the same as the ZRANGEBYSCORE command except that the members are arranged in descending order of score values.
     * /
    @Test
    public void ZRANGEBYSCORE () {
        System.out.println (jedis.zrangeByScore (KEY, 0, 100));
        System.out.println (jedis.zrangeByScore (KEY, 0, 100, 8, 15));
        System.out.println (jedis.zrangeByScore (KEY, "-inf", "+ inf"));
        System.out.println (jedis.zrangeByScore (KEY, "-inf", "+ inf", 8, 1));
        Set <Tuple> tuples = jedis.zrangeByScoreWithScores (KEY, "-inf", "+ inf", 8, 1);
        for (Tuple tuple: tuples) {
            System.out.println (tuple.getElement () + "=" + tuple.getScore ());
        }
    }

    / **
     * ZRANK key member
     * Returns the rank of member member in the ordered set key. The members of the ordered set are arranged in ascending (small to large) score values.
* The ranking is based on 0, which means that the member with the lowest score is ranked 0.
     * Use the ZREVRANK command to get the ranking of members in descending (large to small) scores.
     * <p />
     * ZREVRANK key member
     * Returns the rank of member member in the ordered set key. The members of the ordered set are sorted by descending score values (large to small).
     * Rankings are based on 0, which means that the member with the highest score is ranked 0.
     * Use the ZRANK command to get members ranked by increasing score values (from small to large).
     * /
    @Test
    public void ZRANK () {
        System.out.println (jedis.zrank (KEY, "layman56.0"));
    }

    / **
     * ZREM key member [member ...]
     * Remove one or more members from the ordered set key, non-existing members will be ignored.
     * When key exists but is not an ordered set type, an error is returned.
     * /
    @Test
    public void ZREM () {
        ZRANGE ();
        jedis.zrem (KEY, "layman72.0", "layman77.0");
        System.out.println ("#########################");
        ZRANGE ();
    }

    / **
     * ZREMRANGEBYRANK key start stop
     * Remove all members from the ordered set key in the specified rank range.
     * The interval is indicated by the subscript parameters start and stop, respectively, including start and stop.
     * The subscript parameters start and stop both have 0 as the base, that is, 0 represents the first member of the ordered set, 1 represents the second member of the ordered set, and so on.
     * You can also use negative subscripts, with -1 for the last member, -2 for the penultimate member, and so on.
     * /
    @Test
    public void ZREMRANGEBYRANK () {
        ZRANGE ();
        jedis.zremrangeByRank (KEY, 0, 1);
        System.out.println ("#####################");
        ZRANGE ();
    }

    / **
     * ZREMRANGEBYSCORE key min max
     * Remove all members in the ordered set key whose score values are between min and max (including equal to min or max).
     * Beginning with version 2.1.6, members with a score equal to min or max may not be included. For details, see the ZRANGEBYSCORE command.
     * /
    @Test
    public void ZREMRANGEBYSCORE () {
        ZRANGE ();
        jedis.zremrangeByScore (KEY, "53", "63"); // Delete 53 <score <63
        System.out.println ("########################");
        ZRANGE ();
    }

    / **
     * ZSCORE key member
     * Returns the score value of member member in the ordered set key.
     * If the member element is not a member of the ordered set key or key does not exist, nil is returned.
     * /
    @Test
    public void ZSCORE () {
        System.out.println (jedis.zscore (KEY, "layman84.0"));
    }

    / **
     * ZUNIONSTORE destination numkeys key [key ...] [WEIGHTS weight [weight ...]] [AGGREGATE SUM | MIN | MAX]
     * Calculate the union of a given ordered set or sets, where the number of given keys must be specified with the numkeys parameter, and store the union (result set) to destination.
     * By default, the score value of a member in the result set is the sum of the score values of that member in all the given sets.
     * WEIGHTS
     * With the WEIGHTS option, you can specify a multiplication factor for each given ordered set,
     * The score values of all members of a given ordered set are multiplied by the factors of the ordered set before being passed to the aggregation function.
     * If the WEIGHTS option is not specified, the multiplication factor is set to 1 by default.
     * AGGREGATE
     * With the AGGREGATE option, you can specify how the result set of the union is aggregated.
     * The parameter SUM is used by default, and the sum of the score values of a member in all sets can be used as the score value of that member in the result set; using the parameter MIN,
     * The minimum score value of a member in all sets can be used as the score value of the member in the result set; and the parameter MAX is the maximum score value of a member in all sets as the score value of the member in the result set.
     * /
    @Test
    public void ZUNIONSTORE () {
        ZADDForKey (KEY + 0);
        ZRANGE ();
        System.out.println ("###################################");
        System.out.println (jedis.zrange (KEY + 0, 0, -1));
        ZParams zParams = new ZParams ();
        zParams.aggregate (ZParams.Aggregate.MAX);
// zParams.weightsByDouble (1);
        jedis.zunionstore (KEY, zParams, KEY, KEY + 0);
        System.out.println ("###################################");
        System.out.println (jedis.zrange (KEY, 0, -1));
    }

    / **
     * ZINTERSTORE destination numkeys key [key ...] [WEIGHTS weight [weight ...]] [AGGREGATE SUM | MIN | MAX]
     * Calculate the intersection of a given one or more ordered sets, where the number of given keys must be specified with the numkeys parameter, and store the intersection (result set) to destination.
     * By default, the score value of a member in the result set is the sum of the score values of that member in all the given sets.
     * For a description of the WEIGHTS and AGGREGATE options, see the ZUNIONSTORE command.
     * /
    @Test
    public void ZINTERSTORE () {
        System.out.println (jedis.zrange (KEY, 0, -1));
        System.out.println ("###################################");
        ZParams zParams = new ZParams ();
        zParams.aggregate (ZParams.Aggregate.MIN);
// zParams.weightsByDouble (1d);
        System.out.println (jedis.zrange (KEY + 0, 0, -1));
        jedis.zinterstore (KEY, zParams, KEY, KEY + 0);
        System.out.println ("###################################");
        System.out.println (jedis.zrange (KEY, 0, -1));
    }

    / **
     * ZRANGEBYLEX key min max [LIMIT offset count]
     * When all members of an ordered set have the same score, the elements of the ordered set are sorted according to the lexicographical ordering of the members,
     * This command returns the members of the given ordered collection key key with values between min and max.
     * If members in an ordered set have different scores, the result returned by the command is unspecified.
     The * command uses the C language memcmp () function to perform a byte-by-byte compare on each member in the collection, and returns the sorted collection members in descending order.
     * If two strings have the same content, the command will consider that the longer string is larger than the shorter string.
     * The optional LIMIT offset count parameter is used to get matching elements in the specified range (like the SELECT LIMIT offset count statement in SQL). One thing to note is that
     * If the value of the offset parameter is very large, the command needs to traverse to the position specified by offset before returning the result. This operation will add up to O (N) complexity to the command.
     * How to specify the range interval
     * The legal min and max parameters must contain (or [, where (indicates the open interval (the specified value will not be included in the range), and [indicates the closed interval (the specified value will be included in the range) .
     * The special values + and-have special meaning in the min and max parameters, where + means positive infinity and-means negative infinity. So, send a command to an ordered set with the same score for all members
     * ZRANGEBYLEX <zset>-+, the command will return all elements in the ordered set.
     * /
    @Test
    public void ZRANGEBYLEX () {
        / **
         *
         redis> ZADD myzset 0 a 0 b 0 c 0 d 0 e 0 f 0 g
         (integer) 7
         redis> ZRANGEBYLEX myzset-[c
         1) "a"
         2) "b"
         3) "c"

         redis> ZRANGEBYLEX myzset-(c
         1) "a"
         2) "b"

         redis> ZRANGEBYLEX
myzset [aaa (g
         1) "b"
         2) "c"
         3) "d"
         4) "e"
         5) "f"
         * /
        ZRANGE ();
        System.out.println (jedis.zrangeByLex (KEY, "-", "+"));
        System.out.println (jedis.zrangeByLex (KEY, "-", "+", 1, 2));
    }

    / **
     * ZLEXCOUNT key min max
     * For an ordered set key with the same score for all members, this command returns the number of elements in the set with members between min and max.
     * The min and max parameters of this command have the same meaning as the min and max parameters of the ZRANGEBYLEX command.
     * /
    @Test
    public void ZLEXCOUNT () {
        System.out.println (jedis.zlexcount (KEY, "-", "+"));
    }

    / **
     * ZREMRANGEBYLEX key min max
     * For an ordered collection key key with the same scores for all members, this command removes all elements from the collection with members between min and max.
     * The min and max parameters of this command have the same meaning as the min and max parameters of the ZRANGEBYLEX command.
     * /
    @Test
    public void ZREMRANGEBYLEX () {
        ZRANGE ();
        jedis.zremrangeByLex (KEY, "-", "+");
        System.out.println ("####################");
        ZRANGE ();
    }

    private int getRandomInt () {
        return new Random (). nextInt (100);
    }

    private void ZADDForKey (String key) {
        if (StringUtils.isEmpty (key)) {
            key = KEY;
        }
        Map <String, Double> sourceMember = new HashMap <String, Double> ();
        for (int i = 0; i <3; i ++) {
            double score = getRandomInt ();
            sourceMember.put (VALUE + score, score);
        }
        jedis.zadd (key, sourceMember);
    }
}


Jedis Operation Redis--sortedset Type


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.