引言
在我們遊覽網頁時,隨處可見標籤的身影:
- 進入個人微博首頁,可以看到自己/他人的標籤,微博系統會推送與你有相同標籤的人
- 遊覽博文,大多數博文有標籤標記,以說明文章主旨,方便搜尋和查閱
- 網上購物,我們經常使用標籤進行商品搜尋,如點選 “冬裝” + “男士” + “外套” 進行衣物過濾
rtags就是一個用於標籤管理的node.js模組,其使用redis的set資料結構,存放標籤和相關資訊。(github地址: https://github.com/bangerlee/rtags.git)
API
rtags提供以下介面:
- 添加物件及其標籤 Tag#add(tags, id[, fn])
- 查詢物件的標籤 Tag#queryID(id, fn)
- 查詢兩個物件共有的標籤 Tag#queryID(id1, id2, fn)
- 查詢具有特定標籤的物件 Tag#queryTag(tags, fn)
- 刪除物件的標籤 Tag#delTag(tags, id[, fn])
- 刪除物件 Tag#remove(id[, fn])
樣本
首先調用 Tag#createTag 產生一個 Tag 執行個體,傳入一個字串指示物件的類別,比如 ‘blogs’ 指示博文,‘clothes’ 指示衣服:
var tag = rtags.createTag('blogs');
然後添加該類別的物件和對應的標籤,Tag#add 接收兩個參數,第一個是物件的標籤,有多個標籤可用逗號隔開;第二個參數是物件的 id,以下代碼中以 strs 下標為 id:
var strs = [];strs.push('travel,photography,food,music,shopping');strs.push('music,party,food,girl');strs.push('mac,computer,cpu,memory,disk');strs.push('linux,kernel,linus,1991');strs.push('kernel,process,lock,time,linux');strs.forEach(function(str, i){ tag.add(str, i); });
經過上面調用,redis 資料庫中就有了博文標籤資料,我們就可以進行相關查詢了。查詢某物件具有哪些標籤,我們可以調用 Tag#queryID,該函數接收物件 id 和一個回呼函數作為參數,查詢結果作為數組存放在 ids 中:
tag .queryID(id = '3') .end(function(err, ids){ if (err) throw err; console.log('Tags for "%s":', id); var tags = ids.join(' '); console.log(' - %s', tags); });
以上代碼用於查詢 id 為 ‘3’ 的博文的標籤,執行該段代碼,輸出為:
Tags for "3": - kernel linux linus 1991
要查詢兩個物件具有哪些相同標籤,同樣調用 Tag#queryID,這時傳入的參數應為兩個物件的 id 和一個回呼函數:
tag .queryID(id1 = '3', id2 = '4') .end(function(err, ids){ if (err) throw err; console.log('Tags for "%s" and "%s" both have:', id1, id2); var tags = ids.join(' '); console.log(' - %s', tags); });
以上代碼用於查詢 id 為 ‘3’ 和 ‘4’ 的博文共有的標籤,查詢結果為:
Tags for "3" and "4" both have: - kernel linux
rtags 還提供根據標籤搜尋物件的功能,調用 Tag#queryTag,傳入標籤和一個回呼函數,若有多個標籤,可用逗號隔開:
tag .queryTag(tags = 'music,food') .end(function(err, ids){ if (err) throw err; console.log('The objects own the "%s" tags:', tags); var id = ids.join(' '); console.log(' - %s', id); process.exit(); });
以上代碼查詢同時具有 ‘music’ 和 ‘food’ 標籤的博文,其輸出為:
The objects own the "music,food" tags: - 0 1
安裝
rtags通過以下命令安裝,該命令會一同安裝rtags依賴的redis模組:
$ npm install rtags
亦可以通過以下命令從 github 擷取 rtags 源碼:
$ git clone git@github.com:bangerlee/rtags.git
拉起 redis-server,安裝 should 模組後,我們可以執行 rtags 源碼目錄下的例子:
$ cd rtags/test$ node index.js
github地址: https://github.com/bangerlee/rtags.git
歡迎 git pull/fork/clone。
Have fun!