Constant score query

Elasticsearch supports querying both structured data and full text. While full-text queries need scoring mechanisms to find the best matching documents, structured searches don't need scoring. The constant score query allows us to convert a scoring query that normally runs in a query context to a non-scoring filter contextThe constant score query is a very important tool in your toolbox.

For example, a term query is normally run in a query context. This means that when Elasticsearch executes a term query, it not only filters documents but also scores all of them:

GET /amazon_products/_search
{
"query": {
"term": {
"manufacturer.raw": "victory multimedia"
}
}
}

Notice the text in bold. This part is the actual term query. By default, the query JSON element that contains the bold text defines a query context.

The response contains the score for every document. Please see the following partial response:

{
...,
"hits": {
"total": 3,
"max_score": 5.966147,
"hits": [
{
"_index": "amazon_products",
"_type": "products",
"_id": "AV5rBfasNI_2eZGciIbg",
"_score": 5.966147,
"_source": {
"price": "19.95",
...
}

Here, we just intended to filter the documents, so there was no need to calculate the relevance score of each document.

The original query can be converted to run in a filter context using the following constant_score query:

GET /amazon_products/_search
{
"query": {
"constant_score": {
"filter": {
"term": {
"manufacturer.raw": "victory multimedia"
}
}
}
}
}

As you can see, we have wrapped the original highlighted term element and its child. It assigns a neutral score of 1 to each document by default. Please note the partial response in the following code:

{
...,
"hits": {
"total": 3,
"max_score": 1,
"hits": [
{
"_index": "amazon_products",
"_type": "products",
"_id": "AV5rBfasNI_2eZGciIbg",
"_score": 1,
"_source": {
"price": "19.95",
"description": ...
}
...
}

It is possible to specify a boost parameter, which will assign that score instead of the neutral score of 1:

GET /amazon_products/_search
{
"query": {
"constant_score": {
"filter": {
"term": {
"manufacturer.raw": "victory multimedia"

}
},
"boost": 1.2
}
}
}

What is the benefit of boosting the score of every document in this filter to 1.2? Well, there is no benefit if this query is used in an isolated way. When this query is combined with other queries, using a query such as a bool query, the boosted score becomes important. All the documents that pass this filter will have higher scores compared to other documents that are combined from other queries.

Let's look at the bool query next.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.146.176.254