人们想要找到内容。良好的搜索是必不可少的。
全文搜索。使用本机MongoDB 命令。
示例应用程序:
默认情况下,Meteor 启动自己的 MongoDB 实例,它没有全文索引/搜索,因此您需要使用本机。
如果您的系统上尚未“真正”安装 MongoDB,请使用HomeBrew安装它:
brew update
brew install mongodb
如果您不使用 Mac...
在终端/控制台窗口中使用以下命令启动 mongod 数据库:
mongod --dbpath ~/code/meteor-search/.meteor/local/db --setParameter textSearchEnabled=true
注意事项:
通过访问以下地址确认其工作:http://localhost:28017/(在浏览器中)
有关启用文本搜索的更多信息:http://docs.mongodb.org/manual/tutorial/enable-text-search/
因为我们使用的是“真正的”Mongo,所以我们需要在启动 Meteor 时指定它。 (这仅适用于当您在生产环境中进行开发时,您将设置 ENV
)
MONGO_URL="mongodb://localhost:27017/meteor" meteor
如果应用程序启动正常,游戏就开始了!
(否则请向此存储库提交错误,我将尽力帮助您!)
当您启动此应用程序时,它将访问 Twitter Streaming API 并获取数千条推文供您搜索(本地)。 (让它运行几分钟,您将获得 10k 个帖子。如果您想要数十万个帖子对搜索进行压力测试,则需要几个小时)
如果您想要快速获得大量内容,请将关键字更改为news 。
如果您想要大量(嘈杂)数据(以模拟高容量),请使用:
var KEYWORDS = "katie, justin, kim, beyonce, miley, Obama, 1DWorld, OMG, FML, breaking, news";
一旦您拥有一些内容,您需要确保 MongoDB 正在为其建立索引。
值得庆幸的是,使用 MongoDB 的EnsureIndex方法这非常容易。在我们的例子中,我们只需索引帖子的正文字段:
db.posts.ensureIndex( { body: "text" },{ background:true } );
有一个启动脚本可以自动为您执行此操作: server/indexes.js
根据您已插入的数据量,这可能需要一些时间...当我运行它时,我的数据库中有 92k 个帖子(推文),并且花费了不到 10 秒!
有关EnsureIndex的更多详细信息:
db.posts.runCommand( "text", { search: "paypal" } )
虽然这在 RoboMongo 中运行良好:
Meteor 不支持runCommand方法:
所以 ...
http://stackoverflow.com/questions/17159626/implementing-mongodb-2-4s-full-text-search-in-a-meteor-app/18258688#18258688
我编写了一个简单的正则表达式,将主题标签关键字转换为链接。我们不会使用链接污染原始数据(并使我们的记录膨胀),而是使用 Handlebars 模板帮助程序方法在渲染时(客户端)查找/替换 #keywords:
// place this code in your main.js or inside an Meteor.isClient block
Handlebars.registerHelper('highlight', function(text) {
var hashtagPattern = /s*(#w*)/gi,
link = "/search/",
m, match, matches = [], t, url ='';
// initial check for hashtag in text
if(text.indexOf("#") !== -1) {
// find all #keywords (that have hashtags)
while ( (match = hashtagPattern.exec(text)) ) {
matches.push(match[0]);
}
// replace any #keywords with <a href="/search/keywords">#keywords</a>
for(var j=0; j < matches.length; j++) {
m = matches[j].replace(/s/g, "");
// console.log('match',m);
url = link+m;
url = url.replace('#',"").toLowerCase(); // remove hashtag for lookup
t = " <a class='hashtag' href='"+url+"'>"+m+"</a> "; // replace with
replace = new RegExp("\s*("+m+")", 'gi');
text = text.replace(replace, t);
}
}
return text;
});
注意:链接模式是硬编码的/search/:keywords
,并且方法远非完美可链接!如果您对其进行了改进,请发送拉取请求。 :-)
MongoHQ默认情况下没有启用(完整)文本索引。
但当我提出要求时,他们很快就帮助了我:https://twitter.com/nelsonic/statuses/451758108285489152
您需要使用命令手动设置索引
(在您的 Mongo 客户端中 - 我们使用 RoboMongo - 或 Web 界面)
设置完成后,您就可以开始了。
在 RoboMongo(或您选择的任何 MongoDB 客户端)中,使用以下命令搜索您的集合(在您指定为可搜索的字段上)
db.COLLECTION.runCommand( "text", { search: "KEYWORDS" } );
// e.g:
db.posts.runCommand( "text", { search: "learn" } );
当我的集合中有327k 个帖子时,搜索结果在0.15 秒内返回:
该项目使用 Iron Router 进行 url 路由。
如果您不熟悉它(如果您认真使用 Meteor,那么您应该熟悉它),请阅读:
mrt add iron-router
有关如何连接它以接受表单中的请求的更多详细信息,请参阅routes.js文件:http: http://yoursite.com/search/:keywords