Skip to content

Instantly share code, notes, and snippets.

@saintc0d3r
Created June 29, 2014 14:29
Show Gist options
  • Save saintc0d3r/c150678fc1e0163a80cb to your computer and use it in GitHub Desktop.
Save saintc0d3r/c150678fc1e0163a80cb to your computer and use it in GitHub Desktop.
Text Search Index in MongoDB
// Let's say we have a documents db where it has a sentences collection
use documents
db.sentences.insert({'words': 'Cat moss granite.'})
db.sentences.insert({'words': 'dog tree ruby.'})
db.sentences.insert({'words': 'dog tree obsidian.'})
db.sentences.insert({'words': 'dog tree granite.'})
db.sentences.insert({'words': 'dog shrub ruby.'})
db.sentences.insert({'words': 'dog shrub obsidian.'})
db.sentences.insert({'words': 'dog shrub granite.'})
db.sentences.insert({'words': 'dog moss ruby.'})
db.sentences.insert({'words': 'dog moss obsidian.'})
db.sentences.insert({'words': 'dog moss granite.'})
db.sentences.insert({'words': 'rat tree ruby.'})
db.sentences.insert({'words': 'rat tree obsidian.'})
// Let's try query documents that contains 'dog moss'
db.sentences.find({'words': 'dog moss'})
// Oops! It does not return any documents that we wanted :(
// Solution: Let's add a text index on the words field
db.sentences.ensureIndex({'words': 'text'})
// Let's peek the created index
db.sentences.getIndexes()
// Alright. The index should have been created on the word field.
// Let's testing the water now
db.sentences.find({'$text': {'$search':'dog moss'}})
// yay \:D/ ! We should get a number of documents where its words containing either 'dog', 'moss' or both
// But, they documents that has both 'dog' & 'moss' words are not sorted at the top list.
// How to make them placed at the top list ?
// Solution: We're going to add a score-$meta projection in the query and then sort it by the score, as follow:
db.sentences.find({'$text': {'$search':'dog moss'}}, {'score': {'$meta': 'textScore'}}).sort({'score': {'$meta': 'textScore'}})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment