Redis stores key and value pairs in the data structure server. It contains unique keys to each data value.
Key only contains string type. values contain the following data types in Redis.
- Bit Arrays
Redis strings contain raw strings that contain a sequence of characters. The allowed maximum string size is 512 megabytes in length. It stores any sequence of data and it is binary safe. Following commands used to interact with strings process in Redis
|SET key value||Assign the value to the key|
|GET key||Retrieve the value for the given key|
|DEL key||Deletes the given key and value from a cache|
Here is an add, get and delete the keys in Redis interactive shell
127.0.0.1:6379> set name anderw OK 127.0.0.1:6379> get name "anderw" 127.0.0.1:6379> keys * 1) "name" 127.0.0.1:6379> del name (integer) 1
Lists in Redis
list is used to store the sequence of strings as values in insertion order for a given key.
List elements can be inserts head and tail, with linked strings. It is also called LinkedList.
Adding and insertion to the list perform better than retrieving the elements.
Following is a list of operations in the Redis list.
|LPUSH key value||add an element to the left end of a list|
|RPUSH key value||add an element to right end of a list|
|RANGES key start end||Retrieve the list of values with start and index items for a given key,0 is a start and -1 is the end index|
|LPOP key||delete an element from the left end of a list|
|RPOP key||remove an element from the right end of a list|
|LINDEX key index||Retrieves the element from the given key at index position|
Let’s see an examples
roles as keys values as admin,sales,hr,support,finance
let’s create a
roles of type lists by adding left to the end of the list. Since It is an empty list added admin as one of the elements.
127.0.0.1:6379> lpush roles admin (integer) 1
use lrange to retrieve a range of items in a list. 0 is starting index, and -1 is the end index of a list.
127.0.0.1:6379> lrange roles 0 -1 1) "admin"
Lets add a few more elements to the left and right end of a list
127.0.0.1:6379> lpush roles sales (integer) 2 127.0.0.1:6379> lrange roles 0 -1 1) "sales" 2) "admin" 127.0.0.1:6379> rpush roles finance (integer) 3 127.0.0.1:6379> lrange roles 0 -1 1) "sales" 2) "admin" 3) "finance" 127.0.0.1:6379> rpush roles support (integer) 4 127.0.0.1:6379> rpush roles hr (integer) 5 127.0.0.1:6379> rpush roles billing (integer) 6 127.0.0.1:6379> lrange roles 0 -1 1) "sales" 2) "admin" 3) "finance" 4) "support" 5) "hr" 6) "billing"
Next, get an element from a list using an index with
127.0.0.1:6379> lindex roles 0 "sales" 127.0.0.1:6379> lindex roles 1 "admin"
you can remove elements from the list using
127.0.0.1:6379> rpop roles "billing" 127.0.0.1:6379> lrange roles 0 -1 1) "sales" 2) "admin" 3) "finance" 4) "support" 5) "hr"
Redis List Types
Redis Sets Types
List are used to store similar list items. also called Arrays.