基于NodeJS和Redis的輕量級搜索引擎Reds

jopen 9年前發布 | 14K 次閱讀 Redis 搜索引擎

介紹:

Reds 是一個輕量的基于NodeJS和Redis的搜索引擎,由TJ Holowaychuk 開發,這個模塊原本是為優化 Kue 搜索能力而開發,但是它也非常適合作為輕量的通用搜索庫而加入到Blog、文檔系統中去。

安裝:

  1. $ npm install reds

例子:

首先你可能想做的事情就是創建一個可以通過關鍵字來進行搜索的搜索實例,你可以使用Redis的命名空間以支持在同一個DB里進行多重搜索。

  1. var search = reds.createSearch(pets);

Reds嚴格區分任意的數字和字符串ids,所以你可以用這個庫來做任何原本想做的事情,甚至是結構化數據存儲,下面的例子僅僅是一個包括了一些字符串數據庫數組,我們調用Search#index()來將它加入到Reds.

  1. var strs = [];
  2. strs.push(Tobi wants four dollars);
  3. strs.push(Tobi only wants $4);
  4. strs.push(Loki is really fat);
  5. strs.push(Loki, Jane, and Tobi are ferrets);
  6. strs.push(Manny is a cat);
  7. strs.push(Luna is a cat);
  8. strs.push(Mustachio is a cat);
  9.  
  10. strs.forEach(function(str, i){ search.index(str, i); });

執行一個操作以防止Redsg來作為字符串調用Search#query(),然后通過回調函數來獲取一個執行完成之后包含ids或者空數組的返回結果。

  1. search
  2.   .query(query = Tobi dollars)
  3.   .end(function(err, ids){
  4.     if (err) throw err;
  5.     console.log(Search results for "%s":, query);
  6.     ids.forEach(function(id){
  7.       console.log(  – %s, strs[id]);
  8.     });
  9.     process.exit();
  10.   });

當Reds匹配到搜索的關鍵詞,將輸出如下的結果:

  1. Search results for "Tobi dollars":
  2.   – Tobi wants four dollars

我們通過reds.search()也可以用Reds在回調函數里進行聯合查詢。

  1. search
  2.   .query(query = tobi dollars)
  3.   .end(function(err, ids){
  4.     if (err) throw err;
  5.     console.log(Search results for "%s":, query);
  6.     ids.forEach(function(id){
  7.       console.log(  – %s, strs[id]);
  8.     });
  9.     process.exit();
  10.   }, or);

如果匹配到包含:”Tobi”和”dollars”關鍵詞的語句時,將返回如下結果:

  1. Search results for "tobi dollars":
  2.   – Tobi wants four dollars
  3.   – Tobi only wants $4
  4.   – Loki, Jane, and Tobi are ferrets

API

  1. reds.createSearch(key)
  2. Search#index(text, id[, fn])
  3. Search#remove(id[, fn]);
  4. Search#query(text, fn[, type]);

例如:

  1. var search = reds.createSearch(misc);
  2. search.index(Foo bar baz, abc);
  3. search.index(Foo bar, bcd);
  4. search.remove(bcd);
  5. search.query(foo bar).end(function(err, ids){});

Reds的項目主頁是:https://github.com/visionmedia/reds

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!