Introduction to Redis Basics (ii)-hash (hash), set (set), sorted set (ordered set), and key operation

Source: Internet
Author: User
Tags character set hash prepare redis
hashing type (hash) related Operations


We can consider the hashes type in Redis as a map container with string key and string value. Therefore, this type is ideal for storing information about value objects.
such as username, password, and age. If a hash contains very few fields, the data of that type will take up only a small amount of disk space. Each hash can be
To store 4,294,967,295 key-value pairs.



Hset/hget/hdel/hexists/hlen/hsetnx


#Set the key to myhash field to field1 and the value to stephen.
redis 127.0.0.1:6379> hset myhash field1 "stephen"
(integer) 1

#Get the key value of myhash and the value of field1.
redis 127.0.0.1:6379> hget myhash field1
"stephen"

The field2 field does not exist in the #myhash key, so nil is returned.
redis 127.0.0.1:6379> hget myhash field2
(nil)

#Add a new field field2 to the hashes value associated with myhash, with the value liu.
redis 127.0.0.1:6379> hset myhash field2 "liu"
(integer) 1

#Get the number of fields for myhash key.
redis 127.0.0.1:6379> hlen myhash
(integer) 2

# Determine if there is a field named field1 in the myhash key. Due to the existence, the return value is 1.
redis 127.0.0.1:6379> hexists myhash field1
(integer) 1

#Delete the field named field1 in the myhash key and return 1 if the deletion is successful.
redis 127.0.0.1:6379> hdel myhash field1
(integer) 1

#Delete the field named field1 in the myhash key again, because the previous command has deleted it, because it was not deleted, it returns 0.
redis 127.0.0.1:6379> hdel myhash field1
(integer) 0

#Determine if the field1 field exists in the myhash key, because the previous command has deleted it, because it returns 0.
redis 127.0.0.1:6379> hexists myhash field1
(integer) 0

#Add a new field field1 to myhash through the hsetnx command. The value is stephen. Because the field has been deleted, the command is successfully added and returns 1.
redis 127.0.0.1:6379> hsetnx myhash field1 stephen
(integer) 1

#Since the field1 field of myhash has been added successfully by the previous command, this command returns 0 after doing nothing.
redis 127.0.0.1:6379> hsetnx myhash field1 stephen
(integer) 0


Hgetall/hkeys/hvals/hmget/hmset


#Delete this key for later example testing.
redis 127.0.0.1:6379> del myhash
(integer) 1

#For this key myhash, set multiple fields at once, field1 = "hello", field2 = "world".
redis 127.0.0.1:6379> hmset myhash field1 "hello" field2 "world"
OK

#Get multiple fields of myhash key, where field3 does not exist, because the value corresponding to this field in the returned result is nil.
redis 127.0.0.1:6379> hmget myhash field1 field2 field3
1) "hello"
2) "world"
3) (nil)

#Return all fields of myhash key and their values. As can be seen from the results, they are listed pair by pair.
redis 127.0.0.1:6379> hgetall myhash
1) "field1"
2) "hello"
3) "field2"
4) "world"

#Get only the names of all fields in the myhash key.
redis 127.0.0.1:6379> hkeys myhash
1) "field1"
2) "field2"

#Get only the values of all fields in the myhash key.
redis 127.0.0.1:6379> hvals myhash
1) "hello"
2) "world"


Hincrby


#Remove this key for easy testing in the examples below.
redis 127.0.0.1:6379> del myhash
(integer) 1

#Prepare test data. The field field of myhash is set to 1.
redis 127.0.0.1:6379> hset myhash field 5
(integer) 1

#Add 1 to the value of the field field of myhash, and return the added result.
redis 127.0.0.1:6379> hincrby myhash field 1
(integer) 6

#Add -1 to the field value of myhash, and return the result.
redis 127.0.0.1:6379> hincrby myhash field -1
(integer) 5

#Add -10 to the field value of myhash, and return the added result.
redis 127.0.0.1:6379> hincrby myhash field -10
(integer) -5



collection type (set) related operations



