Database Reference
In-Depth Information
Using Text Search
Despite all the complexity we've described, MongoDB text search is surprisingly easy to use; you create a text index in
the same way as any other index. For example, to create a text index on the “content” element of our theoretical blog
collection, I would run the following
db.blog.ensureIndex( { content : "text" } );
And that's it. MongoDB will take care of the rest and insert a text index into your database, and all future documents
that have a content field will be processed and have entries added to the text index to be searched. But really, just
creating an index isn't quite enough data to work with. We need a suitable set of text data to work with and query.
Loading Text Data
Originally, we had planned to use a live stream of data from twitter, but the documents were too ungainly to work with.
So we have instead created a small batch of eight documents mimicking twitter feeds to take text search out for a spin.
Go ahead and mongoimport the MongoDB data from the twitter.tgz into your database:
$ mongoimport test.json -d test -c texttest
connected to: 127.0.0.1
Sat Jul 6 17:52:19 imported 8 objects
Now that we have the data restored, go ahead and enable text indexing if it isn't already:
db.adminCommand({ setParameter: 1, textSearchEnabled : true });
{ "was" : false, "ok" : 1 }
Now that we have text indexing enabled, we should create a text index on the twitter data.
Creating a Text Index
In the case of twitter data, the portion we are concerned with is the text field, which is the body text of the tweet.
To set up the text index we run the following command:
use test;
db. texttest.ensureIndex( { body : "text" } );
If you see the error message “text search not enabled,” you need to ensure that the text index is running, by using
the commands just shown. Now if you review your logs you will see the following, which shows the text index
being built:
Sat Jul 6 17:54:16.078 [conn41] build index test.texttest { _fts: "text", _ftsx: 1 }
Sat Jul 6 17:54:16.089 [conn41] build index done. scanned 8 total records. 0.01 secs
We can also check the indexes for the collection:
db.texttest.getIndexes()
[
{
"v" : 1,
"key" : {
 
Search WWH ::




Custom Search