基于NodeJS和Redis的輕量級搜索引擎Reds
介紹:
Reds 是一個輕量的基于NodeJS和Redis的搜索引擎,由TJ Holowaychuk 開發,這個模塊原本是為優化 Kue 搜索能力而開發,但是它也非常適合作為輕量的通用搜索庫而加入到Blog、文檔系統中去。
安裝:
- $ npm install reds
例子:
首先你可能想做的事情就是創建一個可以通過關鍵字來進行搜索的搜索實例,你可以使用Redis的命名空間以支持在同一個DB里進行多重搜索。
- var search = reds.createSearch(‘pets‘);
Reds嚴格區分任意的數字和字符串ids,所以你可以用這個庫來做任何原本想做的事情,甚至是結構化數據存儲,下面的例子僅僅是一個包括了一些字符串數據庫數組,我們調用Search#index()來將它加入到Reds.
- var strs = [];
- strs.push(‘Tobi wants four dollars‘);
- strs.push(‘Tobi only wants $4‘);
- strs.push(‘Loki is really fat‘);
- strs.push(‘Loki, Jane, and Tobi are ferrets‘);
- strs.push(‘Manny is a cat‘);
- strs.push(‘Luna is a cat‘);
- strs.push(‘Mustachio is a cat‘);
- strs.forEach(function(str, i){ search.index(str, i); });
執行一個操作以防止Redsg來作為字符串調用Search#query(),然后通過回調函數來獲取一個執行完成之后包含ids或者空數組的返回結果。
- search
- .query(query = ‘Tobi dollars‘)
- .end(function(err, ids){
- if (err) throw err;
- console.log(‘Search results for "%s":‘, query);
- ids.forEach(function(id){
- console.log(‘ – %s‘, strs[id]);
- });
- process.exit();
- });
當Reds匹配到搜索的關鍵詞,將輸出如下的結果:
- Search results for "Tobi dollars":
- – Tobi wants four dollars
我們通過reds.search()也可以用Reds在回調函數里進行聯合查詢。
- search
- .query(query = ‘tobi dollars‘)
- .end(function(err, ids){
- if (err) throw err;
- console.log(‘Search results for "%s":‘, query);
- ids.forEach(function(id){
- console.log(‘ – %s‘, strs[id]);
- });
- process.exit();
- }, ‘or‘);
如果匹配到包含:”Tobi”和”dollars”關鍵詞的語句時,將返回如下結果:
- Search results for "tobi dollars":
- – Tobi wants four dollars
- – Tobi only wants $4
- – Loki, Jane, and Tobi are ferrets
API
- reds.createSearch(key)
- Search#index(text, id[, fn])
- Search#remove(id[, fn]);
- Search#query(text, fn[, type]);
例如:
- var search = reds.createSearch(‘misc‘);
- search.index(‘Foo bar baz‘, ‘abc‘);
- search.index(‘Foo bar‘, ‘bcd‘);
- search.remove(‘bcd‘);
- search.query(‘foo bar‘).end(function(err, ids){});
Reds的項目主頁是:https://github.com/visionmedia/reds
本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!