A keyword field keeps a structured value intact: Elasticsearch does not tokenize or analyze it. Use it when a value should match as a whole rather than as full text, such as an email address, phone number, PIN code, error code, certificate, or status. Searches are therefore binary: a matching value is returned, or it is not; relevance is not the goal. section 4.5.2 section 4.4
Choose keyword when the application needs filtering, sorting, aggregations, or exact term-level lookup. A keyword value enters the inverted index as written, so a query must preserve its spelling and case. For example, a stored certificate value of "R" does not match a term query for "r". section 4.5.2 section 9.2.1
Map an email address as a keyword
Create an explicit mapping when the value must remain whole: PUT faculty { "mappings": { "properties": { "email": { "type": "keyword" } } } } The email field is not analyzed, making it suitable for direct lookup, filtering, sorting, and aggregations rather than partial full-text matching. section 4.5.2
A field can serve both full-text and exact-value needs through a multi-field. Keep the main field as text, then add a keyword subfield and address that subfield by name, such as title.raw or subject.kw. Dynamic mapping may create a default subfield named title.keyword, but explicit mappings let you choose its name. section 4.1.2 section 4.7
Sort a string value through its keyword subfield
A text field cannot be sorted by default. Rather than enable fielddata—which uses heap memory and can cause expensive computations—sort the keyword representation: GET students_temp/_search { "sort": [ { "age.keyword": { "order": "asc" } } ] } Here age.keyword is the untokenized field used by the sort operation. section 4.2.2
Treat the mapping choice as durable. Elasticsearch does not allow an indexed field to change from keyword to text or vice versa. To correct a live mapping, create a new index with the desired schema, reindex data into it, switch the application, and retire the old index after validation. section 4.3.2 section 4.3.3
Listing 15.5 A multi-field query using the keyword type
PUT programming_books3
{
"mappings": {
"properties": {
"title":{
"type": "text",
"fields": {
"raw":{
"type":"keyword" #1
}
}
}
}
}
}
Use this mapping pattern when a title needs both analyzed full-text search and an exact, non-analyzed keyword representation. section 15.1.3