In Redis, we can see the set type as an unordered character set, and as with the list type, we can also perform operations such as adding, deleting, or judging whether an element exists on the data value of that type. It should be stated that the time complexity of these operations is O (1), which is the completion of the operation within a constant time. The maximum number of elements the set can contain is 2^32-1 (4294967295).



Unlike the list type, duplicate elements are not allowed in the set collection, which is identical to the set container in the C + + standard library. In other words, if you add the same element more than once, only one copy of the element will be preserved in set. Compared to the list type, the set type has a very important feature, that is, to complete the aggregation calculation operation between multiple sets on the server side.
such as unions, intersections and differences. Because these operations are done on the server side, they are highly efficient and also save a lot of network IO overhead.



Scope of application: You can use Redis's set data type to track some unique data, such as unique IP address information for accessing a blog. For this scenario, we only need to
Visit this blog when the IP of the visitor is credited to Redis, and the set data type automatically guarantees the uniqueness of the IP address. Make full use of the set type of service-side aggregation operation convenient and efficient features, can be used to maintain the relationship between data objects. For example, all purchases of an electronic
The customer ID of the device is stored in a specified set, and the customer ID of the purchase of another electronic product is stored in another set, and if we want to
To get the customers who have purchased both of these goods, the intersections command of set can give full play to its convenience and efficiency advantage.



Sadd/smembers/scard/sismember


#Insert test data, since the key myset does not exist before, the three members in the parameter are inserted normally.
Redis 127.0.0.1:6379> Sadd myset a b c
(integer) 3

#Since the a in the parameter already exists in myset, so this operation only inserts the new members of D and E two.
Redis 127.0.0.1:6379> Sadd myset a D e
(integer) 2

#Judge whether a already exists, a return value of 1 indicates existence.
Redis 127.0.0.1:6379> sismember myset a
(integer) 1

#Judge whether f already exists, a return value of 0 means that it does not exist.
Redis 127.0.0.1:6379> sismember myset F
(integer) 0

#View the result of the insertion through the members command, from the result, the order of the output is independent of the insertion order.
redis 127.0.0.1:6379> smembers myset
1) "C"
2) "D"
3) "a"
4) "B"
5) "E"

# Gets the number of elements in the set collection.
redis 127.0.0.1:6379> SCard myset
(integer) 5


Spop/srem/srandmember/smove


#Remove this key to facilitate subsequent testing.
redis 127.0.0.1:6379> del myset
(integer) 1

# Prepare test data for the following examples.
Redis 127.0.0.1:6379> Sadd MySet a b c D
(integer) 4

#View the position of members in Set.
redis 127.0.0.1:6379> smembers myset
1) "C"
2) "D"
3) "a"
4) "B"

#As can be seen from the results, The command does return a member at random.
redis 127.0.0.1:6379> srandmember myset
"C"

The member b at the end of #Set is removed and returned, in fact B is not the first or last member inserted before.
redis 127.0.0.1:6379> spop myset
"B"

#View the member information of the Set after the removal.
redis 127.0.0.1:6379> smembers myset
1) "C"
2) "D"
3) "A"

# Moved from Set a, D and F three members, where F does not exist, Therefore only A and D two members are moved out and returned as 2.
Redis 127.0.0.1:6379> Srem MySet a D f
(integer) 2

#View the output after removal.
redis 127.0.0.1:6379> smembers myset
1) "C"


Sdiff/sdiffstore/sinter/sinterstore/sunion/sunionstore


#Prepare data for the following move command.
redis 127.0.0.1:6379> sadd myset a b
(integer) 2
redis 127.0.0.1:6379> sadd myset2 c d
(integer) 2

#Move a from myset to myset2, and you can see that the move was successful.
redis 127.0.0.1:6379> smove myset myset2 a
(integer) 1

#Move a from myset to myset2 again, because a is no longer a member of myset at this time, the move fails and returns 0.
redis 127.0.0.1:6379> smove myset myset2 a
(integer) 0

