2

我正在玩弄创建一个全局搜索的想法,它允许我通过任何模型的属性在多个集合中的任何一个集合中找到任何模型。例如:

我有以下收藏:

  • 用户
  • 应用
  • 角色

我不提前知道每个用户、应用程序和角色将具有哪些属性,但为了说明目的,可以说我有:

  • 用户名
  • User.last_name
  • 用户邮箱
  • 应用程序.title
  • 应用程序描述
  • 角色名称
  • 角色描述

现在,假设我创建了Site一个使用名为search. 我想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;
}

这产生了预期的结果,我想它工作正常,但我正在迭代三个数组,这让我很困扰。可能没有其他解决方案,但我有一种感觉。如果有人可以推荐一个,谢谢!同时我会继续研究。

谢谢!

4

1 回答 1

2

我强烈建议您不要这样做,除非您的数据非常有限,而且性能对您来说并不是真正的问题。

如果您想执行搜索,则对所有内容进行迭代是不行的。搜索引擎索引数据并使该过程可行。很难构建搜索,并且没有客户端库可以有效地做到这一点。

这就是为什么每个人都在服务器上进行搜索的原因。存在易于(或某种程度上)使用的搜索引擎,例如solr或更新的和我个人偏好的elasticsearch。大概您已经将模型/集合存储在服务器上,将它们编入索引应该是微不足道的。然后搜索变成了从您的客户端进行 REST 调用的问题。

于 2012-08-02T09:09:57.460 回答