Monday, March 30, 2015

Full Text Search for Meteor

As per the 1.0.4 release notes for Meteor, MongoDB 2.6 and 3.0 are now supported; and Meteor now comes bundled with MongoDB 2.6.7.

So what? This makes it easy to implement full text search via MongoDB's full text search support as follows:

Let's assume a Meteor collection Messages, with properties subject and content. When doing full text search, we want to have both subject and content indexed.

We need to ensure the collection underpinning the Messages collection has a full-text index defined:

Messages._ensureIndex({ subject: "text", content: "text" })

This gives us a full-text index covering both subject and content. (_ensureIndex should be used server-side only.)

A query (e.g. in a publish function) is now as simple as:

Messages.find({ $text: { $search: "invoice" }})

More information can be found in MongoDB's documentation on full text indexes and in Meteor's release notes.

A complete and runnable example is on Github.



No comments:

Post a Comment