Elasticsearch queries are categorized into simple, compound, and aggregation types. This secsion details the core simple query operations.
term Query: A single-term query. It searches for the exact condition value in the field's inverted index (if the field is analyzed) or directly in the field value (if not analyzed). A match yields a score of 1.
terms Query: A multi-term query, equivalent to a logical OR of multiple term queries.
match Query: Performs a search after analysis. If the condition value is analyzed in to N terms, matching any one term returns the document.
The behavior depends on the target field's mapping:
* If the field is a keyword type (not analyzed), it executes a term query with the raw condition value.
* If the field is a text type (analyzed), the condition value is analyzed:
(a) If analysis yields one term, a term query is executed.
(b) If analysis yields multiple terms, a terms query (logical OR) is executed by default.
(c) The relationship can be manually set to AND (requiring all analyzed terms to be present) using the operator parameter. The default is or.
match_phrase Query: Does not analyze the condition value. Searches for a contiguous sequence of terms in the document field, matching both order and position.
match_phrase_prefix Query: Similar to match_phrase, but the final term in the condition is treated as a prefix, not requiring a complete word match.
Example: Document field contains i love you. Query condition is i love yo.
match_phrase would not match. match_phrase_prefix would match.
match_bool_prefix Query: Analyzes the condition value, then executes a bool should query. All terms except the last are used for term queries; the last term is used for a prefix query.
match_all Query: Retrieves all documents (primarily for testing).
Full-Text Queries: Utilize analyzers to process text and match against the inverted index (e.g., match, multi_match).
multi_match Query: Applies the same condition to multiple document fields.
Exact Value Queries: Search for data based on exact term values, typically used for keyword, numeric, date, or boolean fields (e.g., ids, range, term).
wildcard Query: Supports wildcard patterns using * (matches zero or more characters) and ? (matches exactly one character).
Understanding Query Behavior and Results
A common challenge is understanding why queries on certain fields fail to return results. The outcome is influenced by field mapping properties, particular the analyzer configuration.
Field Mapping Example: document_title
To illustrate query analysis, consider a field document_title with the following mapping:
"document_title": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256,
"normalizer": "lowercase_normalizer"
},
"pinyin": {
"type": "text",
"analyzer": "pinyin_analyzer"
}
},
"analyzer": "custom_match_analyzer"
}
"custom_match_analyzer": {
"filter": [
"lowercase"
]
}