You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Experiment with Full-Text-Search using Node.js and MongoDB
WHY
Finding relevance in an ocean of content.
Having spent the last couple of days
wrestling with Meteor + Search
trying to get it let me search through a collection
I've decided to take a different approach to the probrem.
Hopefully by the end of this exercise we will be able to search through
a collection of "posts" (tweets) and find relevant results.
WHAT
Full-text searchwithout having to manage Solr or ElasticSearch.
(keeping it simple with just one data store)
In the past I've used Mongoose to interact with
MongoDB. Mongoose offers many great abstractions when building applications
specifically around pre-defining models and providing constructors to
validate fields on insert/update. We don't need that here.
All we need is the ability to:
Connect to MongoDB (Local)
Insert records into a collection
Create a text index for the text field in the collection
Execute a text (search) query against the records in the collection
Return a list of all the record (_ids) that match the search criteria
Store the results in a "results" collection to speed up future searches
For these simple tasks the Node MongoDB Native client is perfect.
Node.js MongoDB Native does not haverunCommand which is used in most
full-text search examples. So we cannot just do:
db.posts.runCommand("text",{search: "justin"})
But a bit of investigation yields:
// unintuitively the text field is actually the collection!db.command({text:"posts",search: "maths science"},function(err,cb){console.log(cb.results);});
Storing Search Results
The result of the above db.command search query has the format:
{ score: 2.142857142857143,
obj:
{ text: 'Math, science, history, unraveling the mystery it all started with a #BigBang💥',
time: Sun Mar 30 2014 07:03:08 GMT+0100 (BST),
avatar: 'https://pbs.twimg.com/profile_images/442935363095379968/CuEcmYsH_normal.jpeg',
_id: 'Kxssadbi2e5X7ga5L' } },
{ score: 2.142857142857143,
obj:
{ text: 'I was just about to set my maths and science books on fire…#ihateschool',
time: Sun Mar 30 2014 06:22:31 GMT+0100 (BST),
avatar: 'https://pbs.twimg.com/profile_images/449715822454243329/cNN69E3A_normal.jpeg',
_id: 'ghoi72BoEfswZgfws' } }
This returns the score (a float) and the entire record (all fields).
We could return these results directly to the user and we are done.
But going back to our original reason for diving into "naitve" node,
we want to be able to "pipe" these results back into our Meteor app.