Redis QuickStart-Data types

Source: Internet
Author: User
Tags delete key

Objective

Redis has recently been used for projects, so a quick start with the Redis Getting Started Guide (Li Zi), which records some of the knowledge points (mostly commands), is handy for later review.

Brief introduction

Redis is an open source Key-value storage and a perfect solution for building high-performance, scalable Web applications.

Three key features of Redis:
    • The Redis database is completely in memory and uses disk for persistence only.

    • Redis has a rich set of data types compared to many key-value data stores.

    • Redis can replicate data to any number of slave servers.

The benefits of Redis
    • Exceptionally fast: Redis is very fast and can perform about 110,000 episodes per second, about 81000 + records per second.

    • Support for rich data types: Redis supports data types such as lists, collections, ordered collections, hashing, and so on that most developers already know. This makes it very easy to solve a wide variety of problems because we know which problems can be handled better by its data type.

    • Operations are atomic: All Redis operations are atomic, which ensures that Redis servers accessed by two clients at the same time will get the updated values.

    • Multifunction utility: Redis is a versatile tool that can be used in multiple uses such as cache, message, queue (Redis native support publish/subscribe), any transient data, applications such as Web application sessions, Web page hits count etc.

Start and stop start

1. Direct start

$ redis-server

6379 ports are used by default.

An anecdote:

6379 is the phone keypad on the Merz corresponding number, Merz is an Italian showgirl name.

2. Starting Redis with the init script allows Redis to be started randomly (for production environments). See the Redis Getting Started guide for details.

Stop it
$ redis-cli SHUTDOWN

When Redis receives the shutdown command, it disconnects all client connections, then performs persistence based on the configuration and finally completes the exit.

You can also use the PID of the kill Redis process to end the Redis normally.

Redis Command-line Client

We can send commands to Redis through REDIS-CLI, and we can get the return value after the command executes.

Configuration

Redis can be configured through configuration files and command line parameters, see Redis.conf, which is located in the root directory of the source code directory.

Multiple databases

Redis is a dictionary-structured storage server, and a Redis instance provides multiple dictionaries for storing data, which the client can specify in which dictionary to store the data.

Each dictionary in the same instance is equivalent to a separate database, which is named after an incremented number starting at 0 and does not support custom names. By default, number No. 0 can be toggled with the Select command.

In addition, Redis does not support bits per database to set different access passwords, and multiple databases are not completely isolated, such as the Flushall command can empty an instance of the database.

Therefore, different dictionaries are suitable for use as namespaces, such as number No. 0 for production environments, number 1th for test environments, and so on.

Data from different applications are best stored in different instances.

Getting Started-data type warming up

1. Get the list of key names that match the rules

KEYS pattern

Where pattern supports GLOB style wildcard format.

? Match one character

* Match any of the characters

[] matches any one of the characters between parentheses

\ for escaping

Example:

> SET bar 1OK> KEYS *1) "bar"

(Redis is case insensitive to command case)

2. Determine if a key exists

EXISTS key

There is a return of 1, and no return 0 exists.

3. Delete key

DEL key [key ...]

You can delete more than one key, and the return value is the number of deleted keys.

Del's parameters do not support wildcards, but can be implemented in conjunction with the Linux pipeline and the Xargs command itself to implement a key that conforms to the rules, such as deleting all keys that begin with "User:":

redis-cli KEYS "user:*" | xargs redis-cli DEL

4. Get the data type of the key value

TYPE key

The return value might be:

String (String type)

Hash (hash type)

List (listing type)

Set (collection type)

Zset (ordered collection type)

String type

The Redis string is a sequence of bytes. In Redis, strings are binary safe, which means they have a known length that is not determined by any special character termination, so they can store anything for up to 512 megabytes in length.

Redis uses a variable of type SDSHDR to store the string, while the Redisobject PTR field points to the address of the variable.

struct sdshdr {    int//字符串长度    intfree//buf中剩余的空间    char//字符串内容};

Related commands:

1. Assigning and taking values

SET key valueGET key

Example:

127.0.0.1:6379SET"jiange"127.0.0.1:6379GET name"jiange"

2. Incrementing a number
When the stored content is in integer form, it can be self-incrementing, which defaults to 0 when the key value does not exist, so the result is 1 after the first increment.

INCR key

Generate the self-increment ID:

For article Data post: $postID:d ata, we need each article to have a unique self-increment id-> "\ $postID" that can be used with the name object type (plural form): count (named for reference only, can use any other name) Key to store the number of objects of the current type, using INCR for each new object added:

$postID= INCR posts:count$serializedPost= serialize($title,$content,$author,$time)SET post:$postID:data$serializedPost

3. Add a specified integer

INCRBY key increment

4. Decrease the specified integer

DECR keyDECRBY key decrement

5. Increase the specified floating point number

INCRBYFLOAT key increment

6. Append value to Tail

APPEND key value

7. Get the string length

STRLEN key

8. Get/Set multiple key values at the same time

MGET key [key ...]MSET key value [key value ...]

9. Bit operation

GETBIT key offsetSETBIT key offset valueBITCOUNT key [start] [end] //获得二进制中1的个数BITOP operation destkey key [key ...]//operation包括AND,OR,XOR,NOT
Hash type

The key value of a hash type is also a dictionary type that stores the mapping of field and field values, the field value can be only a string, and a hash type key can contain up to 2^32-1 fields.

Hash types are suitable for storing objects: Use object categories and IDs to form key, use fields to represent objects ' properties, and field values to store property values.

Like what:

键       字段  字段值        color   白色car:2   name    奥迪        price   90万

The car object has an ID of 2.

Related commands:

1. Assigning and taking values

......]HGETALL key

