Autocomplete search - Match multiple words in a search term (as AND)

Hi @Pavel_Duchovny, thank you for your quick reply.
I managed to get it work by setting the tokenization to edgeGram with minGrams 1. Thank you very much for this solution! It also helped me to understand the logic behind the search better.

For reference, this is the final solution that works:

The index:

{
	"mappings": {
		"dynamic": false,
		"fields": {
			"name": {
				"type": "autocomplete",
				"tokenization": "edgeGram",
				"minGrams": 1
			}
		}
	}
}

The query:

const searchTerm = ''; // Variable
db.getCollection('test-search').aggregate([
	{
		$search: {
			compound: {
				must: searchTerm.split(' ').map((word) => ({
					autocomplete: {
						query: word,
						path: 'name'
					}
				}))
			}
		}
	}
]).toArray();

Because of changing the minGrams to 1, this now also works with one-letter words. I’ll keep an eye out for the impact on performance.

3 Likes