Tags are especially common in Internet applications, first look at the following relational data table:
Book table:
id |
name |
author |
1 |
The Ruby Programming Language |
Mark Pilgrim |
2 |
Ruby on rail |
David Flanagan |
3 |
Programming Erlang |
Joe Armstrong |
Tag table:
tag_name |
book_id |
ruby |
1 |
ruby |
2 |
web |
2 |
erlang |
3 |
Now use redis to store the data of these two tables:
Save Book data:
redis 127.0.0.1:6379> incr book_id #Use the key book_id to save the id of the book table , and get a new one each time #book_id is automatically incremented by the incr command (integer) 1 The #incr command returns 1, then use the hash whose key is book:1 to save a book object , and the object attribute is the field of the hash redis 127.0.0.1:6379> hset book:1 name "The Ruby Programming Language" (integer) 1 redis 127.0.0.1:6379> hset book:1 author "Mark Pilgrim" (integer) 1 redis 127.0.0.1:6379> hgetall book:1 #Test one with the hgetall command and return all attributes and values of the hash 1) "name" 2) "The Ruby Programming Language" 3) "author" 4) "Mark Pilgrim" redis 127.0.0.1:6379> incr book_id #Create a second book object , first incr a book_id to get the id of the new book (integer) 2 redis 127.0.0.1:6379> hset book:2 name "Ruby on rail" (integer) 1 redis 127.0.0.1:6379> hset book:2 author "David Flanagan" (integer) 1 redis 127.0.0.1:6379> hgetall book:2 1) "name" 2) "Ruby on rail" 3) "author" 4) "David Flanagan" redis 127.0.0.1:6379> incr book_id (integer) 3 redis 127.0.0.1:6379> hset book:3 name "Programming Erlang" (integer) 1 redis 127.0.0.1:6379> hset book:3 author "Joe Armstrong" (integer) 1 redis 127.0.0.1:6379> hgetall book:3 1) "name" 2) "Programming Erlang" 3) "author" 4) "Joe Armstrong" |
保存Tag的数据,使用集合来存储数据,因为集合可以求交集、并集、差集:
redis 127.0.0.1:6379> sadd tag:ruby 1 (integer) 1 redis 127.0.0.1:6379> sadd tag:ruby 2 (integer) 1 redis 127.0.0.1:6379> sadd tag:web 2 (integer) 1 redis 127.0.0.1:6379> sadd tag:erlang 3 (integer) 1 |
如果要取得即属于ruby又属于web的书:
redis 127.0.0.1:6379> sinter tag:ruby tag:web 1) "2" |
如果要取得属于ruby,但不属于web的书:
redis 127.0.0.1:6379> sdiff tag:ruby tag:web 1) "1" |
属于ruby和属于web的书的合集:
redis 127.0.0.1:6379> sunion tag:ruby tag:web 1) "1" 2) "2" |