DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
  1. DZone
  2. Data Engineering
  3. Databases
  4. MongoDB Full Text Search - Finally!

MongoDB Full Text Search - Finally!

A. Jesse Jiryu Davis user avatar by
A. Jesse Jiryu Davis
·
Jan. 15, 13 · Interview
Like (0)
Save
Tweet
Share
33.99K Views

Join the DZone community and get the full member experience.

Join For Free

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.


Database MongoDB

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.

Popular on DZone

  • Differences Between Site Reliability Engineer vs. Software Engineer vs. Cloud Engineer vs. DevOps Engineer
  • Mr. Over, the Engineer [Comic]
  • Upgrade Guide To Spring Data Elasticsearch 5.0
  • 5 Factors When Selecting a Database

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: