Suppose a product search should find TVs rated between 4 and 5, then give every matching product the same score instead of ranking by relevance. Use constant_score for that controlled result ordering. section 11.4 section 11.2
constant_score wraps a filter query and assigns its matches a user-selected score through boost. A filter alone produces no meaningful relevance score; constant_score restores a nonzero, identical score for every match. section 11.4 section 8.4.2
Listing 11.17 A constant_score query that produces a static score
GET products/_search
{
"query": {
"constant_score": { #1
"filter": { #2
"range": {
"user_ratings": {
"gte": 4,
"lte": 5
}
}
},
"boost": 5.0 #3
}
}
}
Use the range filter to select products rated from 4 through 5, then set every matching document's score to 5.0 with boost. section 11.4
Combine constant_score with ordinary relevance when a structured condition should influence ranking:
- Place a match query for the main search term in a bool must clause. section 11.4
- Wrap a term or range filter in constant_score to reward matching documents with a fixed boost. section 11.4
- For example, match TVs and add 3.5 to the score of black TVs. section 11.4
Listing 11.18 A bool query with a constant score
GET products/_search
{
"query": {
"bool": {
"must": [{ #1
"match": { #2
"product": "TV"
}
},
{
"constant_score": { #3
"filter": {
"term": {
"colour": "black"
}
},
"boost": 3.5
}
}
]
}
}
}
This bool query combines text relevance for TVs with a constant 3.5 boost for documents whose colour is black. section 11.4
