Search and Elasticsearch learning path Level 1 This level · 6 of 6
Easy search elasticsearch

Should a product ID be mapped as a number or a keyword in Elasticsearch?

The 30 second answer

Usually keyword. A product ID looks like a number, but you never ask for IDs between two values. You look up exact IDs. Elasticsearch optimizes numeric fields for range queries, while keyword fields are better for exact term lookups, and the docs say to map identifiers like product IDs as keyword. Keep a numeric type only for real quantities such as price or stock, or add both through multi-fields.

Could you say this in an interview?

Two different index structures. Elasticsearch stores the two field types differently:

  • Numeric fields (integer, long and so on) are stored in a tree structure built for ranges, called a BKD tree. "Price between 20 and 50" is fast.
  • Keyword fields go into the inverted index, a sorted list of exact terms. "ID equals 123456" is a direct lookup.

So the question is how the field is used, not whether its values look like numbers.

What the docs say. The numeric field page says that not all numeric data should be mapped as a numeric type. Numeric fields are optimized for range queries, keyword fields are better for term and other term-level queries, and identifiers such as an ISBN or a product ID are rarely used in range queries. The search-speed guide repeats this as "consider mapping identifiers as keyword".

Other reasons keyword is the safer choice for IDs.

  • IDs can have leading zeros (000123), letters added later (SKU-123) or values larger than a long can hold. A keyword keeps the exact string.
  • Facets and terms aggregations on IDs work naturally on keyword fields.
  • It matches the reel's SQL example: comparing a text column with an unquoted number breaks index use. Keep the stored type and the query type consistent.

When you need both. If someone really does need ranges, for example order numbers in a range during an investigation, use multi-fields: a keyword main field for lookups plus a long sub-field for ranges.

PUT products
{ "mappings": { "properties": {
    "product_id": { "type": "keyword",
                    "fields": { "num": { "type": "long" } } },
    "price":      { "type": "scaled_float", "scaling_factor": 100 }
}}}

Alternate interview scenarios

"Searching for ID 00123 finds nothing."

It was indexed as a number, so the leading zeros were lost. Store IDs as keyword strings exactly as the source system produces them.

Sources (3)
  1. Elasticsearch docs: Numeric field types (mapping numeric identifiers)elastic.co
  2. Elasticsearch docs: Tune for search speed (consider mapping identifiers as keyword)elastic.co
  3. Elasticsearch docs: Multi-fieldselastic.co
Previous
Next