Medium search elasticsearch

Why does searching across many fields slow Elasticsearch down, and how does copy_to help?

The 30 second answer

A multi-match query runs the search once per field and then combines the scores, so twenty fields means roughly twenty searches. The docs say the more fields a query targets, the slower it is. With copy_to, I copy the values of those fields into one combined field at index time and search just that field. I keep a few important fields separate, like the title, so I can still boost them.

Could you say this in an interview?

What happens with many fields. A multi_match or query_string query over name, brand, color, material, description and so on searches each field's inverted index separately, then combines the scores. More fields means more lookups and more scoring work on every request. The Elasticsearch guide says: the more fields a query_string or multi_match query targets, the slower it is.

copy_to. In the mapping, mark each field with copy_to pointing at one combined field. At index time, Elasticsearch adds the values to that field as well, and the search targets only it. The original fields stay indexed too, so you can still filter on them or search them alone. The docs note that this costs extra storage.

Keep relevance in mind. One combined field can't boost "the word appears in the title" above "the word appears in the description". A common design is a combined field for broad recall, plus a few important fields such as name and brand, searched with boosts. That's a handful of fields instead of twenty.

Related trick from the same guide. Search only the fields you need, and avoid broad patterns like "fields": ["*"]. Each extra field adds work on every shard.

PUT products
{ "mappings": { "properties": {
    "all_text": { "type": "text" },
    "name":     { "type": "text", "copy_to": "all_text" },
    "brand":    { "type": "text", "copy_to": "all_text" },
    "color":    { "type": "text", "copy_to": "all_text" },
    "material": { "type": "text", "copy_to": "all_text" }
}}}

GET products/_search
{ "query": { "multi_match": { "query": "red leather boots",
    "fields": ["all_text", "name^3", "brand^2"] } } }

Alternate interview scenarios

"Product teams keep adding fields to the search request, and latency keeps creeping up."

Own the field list in the search API layer, measure each field's effect on relevance and latency, and fold low-value fields into a copy_to field.

"Shoppers search 'red Nike' and want both color and brand to count."

A combined field matches both words in one place. Keep brand as a boosted separate field so a brand match still ranks higher.

Sources (3)
  1. Elasticsearch docs: Tune for search speed (search as few fields as possible)elastic.co
  2. Elasticsearch docs: copy_toelastic.co
  3. Elasticsearch docs: Multi-match queryelastic.co