#Check the members of myset and myset2 respectively to confirm whether the move is really successful.
redis 127.0.0.1:6379> smembers myset
1) "b"
redis 127.0.0.1:6379> smembers myset2
1) "c"
2) "d"
3) "a"


# Prepare test data for subsequent commands.
redis 127.0.0.1:6379> sadd myset a b c d
(integer) 4
redis 127.0.0.1:6379> sadd myset2 c
(integer) 1
redis 127.0.0.1:6379> sadd myset3 a c e
(integer) 3

Compared to #myset and myset2, the three members a, b, and d are the difference members between the two. Then use this result to continue the comparison with myset3. B and d are non-existent members of myset3.
redis 127.0.0.1:6379> sdiff myset myset2 myset3
1) "d"
2) "b"

#Store the difference members of the 3 collections in the Set associated with the diffkey, and return the number of inserted members.
redis 127.0.0.1:6379> sdiffstore diffkey myset myset2 myset3
(integer) 2

#View the operation results of sdiffstore.
redis 127.0.0.1:6379> smembers diffkey
1) "d"
2) "b"

#From the data prepared earlier, it can be seen that the member intersection of these three Sets is only c.
redis 127.0.0.1:6379> sinter myset myset2 myset3
1) "c"

#Store the intersection members in the 3 sets into the Set associated with the interkey, and return the number of intersection members.
redis 127.0.0.1:6379> sinterstore interkey myset myset2 myset3
(integer) 1

#View the operation results of sinterstore.
redis 127.0.0.1:6379> smembers interkey
1) "c"

#Get the union of the members in the 3 sets.
redis 127.0.0.1:6379> sunion myset myset2 myset3
1) "b"
2) "c"
3) "d"
4) "e"
5) "a"

#Store the union of the members in the three collections into the set associated with the unionkey, and return the number of union members.
redis 127.0.0.1:6379> sunionstore unionkey myset myset2 myset3
(integer) 5

#View the operation results of suiionstore.
redis 127.0.0.1:6379> smembers unionkey
1) "b"
2) "c"
3) "d"
4) "e"
5) "a"



ordered collection type (sorted set) related operations



Sorted-sets and sets types are very similar, both are collections of strings and do not allow duplicate members to appear in a set. The main difference between them is sorted-sets
Each member of the score is associated with a fraction, which is the small-to-large ordering of the members in the collection by the score. However, it is necessary to point out that
Although members in Sorted-sets must be unique, fractions (score) can be duplicated.



Adding, deleting, or updating a member in Sorted-set is a very fast operation with a time complexity of a logarithm of the number of members in the collection. Since the members in the Sorted-sets
The positions in the collection are orderly, so even accessing the members in the middle of the collection is still very efficient. In fact, Redis has this feature in many other types of
Database is difficult to achieve, in other words, it is very difficult to model in other databases in order to achieve the same efficiency as Redis.



Application scope: Can be used for a large online game of the points leaderboard. Each time a player's score changes, the Zadd command can be executed to update the player's score, and then the Zrange command gets the top ten user information. Of course we can also use the Zrank command to get the player's ranking information through username. Finally, we will combine the Zrange and Zrank commands to quickly get information about other users with a similar player score. The Sorted-sets type can also be used to build index data.



Zadd/zcard/zcount/zrem/zincrby/zscore/zrange/zrank:


#Add a member with a score of 1.
redis 127.0.0.1:6379> zadd myzset 1 "one"
(integer) 1

#Add two members whose scores are 2 and 3.
redis 127.0.0.1:6379> zadd myzset 2 "two" 3 "three"
(integer) 2

# 0 indicates the first member, and -1 indicates the last member. The WITHSCORES option indicates that each member and its score are included in the returned result, otherwise only members are returned.
redis 127.0.0.1:6379> zrange myzset 0 -1 WITHSCORES
1) "one"
twenty one"
3) "two"
4) "2"
5) "three"
6) "3"

#Get the position index of member one in Sorted-Set. 0 means the first position.
redis 127.0.0.1:6379> zrank myzset one
(integer) 0

