Atlas search on more than 1 field within same collection

I have a requirement where user can multi select search fields from application and fire the search.
So lets take 2 fields for the discussion where I need to apply full text search on both fields. I have created 2 separate text index on both columns. How can I make use of both indexes using compound operator? is there a way?

Note: there can be up to 5 search fields user can select and in different order.

db.sampleCollection.aggregate([
{$search: {index: “index1” , “compound”: {“should”: [ { “regex”: {“path”: “name.fullName”,“query”: “(.)bin(.)”}}]}}},
])

db.sampleCollection.aggregate([
{$search: {index: “index2” , “compound”: {“should”: [ { “regex”: {“path”: “references.name”,“query”: “(.)intel(.)”}}]}}},
])

The queries above are working, however I want to merge these into one using compound operator and mention both indexes.

Hey @Prabhu_Pasupathiraj , welcome to the community!

You can just use one search index that indexes both the name.fullName field and the references.name field.

For the index definition:

{
  "mappings": {
    "dynamic": true,
    "fields": {
      "name": [
        {
          "type": "document",
          "dynamic": true
        }
      ],
      "references": {
        "type": "document",
        "dynamic": true
      }
    }
  }
}

Query:

db.sampleCollection.aggregate([
{$search: 
   {
     index: “default” , 
       “compound”: {
          “should”: [ 
             {
                “regex”: {
                   “path”: “references.name”,
                   “query”: “(.)intel(.)”
               },
            },
           {
               “regex”: {
                   “path”: “name.fullName”,
                   “query”: “(.)bin(.)”
               },
            },
         ]
       }
     }
}
])

let me know if this helps!

1 Like

Thanks Amy.
As mentioned earlier, I have up to 5 fields that can be selected by the user in any order and all 5 are searchable fields. In this case, If I add all those 5 fields in one index - will it work even I change the order of fields or limit the search with 3 fields?

This should work unless i’m interpreting the question wrong. You can test it out and advise the results.

For reference, I have one Atlas search index which covers 5 fields in my test environment and i’m able to search on all of those fields.

Thanks Jason. I will try and get back.

1 Like