Match Query vs Term Query
Match Query
Match query analyzes the search term, based on the standard analyzer (if no analyzer is specified) and then matches the analyzed term with the terms stored in the inverted index. By default text
type field uses a standard analyzer if no analyzer is specified.
For eg. SchooL gets analyzed to school OR wonder-land
will get tokenized into
{
"tokens": [
{
"token": "wonder",
"start_offset": 0,
"end_offset": 6,
"type": "<ALPHANUM>",
"position": 0
},
{
"token": "land",
"start_offset": 7,
"end_offset": 11,
"type": "<ALPHANUM>",
"position": 1
}
]
}
Note: Match query when used on keyword
type field will behave exactly as that of term query
Term Query
Term query returns documents that contain an exact term in a provided field. If you have not defined any explicit index mapping, then you need to add .keyword
to the field. This uses the keyword analyzer instead of the standard analyzer.
When using a keyword analyzer instead of the standard analyzer, wonder-land
will be tokenized into wonder-land
only. In the case of keyword
type fields all the whitespace, special characters in between the words, and case sensitivity is preserved.
To get the correct result of the term query (in case you have defined the field type to be of type text
), you can follow the below methods
- If you have defined index mapping, then modify the mapping for
field1
as shown below. You need to use multi-fields if you want to map the field astext
andkeyword
types. Update your index mapping as shown below and then don't forget to reindex your data.
PUT /<index-name>/_mapping
{
"properties": {
"field1": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword"
}
}
}
}
}
- Otherwise, you can create a new index with the below mapping and then index the data in the new index.
PUT /<new-index-name>
{
"mappings": {
"properties": {
"field1": {
"type": "keyword"
}
}
}
}
Note: You can use the case_insensitive
param along with the term query. This parameter will let you decide whether to make the search term case insensitive or not. This parameter was introduced in elasticsearch version 7.10.0