0

I would like to have autocomplete feature that suggests keywords from database. If I use MongoDB and multikey index, I kind of already have these keywords in database, but can I access them somehow?

If I have following object in collection:

{
    "title": "Some awesome title",
    "keywords": [
        "some",
        "awesome",
        "title"
    ]
}

And I have multikey index:

db.somecollection.ensureIndex({ "keywords" : 1 }) 

So index would contain following values:

"some"
"awesome"
"title"

If user enters "s" letter into autocomplete control, application should suggest "some" keyword. Can I search keywords from index or how should I do this?

1
  • 1
    I'd suggest using ElasticSearch or Solr for this as it's not something that MongoDB is currently very good at. Commented Jun 21, 2013 at 0:21

1 Answer 1

1

You can choose to use aggregation framework:

DEV:history:PRI > db.test.find()
{ "_id" : ObjectId("51c37c0c20d107378f9af3cc"), "title" : "Some awesome title", "keywords" : [ "some", "awesome", "title" ] }
{ "_id" : ObjectId("51c37de420d107378f9af3ce"), "title" : "Some awesome title", "keywords" : [ "some", "awesome", "something" ] }
{ "_id" : ObjectId("51c37f1920d107378f9af3cf"), "title" : "Some awesome title", "keywords" : [ "something", "awesome", "someone" ] }
DEV:history:PRI > db.test.aggregate({$match : {keywords : /^som/}}, {$project:{keywords:1, _id : 0}}, {$unwind : "$keywords"}, {$match : {keywords : /^som/}}, {$group: {_id : '$keywords', count : {$sum : 1}}})
{
    "result" : [
        {
            "_id" : "someone",
            "count" : 1
        },
        {
            "_id" : "something",
            "count" : 2
        },
        {
            "_id" : "some",
            "count" : 2
        }
    ],
    "ok" : 1
}

Note: Multi-key index are not covered and there are some JIRA issues already filed. So, despite of using indexes the queries are not covered (for multi-key indexes)

We can optionally use the 'count' params to decide on the ordering in showing the auto-complete. If you don't require, remove from the query.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your answer. In this way I can really read values, so I consider this as correct answer. Although this may be quite slow for bigger collections, so I try to use Redis (beside MongoDB) to target this problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.