比如在MySQL裡面,對內容的標簽有以下簡單的幾張表,我這裡只列出來拆分過後的表結構
第一,MySQL部分,內容表: CREATE TABLE `content` ( `id` int(10) unsigned NOT NULL, -- 內容ID,唯一。 `name` varchar(60) DEFAULT NULL, -- 內容的名字 `created_timestamp` timestamp NULL DEFAULT NULL, -- 內容的加入時間 PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 標簽表: CREATE TABLE `tag` ( `tag_name` varchar(60) NOT NULL, -- 標簽名字,唯一 `visit_count` int(10) unsigned NOT NULL DEFAULT '0', -- 標簽的訪問次數 PRIMARY KEY (`tag_name`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 內容與標簽的關系,多對多。 CREATE TABLE `content_tag_relation` ( `content_id` int(10) unsigned NOT NULL, -- 內容ID `tag_name` varchar(60) NOT NULL -- 標簽名字 ) ENGINE=InnoDB DEFAULT CHARSET=latin1
SELECT a.name FROM content AS a,content_tag_relation AS b WHERE a.id = b.content_id AND b.tag_name = 'mysql'
SELECT tag_name FROM tag WHERE 1 ORDER BY visit_count DESC LIMIT 3;
下來我們在REDIS裡面存儲這部分數據。
t_girl:6379> set string:content_id:4 '{"name":"test48601","created_timestamp":"2012-01-01 05:41:01"}' OK t_girl:6379> get string:content_id:4 "{\"name\":\"test48601\",\"created_timestamp\":\"2012-01-01 05:41:01\"}"
t_girl:6379> hset 'hset:content_id:4' name 'test48601' (integer) 1 t_girl:6379> hset 'hset:content_id:4' created_timestamp '2012-01-01 05:41:01' (integer) 1
t_girl:6379> hget hset:content_id:4 name "test48601" t_girl:6379> hget hset:content_id:4 created_timestamp "2012-01-01 05:41:01" t_girl:6379>
t_girl:6379> zadd zset:tag 680 database 469 db2 (integer) 2
t_girl:6379> zrevrangebyscore zset:tag +inf 0 limit 0 3 1) "mongodb" 2) "sql" 3) "postgresql"
t_girl:6379> sadd set:content_id:4 role mongodb role database (integer) 3
t_girl:6379> smembers set:content_id:4 1) "database" 2) "role" 3) "mongodb"
import redis content_id_keys = r.keys('set*') content_id_keys_len = len(content_id_keys) i = 0 j = 0 content_name_list = [] while i < content_id_keys_len: if r.sismember(content_id_keys[i],'mysql') == 1: content_name_list.append(eval(r.get(content_id_keys[i].replace('set','string')))['name']) print('Content name is :' + content_name_list[j]) j += 1 i += 1
t_girl:6379> sadd tag:mysql test123 test133 test144 test155 (integer) 4 t_girl:6379> smembers tag:mysql 1) "test133" 2) "test155" 3) "test123" 4) "test144"