NoSQL Zone is brought to you in partnership with:

Software developer specializing in MongoDB, Python, Tornado, and Javascript, with particular interests in real-time web and new tools that get the job done with grace and alacrity. A. Jesse Jiryu is a DZone MVB and is not an employee of DZone and has posted 67 posts at DZone. You can read more from them at their website. View Full User Profile

MongoDB Full Text Search - Finally!

01.15.2013
| 21571 views |
  • submit to reddit

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()
    parser.feed(html)
    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:

db.posts.create_index(
    [
        ('title', 'text'),
        ('categories.name', 'text'),
        ('tags', 'text'), ('plain', 'text')
    ],
    weights={
        '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
ASCENDING, DESCENDING, GEO2D, or GEOHAYSTACK

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

db.posts.createIndex(
    {
        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',
    search=q,
    filter={'status': 'publish', 'type': 'post'},
    projection={
        'display': False,
        'original': False,
        'plain': False
    },
    limit=50)

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 A. Jesse Jiryu Davis, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Comments

Robert Sindall replied on Mon, 2013/03/25 - 6:52pm

Nice article, we used Elastic Search for free text searching, it was easy to setup and a nightmare to code with.

Now that MongoDB 2.4 has a beta Text Search feature, I like you feel it could simplify out overall architecture and code base.

I've written a short how to use MongoDB Free Text Search blog post, it has instructions on how to get setup, code example and overview of some of the current limitations.

http://www.robertsindall.co.uk/blog/how-to-use-mongodb-free-text-search/ 

I thought it might come in handy getting some developers started.

Ronaeg Osama replied on Mon, 2014/08/25 - 2:55am

 This is very interesting, You’re a very skilled blogger. I have joined your rss feed and look forward to seeking more of your fantastic post. Also, I’ve shared your website in my social networks! العاب باربي برنامج تحليل الاسهم توصيات اسهم سنايبرستوك    jailbreak jailbreak wizard application for iphone

Adham Slim replied on Thu, 2014/08/28 - 5:11am

 Wonderful illustrated information. I thank you about that. No doubt it will be very useful for my future projects. Would like to see some other posts on the same subject! اجابات اجابة

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.