骨干多集合全局搜索

Backbone multi-collection global search

本文关键字:全局搜索 集合      更新时间:2023-09-26

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

我有以下收藏品:

  • 用户
  • 应用程序
  • 角色

我不知道每个用户、应用程序和角色都会有什么属性,但为了说明起见,我说我有:

  • 用户名
  • 用户.last_name
  • 用户电子邮件
  • 应用程序标题
  • 应用程序说明
  • 角色名称
  • 角色说明

现在,假设我用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;
}

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

谢谢!

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

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

这就是为什么每个人都在服务器上搜索。存在简单(或某种)使用的搜索引擎,如solr或最近的和我个人偏好的弹性搜索。假设您已经在服务器上存储了模型/集合,那么对它们进行索引应该是很简单的。然后搜索就变成了从客户端进行REST调用的问题。