我在创造一个全球搜索的想法,让我可以通过模型的任何属性找到任何一个集合中的任何模型。例如:骨干多集合全球搜索
我有以下类别:
- 用户
- 应用
- 角色
我不知道前面的时间每个用户什么属性,广告应用程式和角色将有,但为了说明的目的可以说我有:
- 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;
}
这将产生预期的结果,我想它工作正常,但它困扰我我正在迭代三个数组。可能没有其他解决方案,但我有一种感觉。如果有人可以推荐一个,谢谢!同时我会继续研究。
谢谢!
我们与[sphinx](http://sphinxsearch.com/)也取得了成功,很容易上手。 – 2013-09-15 02:56:13