Custom Weighted Search Results

Saturday, March 11th 2023

Q: How do I get custom weighted search results for $search?

You can get custom weighted search results in MongoDB using the $search stage in combination with the $project stage to calculate and assign weights to the search results.

Here's an example of how you can use the $search stage to perform a text search and then use $project to calculate a custom weight for each document based on the search score and other document fields:

db.collection.aggregate([ { $search: { index: 'textIndex', text: { query: 'searchTerm', path: { wildcard: '*' } } } }, { $project: { _id: 1, field1: 1, field2: 1, score: { $meta: 'searchScore' }, weight: { $add: [ { $multiply: [ '$score', 0.5 ] }, { $multiply: [ '$field1', 0.3 ] }, { $multiply: [ '$field2', 0.2 ] } ] } } }, { $sort: { weight: -1 } } ])

In this example, we are using the $search stage to perform a text search on the textIndex index, searching for documents containing the searchTerm in any field. The results are sorted by their search score, with the highest-scoring documents appearing first.

Next, we use the $project stage to calculate a custom weight for each document based on the search score and the values of two other fields (field1 and field2). We assign weights to each field using the $multiply operator, and then add up the weighted values using the $add operator.

Finally, we sort the documents by their weight in descending order using the $sort stage, so that the documents with the highest weights appear first in the results.

Note that the weights assigned to each field are arbitrary and can be adjusted to fit your specific use case. Also, make sure to replace textIndex with the name of your actual text index.