$search in multiple fields with different score

Hi!

We are implementing a feature on our webpage where users can search for users stored in a collection in MongoDB (users).

After setting up a Search Index (with dynamic mapping) in Atlas, we managed to create a search aggregation that is querying multiple fields. The only thing we need to get working now, is scoring/weighting different properties differently.

Our current aggregation query;

{
  $search: {
    text: {
      query: 'search text',
      path: ['samAccountName', 'userPrincipalName', 'displayName']
    }
  }
}

Example documents in the users collection:

[
  {
    "_id": ObjectId("..."),
    "samAccountName": "adams",
    "userPrincipalName": "john.adams@example.com",
    "displayName": "John Adams"
  },
  {
    "_id": ObjectId("..."),
    "samAccountName": "john",
    "userPrincipalName": "john.snow@example.com",
    "displayName": "John Snow"
  }
]

In our search we want the fields to be scored in the order it’s in the path array, so matches for samAccountName is scored higher than userPrincipalName and displayName, so if I search for “john”, I will get the user with samAccountName “john” higher in the results than the other users with displayName containing this value.

How can we achieve this? Is it best to add this score boost to the index, or in the search query?

Thanks in advance. :grinning_face_with_smiling_eyes:
\\ Mats Andreassen

@vtfkmats Thank you for your question. I hope my answer can be helpful.

I suggest you explore the compound operator, must, and/or should depending on your use case. You can see this book search example below where I applying different scoring/weighting properties per field.

{  
 "$search": {   
   "compound": {
     "must": [{
         "text": {
           "query": "Hunter S. Thompson",
           "path": "author_name",
           "score": {
             "boost": {
               "value": 9
               }
             }
           }
       },
       {
         "text": {
           "query": "Fear and Loathing in Las Vegas",
           "path": "title",
           "score": {
             "boost": {
               "value": 5
               }
             }
           }
       }],
     "should": [{
         "range": {
           "value": "0",
           "path": "qty_available",
           "score": {
             "boost": {
               "value": 3
               }
             }
           }
       }],
     }
   }

Let me know if that’s helpful.

1 Like