2012-08-02 48 views
2

我在創造一個全球搜索的想法,讓我可以通過模型的任何屬性找到任何一個集合中的任何模型。例如:骨幹多集合全球搜索

我有以下類別:

  • 用戶
  • 應用
  • 角色

我不知道前面的時間每個用戶什麼屬性,廣告應用程式和角色將有,但爲了說明的目的可以說我有:

  • User.name
  • User.last_name
  • User.email
  • Application.title
  • Application.description
  • Role.name
  • Role.description

現在,讓我們說我用一種叫做search的方法創建了一個名爲Site的模型。我想Site.search(term)搜索每個集合中的所有項目,其中term與任何屬性匹配。本質上是全球模型搜索。

你會建議我如何處理這個問題?我可以通過遍歷所有集合的模型和每個模型的屬性來強制它,但這看起來很臃腫和低效。

有什麼建議嗎?

///幾分鐘後...

這裏有一些代碼我想剛纔:

find: function(query) { 
    var results = {}; // variable to hold the results 
    // iterate over the collections 
    _.each(["users", "applications", "roles"], _.bind(function(collection){ 
     // I want the result to be grouped by type of model so I add arrays to the results object 
     if (!_.isUndefined(results[collection]) || !_.isArray(results[collection])) { 
      results[collection] = []; 
     } 
     // iterate over the collection's models 
     _.each(this.get(collection).models, function(model){ 
      // iterate over each model's attributes 
      _.each(model.attributes, function(value){ 
       // for now I'm only considering string searches 
       if (_.isString(value)) { 
        // see if `query` is in the attribute's string/value 
        if (value.indexOf(query) > -1) { 
         // if so, push it into the result's collection arrray 
         results[collection].push(model); 
        } 
       }; 
      }); 
     }); 
     // a little cleanup 
     results[collection] = _.compact(results[collection]); 
     // remove empty arrays 
     if (results[collection].length < 1) { 
      delete results[collection]; 
     } 
    },this)); 
    // return the results 
    return results; 
} 

這將產生預期的結果,我想它工作正常,但它困擾我我正在迭代三個數組。可能沒有其他解決方案,但我有一種感覺。如果有人可以推薦一個,謝謝!同時我會繼續研究。

謝謝!

回答

2

我強烈勸阻你不要這樣做,除非你有一組非常有限的數據,性能對你來說並不是真正的問題。

如果您想要執行搜索,則對所有事物進行迭代是一項否定的事情。搜索引擎索引數據並使該過程可行。搜索很困難,而且沒有客戶端庫能夠有效地實現這一點。

這就是爲什麼大家都在服務器上搜索。有很容易(或有點)使用搜索引擎,如solr或更新的和我的個人偏好elasticsearch。假設您已經將模型/集合存儲在服務器上,那麼也應該將它們編入索引並且很簡單。然後,搜索就成爲您客戶進行REST調用的問題。

+0

我們與[sphinx](http://sphinxsearch.com/)也取得了成功,很容易上手。 – 2013-09-15 02:56:13