MongoDB Atlas search autocomplete for partial and exact matching

Viewed 90

Documents

{'name': 'name whatever'}, {'name': 'foo whatever'}, ...

Search index

{
  "mappings": {
    "dynamic": false,
    "fields": {
      "name": [
        {
          "type": "string"
        },
        {
          "maxGrams": 100,
          "type": "autocomplete"
        }
      ]
    }
  },
  "storedSource": true
}

I want to search by what, whatever, name whatever

It seems ok when I searching what and whatever

// for what
{
  index: 'indexName',
  autocomplete: {
    query: 'whatever',
    path: 'name'
  }
}

// for whatever
{
  index: 'indexName',
  autocomplete: {
    query: 'whatever',
    path: 'name'
  }
}

But searching name whatever is not working what I expected,

{
  index: 'indexName',
  autocomplete: {
    query: 'name whatever',
    path: 'name'
  }
}

this returns name whatever but also foo whatever

How can I get only name whatever?

1 Answers

I had a similar issue and I believe the answer was to include 'tokenOrder: sequential' in the search - so your query would look like this:

{
  index: 'indexName',
  autocomplete: {
    query: 'name whatever',
    path: 'name',
    tokenOrder: 'sequential'
  }
}

https://www.mongodb.com/docs/atlas/atlas-search/autocomplete/#token-order-example

The description for using sequential tokenOrder states:

sequential Indicates tokens in the query must appear adjacent to each other or in the order specified in the query in the documents. Results contain only documents where the tokens appear sequentially.

Related