#Memberfour does not exist, so nil is returned.
redis 127.0.0.1:6379> zrank myzset four
(nil)

#Get the number of members in the myzset key.
redis 127.0.0.1:6379> zcard myzset
(integer) 3

#Returns the number of members in the Sorted-Set associated with myzset whose scores satisfy the expression 1 <= score <= 2.
redis 127.0.0.1:6379> zcount myzset 1 2
(integer) 2

#Delete members one and two, return the number of members actually deleted.
redis 127.0.0.1:6379> zrem myzset one two
(integer) 2

#Check if the deletion was successful.
redis 127.0.0.1:6379> zcard myzset
(integer) 1

#Get members three scores. The return value is a string.
redis 127.0.0.1:6379> zscore myzset three
"3"

#Since member two has been deleted, this command returns nil.
redis 127.0.0.1:6379> zscore myzset two
(nil)

#Increase the member one's score by 2 and return the updated score of the member (created without the member).
redis 127.0.0.1:6379> zincrby myzset 2 one
"3"

#Increase the member's score by -1 and return the updated score of the member.
redis 127.0.0.1:6379> zincrby myzset -1 one
"2"

#Check if the member's score has been updated correctly.
redis 127.0.0.1:6379> zrange myzset 0 -1 WITHSCORES
1) "one"
twenty two"
3) "two"
4) "2"
5) "three"
6) "3"


Zrangebyscore/zremrangebyrank/zremrangebyscore


redis 127.0.0.1:6379> del myzset
(integer) 1
redis 127.0.0.1:6379> zadd myzset 1 one 2 two 3 three 4 four
(integer) 4

#Get members whose score satisfies the expression 1 <= score <= 2.
redis 127.0.0.1:6379> zrangebyscore myzset 1 2
1) "one"
2) "two"

#Get members whose score satisfies the expression 1 <score <= 2.
redis 127.0.0.1:6379> zrangebyscore myzset (1 2
1) "two"

# -inf indicates the first member, + inf indicates the last member, and the parameter after limit is used to limit the members of the returned members.
# 2 means start with the member whose position index (0-based) is equal to 2, and take the next 3 members.
redis 127.0.0.1:6379> zrangebyscore myzset -inf + inf limit 2 3
1) "three"
2) "four"

#Delete members whose score satisfies expression 1 <= score <= 2 and return the number of actual deletions.
redis 127.0.0.1:6379> zremrangebyscore myzset 1 2
(integer) 2

#See if the deletion above was successful.
redis 127.0.0.1:6379> zrange myzset 0 -1
1) "three"
2) "four"

#Delete members whose position index satisfies the expression 0 <= rank <= 1.
redis 127.0.0.1:6379> zremrangebyrank myzset 0 1
(integer) 2

#Check whether the previous command was deleted successfully.
redis 127.0.0.1:6379> zcard myzset
(integer) 0


Zrevrange/zrevrangebyscore/zrevrank:


# Prepare test data for the following examples.
redis 127.0.0.1:6379> del myzset
(integer) 0
redis 127.0.0.1:6379> zadd myzset 1 one 2 two 3 three 4 four
(integer) 4

#Get and return the members in this interval with the position index from high to low.
redis 127.0.0.1:6379> zrevrange myzset 0 -1 WITHSCORES
1) "four"
twenty four"
3) "three"
4) "3"
5) "two"
6) "2"
7) "one"
8) "1"

#Since it is sorted from high to low, the position equal to 0 is four, 1 is three, and so on.
redis 127.0.0.1:6379> zrevrange myzset 1 3
1) "three"
2) "two"
3) "one"

#Since it is sorted from high to low, the position of one is 3.
redis 127.0.0.1:6379> zrevrank myzset one
(integer) 3

#Since it is sorted from high to low, the position of four is 0.
redis 127.0.0.1:6379> zrevrank myzset four
(integer) 0

#Get members whose score satisfies expression 3> = score> = 0, and output in reverse order, that is, from highest to lowest.
redis 127.0.0.1:6379> zrevrangebyscore myzset 3  
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.