]> git.saurik.com Git - redis.git/blob - doc/IntroductionToRedisDataTypes.html
help.h updated
[redis.git] / doc / IntroductionToRedisDataTypes.html
1
2 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
3 <html>
4 <head>
5 <link type="text/css" rel="stylesheet" href="style.css" />
6 </head>
7 <body>
8 <div id="page">
9
10 <div id='header'>
11 <a href="index.html">
12 <img style="border:none" alt="Redis Documentation" src="redis.png">
13 </a>
14 </div>
15
16 <div id="pagecontent">
17 <div class="index">
18 <!-- This is a (PRE) block. Make sure it's left aligned or your toc title will be off. -->
19 <b>IntroductionToRedisDataTypes: Contents</b><br>&nbsp;&nbsp;<a href="#A fifteen minutes introduction to Redis data types">A fifteen minutes introduction to Redis data types</a><br>&nbsp;&nbsp;&nbsp;&nbsp;<a href="#Redis keys">Redis keys</a><br>&nbsp;&nbsp;&nbsp;&nbsp;<a href="#The string type">The string type</a><br>&nbsp;&nbsp;&nbsp;&nbsp;<a href="#The List type">The List type</a><br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#First steps with Redis lists">First steps with Redis lists</a><br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#Pushing IDs instead of the actual data in Redis lists">Pushing IDs instead of the actual data in Redis lists</a><br>&nbsp;&nbsp;&nbsp;&nbsp;<a href="#Redis Sets">Redis Sets</a><br>&nbsp;&nbsp;&nbsp;&nbsp;<a href="#A digression. How to get unique identifiers for strings">A digression. How to get unique identifiers for strings</a><br>&nbsp;&nbsp;&nbsp;&nbsp;<a href="#Sorted sets">Sorted sets</a><br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#Operating on ranges">Operating on ranges</a><br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#Back to the reddit example">Back to the reddit example</a><br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#Updating the scores of a sorted set">Updating the scores of a sorted set</a>
20 </div>
21
22 <h1 class="wikiname">IntroductionToRedisDataTypes</h1>
23
24 <div class="summary">
25
26 </div>
27
28 <div class="narrow">
29 &iuml;&raquo;&iquest;#sidebar <a href="RedisGuides.html">RedisGuides</a>
30 <h1><a name="A fifteen minutes introduction to Redis data types">A fifteen minutes introduction to Redis data types</a></h1>As you already probably know Redis is not a plain key-value store, actually it is a <b>data structures server</b>, supporting different kind of values. That is, you can't just set strings as values of keys. All the following data types are supported as values:<br/><br/><ul><li> Binary-safe strings.</li><li> Lists of binary-safe strings.</li><li> Sets of binary-safe strings, that are collection of unique unsorted elements. You can think at this as a Ruby hash where all the keys are set to the 'true' value.</li><li> Sorted sets, similar to Sets but where every element is associated to a floating number score. The elements are taken sorted by score. You can think at this as Ruby hashes where the key is the element and the value is the score, but where elements are always taken in order without requiring a sorting operation.</li></ul>
31 It's not always trivial to grasp how this data types work and what to use in order to solve a given problem from the <a href="CommandReference.html">Redis command reference</a>, so this document is a crash course to Redis data types and their most used patterns.<br/><br/>For all the examples we'll use the <b>redis-cli</b> utility, that's a simple but handy command line utility to issue commands against the Redis server.<h2><a name="Redis keys">Redis keys</a></h2>Before to start talking about the different kind of values supported by Redis it is better to start saying that keys are not binary safe strings in Redis, but just strings not containing a space or a newline character. For instance &quot;foo&quot; or &quot;123456789&quot; or &quot;foo_bar&quot; are valid keys, while &quot;hello world&quot; or &quot;hello\n&quot; are not.<br/><br/>Actually there is nothing inside the Redis internals preventing the use of binary keys, it's just a matter of protocol, and actually the new protocol introduced with Redis 1.2 (1.2 betas are 1.1.x) in order to implement commands like MSET, is totally binary safe. Still for now consider this as an hard limit as the database is only tested with &quot;normal&quot; keys.<br/><br/>A few other rules about keys:<br/><br/><ul><li> Too long keys are not a good idea, for instance a key of 1024 bytes is not a good idea not only memory-wise, but also because the lookup of the key in the dataset may require several costly key-comparisons.</li><li> Too short keys are not a good idea. There is no point in writing &quot;u:1000:pwd&quot; as key if you can write instead &quot;user:1000:password&quot;, the latter is more readable and the added space is very little compared to the space used by the key object itself.</li><li> Try to stick with a schema. For instance &quot;object-type:id:field&quot; can be a nice idea, like in &quot;user:1000:password&quot;. I like to use dots for multi-words fields, like in &quot;comment:1234:reply.to&quot;.</li></ul>
32 <h2><a name="The string type">The string type</a></h2>This is the simplest Redis type. If you use only this type, Redis will be something like a memcached server with persistence.<br/><br/>Let's play a bit with the string type:<br/><br/><pre class="codeblock python" name="code">
33 $ ./redis-cli set mykey &quot;my binary safe value&quot;
34 OK
35 $ ./redis-cli get mykey
36 my binary safe value
37 </pre>As you can see using the <a href="SetCommand.html">Set command</a> and the <a href="GetCommand.html">Get command</a> is trivial to set values to strings and have this strings returned back.<br/><br/>Values can be strings (including binary data) of every kind, for instance you can store a jpeg image inside a key. A value can't be bigger than 1 Gigabyte.<br/><br/>Even if strings are the basic values of Redis, there are interesting operations you can perform against them. For instance one is atomic increment:<br/><br/><pre class="codeblock python python" name="code">
38 $ ./redis-cli set counter 100
39 OK
40 $ ./redis-cli incr counter
41 (integer) 101
42 $ ./redis-cli incr counter
43 (integer) 102
44 $ ./redis-cli incrby counter 10
45 (integer) 112
46 </pre>The <a href="IncrCommand.html">INCR</a> command parses the string value as an integer, increments it by one, and finally sets the obtained value as the new string value. There are other similar commands like <a href="IncrCommand.html">INCRBY</a>, <a href="IncrCommand.html">DECR</a> and <a href="IncrCommand.html">DECRBY</a>. Actually internally it's always the same command, acting in a slightly different way.<br/><br/>What means that INCR is atomic? That even multiple clients issuing INCR against the same key will never incur into a race condition. For instance it can't never happen that client 1 read &quot;10&quot;, client 2 read &quot;10&quot; at the same time, both increment to 11, and set the new value of 11. The final value will always be of 12 ad the read-increment-set operation is performed while all the other clients are not executing a command at the same time.<br/><br/>Another interesting operation on string is the <a href="GetsetCommand.html">GETSET</a> command, that does just what its name suggests: Set a key to a new value, returning the old value, as result. Why this is useful? Example: you have a system that increments a Redis key using the <a href="IncrCommand.html">INCR</a> command every time your web site receives a new visit. You want to collect this information one time every hour, without loosing a single key. You can GETSET the key assigning it the new value of &quot;0&quot; and reading the old value back.<h2><a name="The List type">The List type</a></h2>To explain the List data type it's better to start with a little of theory, as the term <b>List</b> is often used in an improper way by information technology folks. For instance &quot;Python Lists&quot; are not what the name may suggest (Linked Lists), but them are actually Arrays (the same data type is called Array in Ruby actually).<br/><br/>From a very general point of view a List is just a sequence of ordered elements: 10,20,1,2,3 is a list, but when a list of items is implemented using an Array and when instead a <b>Linked List</b> is used for the implementation, the properties change a lot.<br/><br/>Redis lists are implemented via Linked Lists, this means that even if you have million of elements inside a list, the operation of adding a new element in the head or in the tail of the list is performed <b>in constant time</b>. Adding a new element with the <a href="LpushCommand.html">LPUSH</a> command to the head of a ten elements list is the same speed as adding an element to the head of a 10 million elements list.<br/><br/>What's the downside? That accessing an element <b>by index</b> is very fast in lists implemented with an Array and not so fast in lists implemented by linked lists.<br/><br/>Redis Lists are implemented with linked lists because for a database system is crucial to be able to add elements to a very long list in a very fast way. Another strong advantage is, as you'll see in a moment, that Redis Lists can be taken at constant length in constant time.<h3><a name="First steps with Redis lists">First steps with Redis lists</a></h3>The <a href="RpushCommand.html">LPUSH</a> command add a new element into a list, on the left (on head), while the <a href="RpushCommand.html">RPUSH</a> command add a new element into alist, ot the right (on tail). Finally the <a href="LrangeCommand.html">LRANGE</a> command extract ranges of elements from lists:<br/><br/><pre class="codeblock python python python" name="code">
47 $ ./redis-cli rpush messages &quot;Hello how are you?&quot;
48 OK
49 $ ./redis-cli rpush messages &quot;Fine thanks. I'm having fun with Redis&quot;
50 OK
51 $ ./redis-cli rpush messages &quot;I should look into this NOSQL thing ASAP&quot;
52 OK
53 $ ./redis-cli lrange messages 0 2
54 1. Hello how are you?
55 2. Fine thanks. I'm having fun with Redis
56 3. I should look into this NOSQL thing ASAP
57 </pre>Note that <a href="LrangeCommand.html">LRANGE</a> takes two indexes, the first and the last element of the range to return. Both the indexes can be negative to tell Redis to start to count for the end, so -1 is the last element, -2 is the penultimate element of the list, and so forth.<br/><br/>As you can guess from the example above, lists can be used, for instance, in order to implement a chat system. Another use is as queues in order to route messages between different processes. But the key point is that <b>you can use Redis lists every time you require to access data in the same order they are added</b>. This will not require any SQL ORDER BY operation, will be very fast, and will scale to millions of elements even with a toy Linux box.<br/><br/>For instance in ranking systems like the social news reddit.com you can add every new submitted link into a List, and with <a href="LrangeCommand.html">LRANGE</a> it's possible to paginate results in a trivial way.<br/><br/>In a blog engine implementation you can have a list for every post, where to push blog comments, and so forth.<h3><a name="Pushing IDs instead of the actual data in Redis lists">Pushing IDs instead of the actual data in Redis lists</a></h3>In the above example we pushed our &quot;objects&quot; (simply messages in the example) directly inside the Redis list, but this is often not the way to go, as objects can be referenced in multiple times: in a list to preserve their chronological order, in a Set to remember they are about a specific category, in another list but only if this object matches some kind of requisite, and so forth.<br/><br/>Let's return back to the reddit.com example. A more credible pattern for adding submitted links (news) to the list is the following:<br/><br/><pre class="codeblock python python python python" name="code">
58 $ ./redis-cli incr next.news.id
59 (integer) 1
60 $ ./redis-cli set news:1:title &quot;Redis is simple&quot;
61 OK
62 $ ./redis-cli set news:1:url &quot;http://code.google.com/p/redis&quot;
63 OK
64 $ ./redis-cli lpush submitted.news 1
65 OK
66 </pre>We obtained an unique incremental ID for our news object just incrementing a key, then used this ID to create the object setting a key for every field in the object. Finally the ID of the new object was pushed on the <b>submitted.news</b> list.<br/><br/>This is just the start. Check the <a href="CommandReference.html">Command Reference</a> and read about all the other list related commands. You can remove elements, rotate lists, get and set elements by index, and of course retrieve the length of the list with <a href="LLenCommand.html">LLEN</a>.<h2><a name="Redis Sets">Redis Sets</a></h2>Redis Sets are unordered collection of binary-safe strings. The <a href="SaddCommand.html">SADD</a> command adds a new element to a set. It's also possible to do a number of other operations against sets like testing if a given element already exists, performing the intersection, union or difference between multiple sets and so forth. An example is worth 1000 words:<br/><br/><pre class="codeblock python python python python python" name="code">
67 $ ./redis-cli sadd myset 1
68 (integer) 1
69 $ ./redis-cli sadd myset 2
70 (integer) 1
71 $ ./redis-cli sadd myset 3
72 (integer) 1
73 $ ./redis-cli smembers myset
74 1. 3
75 2. 1
76 3. 2
77 </pre>I added three elements to my set and told Redis to return back all the elements. As you can see they are not sorted.<br/><br/>Now let's check if a given element exists:<br/><br/><pre class="codeblock python python python python python python" name="code">
78 $ ./redis-cli sismember myset 3
79 (integer) 1
80 $ ./redis-cli sismember myset 30
81 (integer) 0
82 </pre>&quot;3&quot; is a member of the set, while &quot;30&quot; is not. Sets are very good in order to express relations between objects. For instance we can easily use Redis Sets in order to implement tags.<br/><br/>A simple way to model this is to have, for every object you want to tag, a Set with all the IDs of the tags associated with the object, and for every tag that exists, a Set of of all the objects tagged with this tag.<br/><br/>For instance if our news ID 1000 is tagged with tag 1,2,5 and 77, we can specify the following two Sets:<br/><br/><pre class="codeblock python python python python python python python" name="code">
83 $ ./redis-cli sadd news:1000:tags 1
84 (integer) 1
85 $ ./redis-cli sadd news:1000:tags 2
86 (integer) 1
87 $ ./redis-cli sadd news:1000:tags 5
88 (integer) 1
89 $ ./redis-cli sadd news:1000:tags 77
90 (integer) 1
91 $ ./redis-cli sadd tag:1:objects 1000
92 (integer) 1
93 $ ./redis-cli sadd tag:2:objects 1000
94 (integer) 1
95 $ ./redis-cli sadd tag:5:objects 1000
96 (integer) 1
97 $ ./redis-cli sadd tag:77:objects 1000
98 (integer) 1
99 </pre>To get all the tags for a given object is trivial:<br/><br/>$ ./redis-cli smembers <a href="news:1000:tags" target="_blank">news:1000:tags</a>
100 1. 5
101 2. 1
102 3. 77
103 4. 2<br/><br/>But there are other non trivial operations that are still easy to implement using the right Redis commands. For instance we may want the list of all the objects having as tags 1, 2, 10, and 27 at the same time. We can do this using the <a href="SinterCommand.html">SinterCommand</a> that performs the intersection between different sets. So in order to reach our goal we can just use:<br/><br/><pre class="codeblock python python python python python python python python" name="code">
104 $ ./redis-cli sinter tag:1:objects tag:2:objects tag:10:objects tag:27:objects
105 ... no result in our dataset composed of just one object ;) ...
106 </pre>Look at the <a href="CommandReference.html">Command Reference</a> to discover other Set related commands, there are a bunch of interesting one. Also make sure to check the <a href="SortCommand.html">SORT</a> command as both Redis Sets and Lists are sortable.<h2><a name="A digression. How to get unique identifiers for strings">A digression. How to get unique identifiers for strings</a></h2>In our tags example we showed tag IDs without to mention how this IDs can be obtained. Basically for every tag added to the system, you need an unique identifier. You also want to be sure that there are no race conditions if multiple clients are trying to add the same tag at the same time. Also, if a tag already exists, you want its ID returned, otherwise a new unique ID should be created and associated to the tag.<br/><br/>Redis 1.4 will add the Hash type. With it it will be trivial to associate strings with unique IDs, but how to do this today with the current commands exported by Redis in a reliable way?<br/><br/>Our first attempt (that is broken) can be the following. Let's suppose we want to get an unique ID for the tag &quot;redis&quot;:<br/><br/><ul><li> In order to make this algorithm binary safe (they are just tags but think to utf8, spaces and so forth) we start performing the SHA1 sum of the tag. SHA1(redis) = b840fc02d524045429941cc15f59e41cb7be6c52.</li><li> Let's check if this tag is already associated with an unique ID with the command <b>GET tag:b840fc02d524045429941cc15f59e41cb7be6c52:id</b>.</li><li> If the above GET returns an ID, return it back to the user. We already have the unique ID.</li><li> Otherwise... create a new unique ID with <b>INCR next.tag.id</b> (assume it returned 123456).</li><li> Finally associate this new ID to our tag with <b>SET tag:b840fc02d524045429941cc15f59e41cb7be6c52:id 123456</b> and return the new ID to the caller.</li></ul>
107 Nice. Or better.. broken! What about if two clients perform this commands at the same time trying to get the unique ID for the tag &quot;redis&quot;? If the timing is right they'll both get <b>nil</b> from the GET operation, will both increment the <b>next.tag.id</b> key and will set two times the key. One of the two clients will return the wrong ID to the caller. To fix the algorithm is not hard fortunately, and this is the sane version:<br/><br/><ul><li> In order to make this algorithm binary safe (they are just tags but think to utf8, spaces and so forth) we start performing the SHA1 sum of the tag. SHA1(redis) = b840fc02d524045429941cc15f59e41cb7be6c52.</li><li> Let's check if this tag is already associated with an unique ID with the command <b>GET tag:b840fc02d524045429941cc15f59e41cb7be6c52:id</b>.</li><li> If the above GET returns an ID, return it back to the user. We already have the unique ID.</li><li> Otherwise... create a new unique ID with <b>INCR next.tag.id</b> (assume it returned 123456).</li><li> Finally associate this new ID to our tag with <b>SETNX tag:b840fc02d524045429941cc15f59e41cb7be6c52:id 123456</b>. By using SETNX if a different client was faster than this one the key wil not be setted. Not only, SETNX returns 1 if the key is set, 0 otherwise. So... let's add a final step to our computation.</li><li> If SETNX returned 1 (We set the key) return 123456 to the caller, it's our tag ID, otherwise perform <b>GET tag:b840fc02d524045429941cc15f59e41cb7be6c52:id</b> and return the value to the caller.</li></ul>
108 <h2><a name="Sorted sets">Sorted sets</a></h2>Sets are a very handy data type, but... they are a bit too unsorted in order to fit well for a number of problems ;) This is why Redis 1.2 introduced Sorted Sets. They are very similar to Sets, collections of binary-safe strings, but this time with an associated score, and an operation similar to the List LRANGE operation to return items in order, but working against Sorted Sets, that is, the <a href="ZrangeCommand.html">ZRANGE</a> command.<br/><br/>Basically Sorted Sets are in some way the Redis equivalent of Indexes in the SQL world. For instance in our reddit.com example above there was no mention about how to generate the actual home page with news raked by user votes and time. We'll see how sorted sets can fix this problem, but it's better to start with something simpler, illustrating the basic working of this advanced data type. Let's add a few selected hackers with their year of birth as &quot;score&quot;.<br/><br/><pre class="codeblock python python python python python python python python python" name="code">
109 $ ./redis-cli zadd hackers 1940 &quot;Alan Kay&quot;
110 (integer) 1
111 $ ./redis-cli zadd hackers 1953 &quot;Richard Stallman&quot;
112 (integer) 1
113 $ ./redis-cli zadd hackers 1965 &quot;Yukihiro Matsumoto&quot;
114 (integer) 1
115 $ ./redis-cli zadd hackers 1916 &quot;Claude Shannon&quot;
116 (integer) 1
117 $ ./redis-cli zadd hackers 1969 &quot;Linus Torvalds&quot;
118 (integer) 1
119 $ ./redis-cli zadd hackers 1912 &quot;Alan Turing&quot;
120 (integer) 1
121 </pre>For sorted sets it's a joke to return these hackers sorted by their birth year because actually <b>they are already sorted</b>. Sorted sets are implemented via a dual-ported data structure containing both a skip list and an hash table, so every time we add an element Redis performs an O(log(N)) operation, that's good, but when we ask for sorted elements Redis does not have to do any work at all, it's already all sorted:<br/><br/><pre class="codeblock python python python python python python python python python python" name="code">
122 $ ./redis-cli zrange hackers 0 -1
123 1. Alan Turing
124 2. Claude Shannon
125 3. Alan Kay
126 4. Richard Stallman
127 5. Yukihiro Matsumoto
128 6. Linus Torvalds
129 </pre>Didn't know that Linus was younger than Yukihiro btw ;)<br/><br/>Anyway I want to order this elements the other way around, using <a href="ZREVRANGE.html">ZrangeCommand</a> instead of <a href="ZRANGE.html">ZrangeCommand</a> this time:<br/><br/><pre class="codeblock python python python python python python python python python python python" name="code">
130 $ ./redis-cli zrevrange hackers 0 -1
131 1. Linus Torvalds
132 2. Yukihiro Matsumoto
133 3. Richard Stallman
134 4. Alan Kay
135 5. Claude Shannon
136 6. Alan Turing
137 </pre>A very important note, ZSets have just a &quot;default&quot; ordering but you are still free to call the <a href="SortCommand.html">SORT</a> command against sorted sets to get a different ordering (but this time the server will waste CPU). An alternative for having multiple orders is to add every element in multiple sorted sets at the same time.<h3><a name="Operating on ranges">Operating on ranges</a></h3>Sorted sets are more powerful than this. They can operate on ranges. For instance let's try to get all the individuals that born up to the 1950. We use the <a href="ZrangebyscoreCommand.html">ZRANGEBYSCORE</a> command to do it:<br/><br/><pre class="codeblock python python python python python python python python python python python python" name="code">
138 $ ./redis-cli zrangebyscore hackers -inf 1950
139 1. Alan Turing
140 2. Claude Shannon
141 3. Alan Kay
142 </pre>We asked Redis to return all the elements with a score between negative infinite and 1950 (both extremes are included).<br/><br/>It's also possible to remove ranges of elements. For instance let's remove all the hackers born between 1940 and 1960 from the sorted set:<br/><br/><pre class="codeblock python python python python python python python python python python python python python" name="code">
143 $ ./redis-cli zremrangebyscore hackers 1940 1960
144 (integer) 2
145 </pre><a href="ZremrangebyscoreCommand.html">ZREMRANGEBYSCORE</a> is not the best command name, but it can be very useful, and returns the number of removed elements.<h3><a name="Back to the reddit example">Back to the reddit example</a></h3>For the last time, back to the Reddit example. Now we have a decent plan to populate a sorted set in order to generate the home page. A sorted set can contain all the news that are not older than a few days (we remove old entries from time to time using ZREMRANGEBYSCORE). A background job gets all the elements from this sorted set, get the user votes and the time of the news, and compute the score to populate the <b>reddit.home.page</b> sorted set with the news IDs and associated scores. To show the home page we have just to perform a blazingly fast call to ZRANGE.<br/><br/>From time to time we'll remove too old news from the <b>reddit.home.page</b> sorted set as well in order for our system to work always against a limited set of news.<h3><a name="Updating the scores of a sorted set">Updating the scores of a sorted set</a></h3>Just a final note before to finish this tutorial. Sorted sets scores can be updated at any time. Just calling again ZADD against an element already included in the sorted set will update its score (and position) in O(log(N)), so sorted sets are suitable even when there are tons of updates.<br/><br/>This tutorial is in no way complete, this is just the basics to get started with Redis, read the <a href="CommandReference.html">Command Reference</a> to discover a lot more.<br/><br/>Thanks for reading. Salvatore.
146 </div>
147
148 </div>
149 </div>
150 </body>
151 </html>
152