$text only returns a result if the field has multiple words

Greetings. I have a collection with a lot of entries and I’m trying to make it so I can search in it by text, without having to use the exact content of a field. I have created a text index for it, indicating which fields contain text that should we search in.

It seemed to work fine for the first few times, but then I noticed it only works if there are multiple words in the matching field. If it’s a single word, it won’t return anything unless I type the exact word, which is what I am trying to avoid.

My current code:

client.db.itemdata.findOne( { $text: { $search: \"${input}\", $caseSensitive: false } } )

Here is a screenshot to help present the issue. Any help is appreciated

Hi @Lord_Wasabi,

Text search uses the Snowball stemming algorithm which has language-specific heuristics to determine the common word stem of indexed words. Heuristics are common rules like "plurals end in a single s" in English. Snowball does not include any comprehension of language, grammar, or context so partial or nonsense words will be stemmed according to the same rules.

There’s an online Snowball demo that is a handy reference for how words are stemmed, or you could look at the MonngoDB query explain output using your text index:

> db.mydb.find({$text: {$search: 'arany'} }).explain().queryPlanner.winningPlan.parsedTextQuery
{
	"terms" : [
		"arani"
	],
	"negatedTerms" : [ ],
	"phrases" : [ ],
	"negatedPhrases" : [ ]
}

Using English stemming your example of arany stems to arani, which will not match a search term of ara. Exact matches or phrases that stem to the same root (like aranys, arani, or aranie) will match. If you change the text language to Hungarian, arany stems to arany using the language-specific heuristics (but ara is still not a match).

If you are interested in more advanced search cases and are open to using MongoDB Atlas, Atlas Search integrates the Lucene search engine for more complex query behaviour such as autocomplete, fuzzy matches, and wildcards.

Regards,
Stennie

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.