Sorting on any field in MongoDb Atlas Search pipeline

Viewed 310

I have a test data set (500k rows)

    {
        "_id": ObjectId("61309575c9346aab086f91fb"),
        "listId": ObjectId("61309575c9346aab086f91fa"),
        "createdDate": ISODate("2021-09-02T09:12:21.594Z"),
        "es0": "Firstname 0 Moscow",
        "es1": "firstname0@gmail.com",
        "es2": "0701230000",
        "es3": "Equatorial Guinea",
        "es4": "Iceland",
        "es5": "Los Angeles International Airport",
        "ed0": ISODate("1975-10-17T00:00:00Z"),
        "ed1": ISODate("2020-01-01T00:00:00Z"),
        "ei0": 46,
        "ei1": 1345
    }

I have a test query like this

    db.collection.aggregate([{
        $search: {
          "index": "test_index1",
          "compound": { 
            "filter": [{
                "equals": {
                  "path": "listId",
                  "value": ObjectId("613098df46239505942b8b13")
              }
            }],
            "must": [{
                "text": {
                    "query": 'Los Angeles',
                    "path": {
                      'wildcard': '*'
                    }
                  }
            }]
          }
        }
      }, 
      {
        $limit: 10
      }]);

which is super fast.

but if I add in a sort stage (before $limit)

    {
        $sort: {
            ei0: -1
        }
    }

it gets REALLY slow

I do have a regular index on "ei0" and its included in the search index as well (defined as a Number and dynamic mapping off)

Is there anyway to sort on any field (asc/desc), inside the search pipeline?

1 Answers

In the docs, they say:

Using a $sort aggregation pipeline stage after a $search stage can drastically slow down query results.

You should use near operator in atlas search to sort results.

Also you can customize your query scores to sort them.

Related