Redis Paging Sort Query

Source: Internet
Author: User
Tags mysql query redis

Redis is an efficient memory database that supports storage of data types including string, List, Set, SortedSet, and hash, and in Redis usually queries its value based on the key of the data, Redis no conditional query, Redis is not very good at dealing with scenes that require paging or sorting, such as comments, timelines.

Some time ago in the project, you need to assemble the comments of users under each topic into the Redis, each subject will have a topicid, each comment will be associated with the topicid, get the approximate data model as follows:

1
2
3
4
5
6 7 8 9 (16)
19
{
    topicid: ' xxxxxxxx ',
    comments: [
        {
            username: ' Niuniu ',
            createdate:1447747334791,
            Content: ' Pagination in Redis ',
            commentid: ' xxxxxxx ',
            reply: [
                {
                    content: ' yyyyyy '
                    username: ' Niuniu '
                },
                ...]}
        ,
        ...
    ]
}

The comment data from the MySQL query assembled to save to Redis, after each can get assembled from the Redis comments data, from the above data model can be seen is key-value data, no doubt to use hash for storage, But every time you pick up the comment data needs pagination and also by the CreateDate field to sort, hash must not be able to do pagination and sorting.

So, take a look at the data types supported by Redis:

1, string: Mainly used for storing strings, obviously does not support paging and sorting.
2, hash: Mainly used to store key-value data, the comment model is full of key-value data, so hash will undoubtedly be used here.
3, List: Mainly used to store a list, each element of the listing in the order of the insertion of the elements to save, if we will comment on the model createdate row after the sequence and then insert the list, it seems to be able to sort, and then use the list of Lrange key start The Stop command can also be paged. Well, up here. The list seems to meet our paging and sorting requirements, but comments will also be deleted, you need to update the data in the Redis, if you delete the comments after each redis all the data to write again, obviously not elegant, efficiency will be greatly reduced, if you can delete the specified data will undoubtedly be better , and the list involves the deletion of data only Lpop and rpop these two instructions, but Lpop and Rpop can only delete the list header and the end of the list of data, can not delete the specified location of the data, so the list is not very suitable (reprinted when looked at, there is a lrem command can do to delete, But Lrange seems to be a time-consuming command O (N)).
4, set: Main storage unordered set, unordered. Exclude.
5, SortedSet: The main storage ordered set, SortedSet add element Directive zadd key score member [[Score,member] ...] Each added element member is bound to a value that is used for sorting score,sortedset will sort the elements based on the size of the score value, where createdate can be used as score for sorting, SortedSet in the instruction Zrevrange key start stop can return to the specified range of members, can be used to do paging, sortedset instructions zrem key member can be removed according to the key designated members, to meet the requirements of the deletion of comments, so, SortedSet is most suitable here (time complexity O (log (N))).

So, the data types I need to use are sortset and hash,sortset for paging, and hash is used to store specific key-value pairs of data, and I've drawn the following chart:

In the sortset structure of the diagram above, the topicid of each topic is used as the key of the set, and the CreateDate and Commentid of the comments associated with the subject are respectively the score and member of the set. The order of the Commentid is arranged according to the size of the createdate.
When you need to query for comments on a particular page of a topic, you can topicid the topic through instructions zrevrange topicid (page-1) x10 (page-1) x10+ Perpage this way you can find out the commintid of all the comments in chronological order for a particular page of a topic. Page is the number of pages that are queried on the first page, and the perpage that are displayed for each page.
When you find all the comments Commentid, you can use these commentid as key to hash structure to query the corresponding content of the comment.
This makes use of sortset and hash two structure in redis to achieve the purpose of paging and sorting.


Bloggers Add additional implementation algorithms:

