Meteor數據庫mongodb查詢

當我們進行數據查詢的時候,默認數據發佈的時候是不帶條件過濾,可能將全部的數據發佈到客戶端,這是無法想象的,因此我們採用幾種措施來提高查詢效率:

使用正則查詢

沒有查詢條件的代碼

// location: /server/app.js

Meteor.publish('getEntries', function(searchText) {
  return Entries.find({}, {sort: {name: 1}, limit:20});
});

改進後:

Meteor.publish('getEntries', function(searchText) {
  // second paramter 'i' indicates that we want our regular expression to be case-insensitive.
  var filter = new RegExp(searchText, 'i');
  return Entries.find({name: filter}, {sort: {name: 1}, limit:20});
});

上面的查詢方式可能是inefficient,最好在使用過程中加上索引,Meteor mongo啓動後,使用以下語句添加索引:

db.entries.ensureIndex({name:1})

檢索過程使用精確的匹配符和大小寫將提高查詢效率,eg:

db.entries.find({name: new RegExp("^Tom")}).explain()

忽略大小寫將降低查詢效率,以下語句可同上面的查詢進行對比:

db.entries.find({name: new RegExp("^Tom", "i")}).explain()

使用全文檢索查詢

全文檢索在mongodb2.6裏面成爲默認支持的功能,搜索文檔的時候將變得更加敏捷。
使用全文檢索前需添加text類型的index。

db.entries.ensureIndex({name: "text"});

查詢:

Entries.find({$text: {$search: searchText}});
Entries.find({$text: {$search: searchText}, age: {$gt: 25}});

當使用複合條件查詢時,可修改索引爲

db.entries.ensureIndex({name: "text", age: 1});
Entries.find({$text: {$search: searchText}, age: {$gt: 25}});

When to Use Regular Expression Search

Here are some of the places you can use Regular Expression Search:

If you need real-time searching capabilities
If your dataset size is not more than few thousand documents
If you need partial word matching
If you need to save disk space
When to Use Full Text Search

If your dataset is big, and you need high-performance search results
If you can afford more disk space
If you need language-specific search requirements
If you don’t need real-time search (actually, real-time updates)
It is very important not to create publications contain Full Text Search–related queries. Since it does not support oplog tailing, Meteor will poll the db for changes. This could be very costly for both Meteor and MongoDB.

So if you’re going with Full Text Search, always get data from a method rather than by using a publication.
If you’re going to use Full Text Search, you need to allocate enough space and memory for your MongoDB instance. You can learn about this in detail here.

Other Options

It’s clear that both of the above solutions are very limited in functionality and have some issues. That’s why MongoDB is not a good solution for searching. Therefore, you may need to use some other solutions. Here are two of the best:

Elastic Search—One of best open source search solutions
Algolia—A cloud-based solution
In an upcoming lesson, we’ll talk about how to use Elastic Search with Meteor. You may also have had some good search experiences. If so, please share those with us in the comments section.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章