Redis学习笔记3--Redis键值设计


原文:http://blog.csdn.net/freebird_lb/article/details/7733988



tag在互联网应用里尤其多见,首先看下面的关系型数据表:

Book表: 

id

name

author

1

The Ruby Programming Language

Mark Pilgrim

2

Ruby on rail

David Flanagan

3

Programming Erlang

Joe Armstrong

Tag表:

tag_name

book_id

ruby

1

ruby

2

web

2

erlang

3

 

现在用Redis将这两张表的数据存起来: 

保存Book的数据:

redis 127.0.0.1:6379> incr book_id #book_id这个key保存book表的id,每次要获得一个新的

                                          #book_idincr命令自增取得

(integer) 1

#incr命令返回1,则用keybook:1hash来保存一个book对象,对象属性为hashfield

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 #hgetall命令测试一个,返回hash的所有属性和值

1) "name"

2) "The Ruby Programming Language"

3) "author"

4) "Mark Pilgrim"

redis 127.0.0.1:6379> incr book_id #创建第2book对象,incr一个book_id获得新bookid

(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"

 


你可能感兴趣的:(redis)