Home > Software design >  Indexing With Raking System MongoDB
Indexing With Raking System MongoDB

Time:08-18

This is my first question.

In my DB, I have documents that look something like this:

{
    “_id”: “book1”,
    “title”: “example title”,
    “description”: “example description”,
    “rating”: 3.6
},
{
    “_id”: “book2”,
    “title”: “example title”,
    “description”: “example description”,
    “rating”: 4.2
}

I have a text index setup for the title and description with weights making the title more important than the description. Let’s say I search for “example” is there a way to take the rating into account? What I mean by this is that a book with a higher rating is more important, and in this specific case, book2 should show up above book1. Is this possible, or is processing outside of MongoDB necessary- I’m kind of a database noob.

CodePudding user response:

You can do that by getting the score of the text search via meta data and add the rating to it. After that just sort the results. This must be done via aggregation pipeline.

[
  {
    '$match': {
      '$text': {
        '$search': 'example'
      }
    }
  }, {
    '$addFields': {
      'score': {
        '$add': [
          {
            '$meta': 'textScore'
          }, '$rating'
        ]
      }
    }
  }, {
    '$sort': {
      'score': 1
    }
  }
]
  • Related