{{ !articles[0].partner.isSponsoringArticle ? "Platinum" : "Portal" }} Partner

MongoDB Full Text Search - Finally!

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.

Published at DZone with permission of {{ articles[0].authors[0].realName }}, DZone MVB. (source)

Opinions expressed by DZone contributors are their own.

{{ tag }}, {{tag}},

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

{{ parent.tldr }}

{{ parent.urlSource.name }}
{{ parent.authors[0].realName || parent.author}}

{{ parent.authors[0].tagline || parent.tagline }}

{{ parent.views }} ViewsClicks