The Hset command does not differentiate between insert and update operations, returns 1 when an insert is performed, and returns 0 on update. When the key itself does not exist, the Hset command automatically establishes it.

2. Determine if a field exists

HEXISTS key field

3. Assign a value when the field does not exist

HSETNX key field value

If the field already exists, no action is taken.

4. Increase the number

HINCRBY key field increment

5. Delete a field

HDEL key field [field ...]

6. Get field names or field values only

HKEYS keyHVALS key

7. Get the number of fields

HLEN key
List type

Lists can store an ordered list of strings that are commonly used to add elements to both ends of the list, or to get a fragment of a list. It is implemented internally using a doubly linked list, so adding and retrieving elements at the head and tail is fast, and the disadvantage is that accessing the elements through the index is slow.

A list-type key can hold up to 2^32-1 elements.

Related commands:

1. Add elements to both ends of the list

LPUSH key value [value ...]RPUSH key value [value ...]

Add elements to the left and right of the list of key-value bits, respectively, and the return value indicates the length of the list after the element is added.

2. Eject an element to the end of the list

LPOP keyRPOP key

3. Get the number of elements in the list

LLEN key

Returns 0 when the key value does not exist;

4. Get the list fragment

LRANGE key start stop

Lrange supports negative indexing, which indicates that the ordinal is calculated from the right, and 1 represents the rightmost first element, and 2 represents the rightmost second element;

Lrange numbers 0-1 to get all the elements of the list

Returns an empty list when the index position of start is after the Stop index position;
When stop exceeds the actual index range, it returns to the rightmost element of the list;

5. Delete the value specified in the list

LREM key count value

The abbreviation for REM bit remove;
The above command deletes the first count value of the element in the list, and returns the number of elements actually deleted;
When Count > 0 o'clock, start deleting from the left of the list;
When Count < 0 o'clock, start deleting from the right of the list;
When count = 0 o'clock, the "all" value is removed from the list of elements that are values;

6. Get/Set the element value for the specified index

LINDEX key indexLSET key index value

The lindex is used to return the element of the specified index, starting at 0 and index negative, indicating that the calculation is started from the right;

7. Keep List-specific fields only

LTRIM key start end

This command can delete all elements outside the specified index range (the left and right are closed intervals);

8. Inserting elements into the list

LINSERT key BEFORE|AFTER pivot value

Inserts a value in front of or after the element with the value pivot values value;

9. Move elements from one list to another

RPOPLPUSH source destination
Collection type

Each element in the collection is different and has no order, and a key of a collection type can store up to 2^32-1 of strings.

The collection type is implemented within Redis using a hash table with a null value.

Multiple collection-type keys can be set, intersect, and differential-set operations.

Related commands:

1. Add/Remove elements

SADD key member [member ...]SREM key member [member ...]

The return value is the number of elements successfully added/removed;

2. Get all the elements in the collection

SMEMBERS key

3. Determine if the element is in the collection

SISMEMBER key member

Time Complexity is O (1);

4. Inter-assembly operations

SDIFF key [key ...]SINTER key [key ...]SUNION key [key ...]

5. Get the number of elements in the collection

SCARD key

6. Perform set operations and store results

SDIFFSTORE destination key [key ...]SINTERSTORE destination key [key ...]SUNIONSTORE destination key [key ...]

7. Randomly get the elements in the collection

SRANDMEMBER key [count]

In fact, the random selection here is a bucket (mentioned above, set is implemented in hash), and then randomly select an element from the bucket, so the probability that each element is selected is not the same.

8. Pop an element from the collection

SPOP key

Randomly pops an element.

Ordered collection types

An ordered set of similar sets. The difference is that each element of an ordered set has fractions that are easy to sort.

The ordered collection type is implemented using hash lists and jump tables, so it is very fast (time complexity is O (log (N)) Even if you are reading data in the middle section.

Related commands:

1. Adding elements

ZADD key score member [score member ...]

If an element already exists, the original score is replaced with a new score.
The return value is the number of elements newly added to the collection.

2. Get the number of elements

ZSCORE key member

3. Get a list of elements ranked in a range

ZRANGE key start stop [WITHSCORES]ZREVRANGE key start stop [WITHSCORES]

Zrange returns all elements (containing elements at both ends) of an index from start to stop in the order of element fractions from small to large.

Withscores can get the fraction of the element at the same time.

Zrevrange are sorted by fractions from large to small.

4. Get the element with the specified fraction range

ZRANGEBYSCORE key min max [WITHSCORES] [LIMIT offset count]

Returns the elements between Min and Max (including Min and Max) in the order of fractions from small to large.

The LIMIT offset count offsets the offset element backwards on the basis of the obtained element list, and only gets the first count elements.

5. Increase the score of an element

ZINCRBY key increment member

6. Get the number of elements in the collection

ZCARD key

7. Get the number of elements in the specified score range

ZCOUNT key min max

8. Delete one or more elements

ZREM key member [member ...]

9. Delete Elements by rank range

ZREMRANGEBYRANK key start stop

10. Deleting elements by fractional range

ZREMRANGEBYSCORE key min max

11. Get the ranking of the elements

ZRANK key memberZREVRANK key member

12. Calculating the intersection of ordered sets

ZINTERSTORE destination numkeys key [key ...] [WEIGHTS weight [weight ...]] [AGGREGATE SUM|MIN|MAX]

Redis QuickStart-Data types

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.