Indexing with Ranks/Ratings

Hi! This is my first question :slight_smile:

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 :face_with_open_eyes_and_hand_over_mouth:.

Dear @Samuel_Tinnerholm,

Welcome to The MongoDB Community forums! :wave:

Just to clarify, the text index you’re referring to is the $text operator instead of Atlas Search, right?

If it’s about the $text operator, I think you are looking for Sort functionality which you can use with $search.
Please check below documentation for reference:

These operators will work with your text index setup and you may be able to use them according to your requirements.

As a quick demonstration, let’s say we have a collection of documents similar to the example you posted:

[
  {
    "_id": "book1",
    "title": "example title",
    "description": "example description",
    "rating": 3.6
  },
  {
    "_id": "book2",
    "title": "example title",
    "description": "example description",
    "rating": 4.2
  }
]

Create a Text Index on it:

>db. collection.createIndex(
  {
    title: "text",
    description: "text"
  },
  {
    weights:{
      title: 2,
      description: 2
    },
    name: "Text1Index"
  }
)

Query the collection using the index and sorting the result by rating:

>db.Testing.find(
  {
    $text: {
      $search: "example"
    }
  }
).sort({ rating: -1})

Output will look like below:

[
  {
    "_id": "book2",
    "title": "example title",
    "description": "example description",
    "rating": 4.2
  },
  {
    "_id": "book1",
    "title": "example title",
    "description": "example description",
    "rating": 3.6
  }
]

Is this the output you are expecting?

In case you need more information, please share below details

  • MongoDB version
  • Your queries
  • Expected output

Regards,
Tarun

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.