0
0
Elasticsearchquery~3 mins

Why Constant score query in Elasticsearch? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

Discover how to make your searches lightning-fast by skipping complicated scoring!

The Scenario

Imagine you want to find all documents about "coffee" in a huge database, but you don't care about how relevant each document is, just that it matches. Doing this manually means writing complex queries and then adjusting scores yourself.

The Problem

Manually adjusting scores or relevance is slow and tricky. You might spend hours tweaking weights and still get inconsistent results. It's easy to make mistakes and hard to maintain.

The Solution

The constant score query lets you wrap any filter and assign the same score to all matching documents. This means you get fast, simple results without worrying about relevance calculations.

Before vs After
Before
GET /_search
{
  "query": {
    "bool": {
      "filter": { "term": { "type": "coffee" } },
      "must": { "match": { "description": "coffee" } }
    }
  }
}
After
GET /_search
{
  "query": {
    "constant_score": {
      "filter": { "term": { "type": "coffee" } },
      "boost": 1.0
    }
  }
}
What It Enables

You can quickly filter documents with a fixed score, making searches faster and simpler when relevance doesn't matter.

Real Life Example

For example, an online store wants to show all products in the "coffee" category equally, without ranking by popularity or reviews.

Key Takeaways

Manual scoring is complex and error-prone.

Constant score query assigns the same score to all matches.

This simplifies filtering when relevance is not needed.