How Zset operates Redis--Based on Jedis, Java Edition

1. Zset concept

Zset ordered set (sorted set):
1. An ordered set is also a collection of string type elements like a set, and duplicate members are not allowed, that is, the elements are unique!
2. Each element is associated with a double type score (score), and redis uses these scores (score) to sort the elements in the collection.
3. The elements of an ordered set are unique, but the score (score) can be repeated.
4. The maximum number of elements in a collection is 2^32 - 1 (4294967295, each collection can store more than 4 billion elements).

2. Zset syntax

1. Zadd key score1 member1 [score2 member2] # 向有序集合添加一个或多个成员,或者更新已存在成员的分数
2. Zrange key start stop [withscores] # 通过索引区间内返回有序集合指定区间内的成员

  • start and stop represent the subscript of index respectively.
  • The withscores result brings the score value.

3. Zcard key # 获取有序集合的成员数
4. Zrem key member[member…] #移除有序集合中的一个或多个成员
5. Zcount key min max # 计算在有序集合中指定分数区间的成员数
6. Zincrby key increment member # 有序集合中指定成员的分数加上增量 increment
7. Zrangebylex key min max [LIMIT offset count] #通过字典区间返回有序集合的成员
8. Zrank key member # 返回有序集中指定成员的排名。** 其中有序集成员按分数值递增(从小到大)顺序排列。
9. Zrevrank key member [withscores] # 返回有序集中指定成员的排名。其中有序集成员按分数值递减(从大到小)排序。 效果和Zrevrangebyscore一样
10. Zrangebyscore key min max [withscores] # 通过分数按照递增(从小到大)次序排列返回有序集合指定区间内的成员

  • min max represents the value of score, and Zrange represents the subscript
  • min max can be used with closed intervals [less than or equal to or greater than or equal to] and open intervals (less than or greater than)

11. Zrevrangebyscore key max min [withscores] # 返回有序集中指定分数区间内的成员,分数从高到低排序

3. Example of Zset in Jedis

Select some parts here for demonstration, and other commands can be operated by viewing the source code!


public class TestZset {
    
    
	public static void main(String[] args) {
    
    
		// 创建jedis对象
		Jedis jedis = new Jedis("localhost",6379);  // 如果你是用服务器,localhost改为服务器ip即可
		jedis.auth("12345688"); // 如果redis设置了密码验证,反之,则不需要该代码

		HashMap<String, Double> scoreMap = new HashMap<String, Double>();
		scoreMap.put("xiaoming",70.0);
		scoreMap.put("xiaowang",100.0);
		scoreMap.put("xiaohong",88.0);
		scoreMap.put("xiaoli",60.0);
		scoreMap.put("zhangsan",58.0);
		jedis.zadd("math", scoreMap);
		// 查看scoreMap的形式
		System.out.println("查看scoreMap的形式:"+scoreMap.toString());
		// 0 第0个元素,-1最后一个元素
		System.out.println("返回math全部元素:"+jedis.zrange("math", 0, -1));
		System.out.println("查看key有多少个元素:"+jedis.zcard("math"));
		// 移除 xiaoli 这个元素
		System.out.println("移除xiaoli 这个元素");
		jedis.zrem("math", "xiaoli");
		// -inf 负无穷  inf 正无穷,即从小到大排序
		System.out.println("按照递增顺序,返回math全部的元素(含成绩):"+jedis.zrangeByScoreWithScores("math", "-inf", "inf"));
		System.out.println("统计math集合,成绩在[80,100]之间的元素个数:"+jedis.zcount("math", 80,100 ));
	}
}

Result demo:insert image description here

Guess you like

Origin blog.csdn.net/qq_44231797/article/details/123644135