The Little Redis Book Chinese version chapter II-Data structure

Source: Internet
Author: User
Tags data structures hash redis strlen value store

Now that we're going to explore the 5 data structures of Redis, we'll explain what each data structure is, what effective methods it contains, and what types of features and data you can handle with these data structures.

So far, the redis composition We know includes only commands, keywords, and values, and has not yet touched on the specific concepts of data structures. When we use the SET command, how does Redis know which data structure we are using? The workaround is that each command corresponds to a specific data structure. For example, when you use the SET command, you are storing the value in a string data structure. And when you use the Hset command, you store the value in a hash data structure. This mechanism is fairly manageable, given the small set of key words for Redis.

The Redis site has excellent reference documentation, and there is no reason to reinvent the wheel. But in order to figure out what these data structures do, we will overwrite important commands that must be known.

Nothing is more important than to play with pleasure and to experiment with interesting things. At any time, you can erase all the values in your database by typing the FLUSHDB command, so don't be shy and try to do something crazy. string (Strings)

In Redis, strings are the most basic data structures. When you're thinking about keyword-value pairs, you're thinking about string data structures. Don't get confused by the name, as you said before, your value can be anything. I prefer to call them "scalars" (scalars), but maybe only I think so.

We have seen a common string use case where an instance of an object is stored by means of a keyword. Sometimes you will use this kind of operation frequently:

Set Users:leto "{Name:leto, Planet:dune, likes: [Spice]}"

In addition to these, Redis also has some common operations. For example, strlen can be used to get the length of a keyword's corresponding value; GetRange will return the corresponding value of the keyword in the specified range; append will append value to the existing keyword value (if the keyword does not exist, a new keyword-value pair will be created). Don't hesitate to try these commands. Here's what I got:

> strlen users:leto
(integer)

> GetRange users:leto
"likes: [Spice]"

> Append users: Leto "Over 9000!!"
(integer) 54

Now you might think, that's fine, but it doesn't seem to make any sense. You cannot effectively extract a range of JSON files, or attach some values to them. You're right, the experience here is that some commands, especially about string data structures, are meaningful only given the explicit data type.

As we know before, Redis doesn't pay attention to what your value is. Normally, this is not wrong. However, some string commands are designed specifically for the structure of some type or value. As a somewhat ambiguous use case, we can see that the Append and GetRange commands are useful for some custom, spatially efficient (space-efficient) serialization objects. For a more specific use case, we can look at the incr, Incrby, DECR, and Decrby commands. These commands increase or decrease the value of a string data structure:

> incr stats:page:about
(integer) 1
> Incr stats:page:about
(integer) 2

> Incrby ratings: video:12333 5
(integer) 5
> Incrby ratings:video:12333 3
(integer) 8

As you can imagine, Redis's string data structures are good for analytical purposes. You can also try to grow Users:leto (a value that is not an integer) and see what happens (you should get an error).

The more advanced use cases are the setbit and Getbit commands. "How many independent user visits we have today" is a common problem in Web applications, and there is a wonderful post where you can see how spool uses these two commands to solve this problem effectively. For 128 million users, a laptop computer responds in less than 50 milliseconds and uses only 16MB of storage space.

The most important thing is not whether you understand how bitmaps work, or how spool use these commands, but rather understand that Redis's string data structures are much more useful than you thought Bitmaps. However, the most common application cases are given above: storage objects (simple or complex) and counting. At the same time, because the keyword to get a value is so fast, the string data structure is often used to cache data. Hash (hashes)

We already know that Redis is known as a keyword-value store is less accurate, and the hashing data structure is a good example. As you can see, in many ways, the hash data structure is much like a string structure. The significant difference between the two is that the hash data structure provides an additional layer of indirection: a Domain (field). Therefore, the set and get in the hash data structure are:

Hset Users:goku powerlevel 9000
hget Users:goku powerlevel

Related actions also include setting up multiple domains at the same time, getting multiple domains at the same time, getting all the fields and values, listing all domains, or deleting a specified domain:

Hmset Users:goku Race Saiyan Age 737
hmget Users:goku race powerlevel
hgetall users:goku
hkeys users:goku
  hdel Users:goku Age

As you can see, the hash data structure has more operability than the normal string structure. We can use a hash data structure to get a more precise description of what is stored as a user rather than a serialized object. The benefit is the ability to extract, update, and delete specific pieces of data without having to fetch or write the entire value.

