How to search exact word in a test in Elastic Search

Viewed 25

Let's say I have two texts: Text 1 - "The fox has been living in the wood cabin for days." Text 2 - "The wooden hammer is a dangerous weapon."

And I would like to search for the word "wood", without it matching me "wooden hammer". How would I do that in Elastic Search or nest?

1 Answers

Term query is used for exact matches search. However it's not recommended to use it against text fields, the following quote from term query documentation:

To better search text fields, the match query also analyzes your provided search term before performing a search. This means the match query can search text fields for analyzed tokens rather than an exact term.

The term query does not analyze the search term. The term query only searches for the exact term you provide. This means the term query may return poor or no results when searching text fields.

The problem with text exact matches, as described in the Term query documentation:

By default, Elasticsearch changes the values of text fields as part of analysis. This can make finding exact matches for text field values difficult.

So, the documents data is modified (i.e., analyzed) before indexing. This depends on the index mapping definition for each field, defaults to the default index analyzer, or the standard analyzer.

But the default standard analyzer will not change the token "Wooden" to "Wood", this might happen if you used stemming for this field. This means, if you don't use a different analyzer or stemming, querying with "Wood" shouldn't match "Wooden" token.

To summarize: Indexed data is modified/analyzed before indexing (based on the field mapping definition). Match query analyze the search query, while Term query doesn't analyze the search query. So you have to properly chose the field mapping and the search query to better suit your use case

For some use cases, like storing email addressed, phone numbers or keyword fields that always have the same value, consider using the Keyword type, which is suitable for exact matches in these use cases. However, ES recommends:

Avoid using keyword fields for full-text search. Use the text field type instead.

So for better visibility and practical solution for your use case, it's better to elaborate more the field mapping you use and what you want to achieve.

Related