Over a million developers have joined DZone.

MongoDB Full Text Search - Finally!

Learn NoSQL for free with hands-on sample code, example queries, tutorials, and more.  Brought to you in partnership with Couchbase.

Dictionary indents headon

Wikimedia commons

Yesterday we released the latest unstable version of MongoDB; the headline feature is basic full-text search. You can read all about MongoDB's full text search in the release notes.

This blog had been using a really terrible method for search, involving regular expressions, a full collection scan for every search, and no ranking of results by relevance. I wanted to replace all that cruft with MongoDB's full-text search ASAP. Here's what I did.

Plain Text

My blog is written in Markdown and displayed as HTML. What I want to actually search is the posts' plain text, so I customized Python's standard HTMLParser to strip tags from the HTML:

import re
from HTMLParser import HTMLParser

whitespace = re.compile('\s+')

class HTMLStripTags(HTMLParser):
    """Strip tags
    def __init__(self, *args, **kwargs):
        HTMLParser.__init__(self, *args, **kwargs)
        self.out = ""

    def handle_data(self, data):
        self.out += data

    def handle_entityref(self, name):
        self.out += '&%s;' % name

    def handle_charref(self, name):
        return self.handle_entityref('#' + name)

    def value(self):
        # Collapse whitespace
        return whitespace.sub(' ', self.out).strip()

def plain(html):
    parser = HTMLStripTags()
    return parser.value()

The output is imperfect—it adds extra spaces around punctuation and generally creates a small mess—but it's not meant to be published in the New Yorker, it's meant to be indexed.

I wrote a script that runs through all my existing posts, extracts the plain text, and stores it in a new field on each document called plain. I also updated my blog's code so it now creates the plain field on each post whenever I save a post.

Creating the Index

I installed MongoDB 2.3.2 and started it with this command line option:

--setParameter textSearchEnabled=true

Without that option, creating a text index causes a server error, "text search not enabled".

Next I created a text index on posts' titles, category names, tags, and the plain text that I generated above. I can set different relevance weights for each field. The title contributes most to a post's relevance score, followed by categories and tags, and finally the text. In Python, the index declaration looks like:

        ('title', 'text'),
        ('categories.name', 'text'),
        ('tags', 'text'), ('plain', 'text')
        'title': 10,
        'categories.name': 5,
        'tags': 5,
        'plain': 1

Note that you'll need to install PyMongo from the current master in GitHub or wait for PyMongo 2.4.2 in order to create a text index. PyMongo 2.4.1 and earlier throw an exception:

TypeError: second item in each key pair must be

If you don't want to upgrade PyMongo, just use the mongo shell to create the index:

        title: 'text',
        'categories.name': 'text',
        tags: 'text',
        plain: 'text'
        weights: {
            title: 10,
            'categories.name': 5,
            tags: 5,
            plain: 1

Searching the Index

To use the text index I can't do a normal find, I have to run the text command. In my async driver Motor, this looks like:

response = yield motor.Op(self.db.command, 'text', 'posts',
    filter={'status': 'publish', 'type': 'post'},
        'display': False,
        'original': False,
        'plain': False

The q variable is whatever you typed into the search box on the left, like "mongo" or "hamster" or "python's thread locals are weird". The filter option ensures only published posts are returned, and the projection avoids returning large unneeded fields. Results are sorted with the most relevant first, and the limit is applied after the sort.

In Conclusion

Simple, right? The new text index provides a simple, fully consistent way to do basic search without deploying any extra services. Go read up about it in the release notes.

The Getting Started with NoSQL Guide will get you hands-on with NoSQL in minutes with no coding needed. Brought to you in partnership with Couchbase.


Published at DZone with permission of A. Jesse Jiryu Davis, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}