For a hashed data structure, it can be considered from the perspective of a well-defined object, such as a user, and the key is to understand how they work. For performance reasons, this is true, and more granular control can be quite useful. In the next chapter, we'll see how to organize your data in a hashed data structure to make the query more effective. In my opinion, this is the place where the hash is really dazzling. list (Lists)

For a given keyword, the list data structure allows you to store and manipulate a set of values. You can add a value to the table, get the first or last value of the list, and process the value with the given index. The list data structure maintains the order of values and provides efficient index-based operations. To keep track of the latest users registered on the site, we can maintain a list of newusers:

Lpush newusers Goku
ltrim newusers 0 50

The specific composition of the LTrim command is LTrim Key start stop. To understand the LTrim command, first understand that the value stored by the key is a list, in theory the list can hold any number of values. For the specified list, the start and Stop,ltrim commands, based on the two range parameters provided, remove the values outside the specified range, leaving only the values in the range. )

First, we push a new user into the front end of the list, and then adjust the list to include only 50 users who were recently pushed. This is a common pattern. LTrim is an operation with an O (n) time complexity, and N is the number of values to be deleted. From the above example, we always make a list adjustment after inserting a user, in fact, it will have a constant performance of O (1) time complexity (because n will always be equal to 1).

This is the first time we see another value for the corresponding value index of a keyword. If we want to get the details of the last 10 users, we can run the following combo operation:

Keys = Redis.lrange (' newusers ', 0, ten)
Redis.mget (*keys.map {|u| "Users:#{u}"})

We've talked about multiple round-trip data patterns before, and the two lines of ruby code above give us a good demonstration.

Of course, the ability to store and index keywords is not the only way to list data structures. The value can be anything, you can use the list data structure to store the log, or you can track the path when the user browses the site. If you've ever built a game in the past, you might use a list data structure to track the user's queued activity. collection (sets)

Collection data structures are often used to store only unique values and provide many collection-based operations, such as a set. The collection data structure does not sort the values, but it provides efficient value-based operations. A typical use case for using a collection data structure is the implementation of a friend list:

Sadd Friends:leto Ghanima Paul Chani Jessica Sadd
Friends:duncan Paul Jessica Alia

Regardless of how many friends a user has, we can effectively (O (1) Time complexity) identify the user X is a friend of user y:

Sismember friends:leto Jessica
sismember friends:leto Vladimir

Also, we can look at two or more people who are not having a common friend:

Sinter Friends:leto Friends:duncan

You can even store the results in a new keyword:

Sinterstore Friends:leto_duncan Friends:leto Friends:duncan

Sometimes it is necessary to mark and trace the properties of a value, but not through a simple copy operation, the collection data structure is one of the best ways to solve such problems. Of course, the collection data structure is the best choice for those places where collection operations need to be applied, such as intersection and set. Category Collection (Sorted sets)

The last and most powerful data structure is the categorical collection data structure. If the hash data structure is similar to string data structures, the main distinction is the concept of domain (field), then the categorical collection data structures are similar to the collection data structures, the main distinction is the concept of markup (score). tags provide the ability to sort (sorting) and Rank Division (ranking). If we want a rank-categorized list of friends, you can do this:

Zadd Friends:duncan Ghanima Paul Chani Jessica 1 Vladimir

For Duncan's friends, how to figure out the number of people with a mark (score) of 90 or higher.

Zcount Friends:duncan 90 100

How to get Chani rank (rank) in the list.

Zrevrank Friends:duncan Chani

The specific composition of the Zrank command is Zrank key Menber, knowing that the sorted set stored by the key is sorted by score in ascending order of Menber, which is used to obtain menber in that permutation, which is called rank. )

We used the Zrevrank command instead of the Zrank command because the default sort of Redis was from low to high, but in this case our rank division was from high to low. The most common use case for categorical collection data structures is to implement a leaderboard system. In fact, for some things that are based on integer ordering and can be effectively manipulated with tags (score), it should be a good choice to use a categorical collection of data structures to handle them. Summary

We have a high-level overview of the 5 types of REDIS data structures. One interesting thing is that you can often use Redis to create something more effective relative to the idea of the initial build. For the use of string data structures and categorical collection data structures, there is a good chance that there are some building methods that no one has yet thought of. When you understand the common application cases, you will find that Redis is an ideal choice for many types of problems. Also, don't assume that you have to use all of your stuff because Redis shows you 5 of data structures and the corresponding methods. It is common to use only a few commands to build a feature.

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.