Atlas search index takes alot of time if query by text

Hi Mongo community!

I have around 300k docs and I want to run a query aggregation with diff stages.

the query needs 2 to 5s to resolve, depend on the text query, let say if we do “iphone 10” the query will take 1s but if we do “iphone 11 glass screen protectors” will take 3 to 10s, is there any way to improve this pipeline :

[
  {
    "$search": {
      "index": "product_title_en",
      "text": {
        "query": "iphone 11 glass screen protectors full",
        "path": "product_title_en"
      }
    }
  },
  {
    "$facet": {
      "products": [
        {
          "$skip": 0
        },
        {
          "$limit": 20
        }
      ],
      "products_count": [
        {
          "$count": "totalCount"
        }
      ],
      "available_categories": [
        {
          "$group": {
            "_id": "$category_en"
          }
        }
      ]
    }
  },
  {
    "$project": {
      "products_count": "$products_count.totalCount",
      "products": "$products",
      "available_categories": "$available_categories._id"
    }
  }
]

I did build atlas search index named “product_title_en”, can you help with with best practice in such scenario.
I do not understand why the seach take much longer evertime we add new word to the query

1 Like

Can you try using Atlas Search’s facet operator? Instead of $facet

2 Likes

Hi Elle_Shwer thank you for the response, I want to create an aggregation pipeline, but I dont know what’s the best practice specially I need a complex query, first we need to search by the title then we need to sort the data by price then limit to 20.
the result should return the docs + the availble categories in these docs + the count of each.

docs suggest to use near instead of sort but I have no Idea how to use it with text/phrase operator.
and how to use facets in my case.

I’ll apreciate any help thanks

Something like this might work:

[
  {
    '$search': {
      'facet': {
        'operator': {
          'text': {
            'path': 'title', 
            'query': '<query>'
          }
        }, 
        'facets': {
          'roomtypeFacet': {
            'type': 'string', 
            'path': 'category'
          }
        }
      }
    }
  }, {
    '$sort': {
      'price': 1
    }
  }, {
    '$facet': {
      'docs': [
        {
          '$limit': 20
        }
      ], 
      'meta': [
        {
          '$replaceWith': '$$SEARCH_META'
        }, {
          '$limit': 1
        }
      ]
    }
  }, {
    '$set': {
      'meta': {
        '$arrayElemAt': [
          '$meta', 0
        ]
      }
    }
  }
]

(can swap text out for near and remove the sort)