@Test public
	void Sortedsetpagenation () {
		for  (int  i =  1; I <=  i+=10) {  
			//Initialize Comme Ntid index Sortset
			redisclient.zadd ("TopicID", I, "Commentid" +i);
			Initializes the Comment data Hash
			redisclient.hset ("Comment_key", "Commentid" +i, "Comment content ...");  
		In reverse, take 5 Id data starting from 0
		linkedhashset<string> sets = Redisclient.zrevrangebyscore ("TopicID", "", "1", 0, 5); 
  string[] items = new string[]{};
		System.out.println (Sets.tostring ());
		Comment data based on ID
		list<string> List = Redisclient.hmget ("Comment_key", Sets.toarray (items));
		for (String str:list) {
			System.out.println (str);
		}
	}
Tool class:
Package com.util;
Import Java.util.LinkedHashSet;

Import java.util.List;
Import Redis.clients.jedis.Jedis;
Import Redis.clients.jedis.JedisPool;

Import Redis.clients.jedis.JedisPoolConfig; /** * REDIS Client cluster * * @author Babylon * 2016-5-10/public class redisclient{private static Jedispool Jedispoo
	
	L
        static {jedispoolconfig config = new Jedispoolconfig ();   
        Config.setmaxtotal (global.max_active);
        Config.setmaxidle (Global.max_idle);
        Config.setmaxwaitmillis (-1);
        Config.settestonborrow (Global.test_on_borrow);
        Config.settestonreturn (Global.test_on_return); Jedispool = new Jedispool ("redis://:" +global.redis_server_password+ "@" +global.redis_server_url+ ":" +Global.REDIS_
Server_port); Jedispool = new Jedispool (config, Global.redis_server_url, Integer.parseint (Global.redis_server_port), "Zjp_Redis_
	224 ");
		public static string set (string key, String value) {Jedis Jedis = Jedispool.getresource (); String Result = JEDis.set (key, value);
		Jedis.close ();
	return result;
		public static string get (String key) {Jedis Jedis = Jedispool.getresource ();
		String result = Jedis.get (key);
		Jedis.close ();
	return result;
		public static Long Hset (string key, string item, String value) {Jedis Jedis = Jedispool.getresource ();
		Long result = Jedis.hset (key, item, value);
		Jedis.close ();
	return result;
		public static string Hget (string key, string item) {Jedis Jedis = Jedispool.getresource ();
		String result = Jedis.hget (key, item);
		Jedis.close ();
	return result;
		The/** * Redis hmget command returns the value of one or more given fields in the hash table.
	 Returns a nil value if the specified field does not exist in the hash table.
	 * @param key * @param item * @return A table that contains multiple values for a given field, and the order of the table values is the same as the request order of the specified fields.
		*/public static list<string> Hmget (string key, String ... item) {Jedis Jedis = Jedispool.getresource ();
		list<string> result = Jedis.hmget (key, item);
		Jedis.close ();
	return result; public static Long incr (String key) {Jedis Jedis = Jedispool.getresource ();
		Long result = JEDIS.INCR (key);
		Jedis.close ();
	return result;
		public static Long DECR (String key) {Jedis Jedis = Jedispool.getresource ();
		Long result = JEDIS.DECR (key);
		Jedis.close ();
	return result;
		public static Long expire (String key, int second) {Jedis Jedis = Jedispool.getresource ();
		Long result = Jedis.expire (key, second);
		Jedis.close ();
	return result;
		public static Long TTL (String key) {Jedis Jedis = Jedispool.getresource ();
		Long result = Jedis.ttl (key);
		Jedis.close ();
	return result;
		public static Long Hdel (string key, string item) {Jedis Jedis = Jedispool.getresource ();
		Long result = Jedis.hdel (key, item);
		Jedis.close ();
	return result;
		public static Long del (String key) {Jedis Jedis = Jedispool.getresource ();
		Long result = Jedis.del (key);
		Jedis.close ();
	return result;
		public static Long Rpush (string key, String ... strings) {Jedis Jedis = Jedispool.getresource (); Longresult = Jedis.rpush (key, strings);
		Jedis.close ();
	return result; /** * Redis Lrange returns the elements within the specified interval in the list, specified by the offset START and end. 
	 where 0 represents the first element of the list, 1 represents the second element of the list, and so on.
	 * You can also use a negative subscript to 1 to represent the last element of the list,-2 for the penultimate element of the list, and so on. * @param String * @param start * @param end * @return/public static list<string> Lrange (string key, int
		Start, int end) {Jedis Jedis = Jedispool.getresource ();
		list<string> result = Jedis.lrange (key, start, end);
		Jedis.close ();
	return result; /** * Removes the count-matching value from the head from the list. If Count is zero, all matching elements are deleted.
	 If count is a negative number, the content is deleted from the tail. * @param String * @param string2 * @param I/public static Long Lrem (string key, Long count, String value) {Je
		Dis Jedis = Jedispool.getresource ();
		Long result = Jedis.lrem (key, count, value);
		Jedis.close ();
	return result;
		The/** * Redis zadd command is used to add one or more member elements and their values to an ordered set.
		If a member is already a member of an ordered set, then the fractional value of the member is updated and the member element is reinserted to ensure that it is in the correct position.
		Fractional values can be integer values or double-precision floating-point numbers.
		If the ordered set key does not exist, an empty ordered set is created and the Zadd operation is performed. When When key exists but is not an ordered set type, an error is returned.
	 * @param String * @param i * @param string2 * @return The number of new members that have been successfully added, excluding those that have already been updated.
		*/public static Long Zadd (string key, double score, String member) {Jedis Jedis = Jedispool.getresource ();
		Long result = Jedis.zadd (key, score, member);
		Jedis.close ();
	return result; /** * Redis Zrevrangebyscore returns all members in the specified fractional interval in an ordered set.
		Ordered set members are arranged in descending order of fractional values (from large to small).
		Members with the same fractional value are arranged in the order of the dictionary sequence (reverse lexicographical order).
	 Other aspects of the Zrevrangebyscore command are the same as the Zrangebyscore command, except that the members arrange this in descending order of fractional values.
	 * @param key * @param max * @param min * @param offset * @param count * @return A list of ordered set members with fractional values (optional) within the specified interval. 
		*/public static linkedhashset<string> Zrevrangebyscore (string key, String max, string min, int offset, int count) {
		Jedis Jedis = Jedispool.getresource (); linkedhashset<string> result = (linkedhashset<string>) jedis.zrevrangebyscore (Key, Max, Min, offset, count
		);
		Jedis.close ();
	return result; }

}



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.