Term query

How would you find all of the products made by a particular manufacturer? We know that the manufacturer field in our data is of the string type. The name of a manufacturer can possibly contain whitespaces. What we are looking for here is an exact search. For example, when we search for victory multimedia, we don't want any results that have a manufacturer that contains just victory or just multimedia. You can use a term query to achieve that.

When we defined the manufacturer field, we stored it as both text and keyword fields. When doing an exact match, we have to use the field with the keyword type:

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

The term query is a low-level query in the sense that it doesn't perform any analysis on the term. Also, it directly runs against the inverted index constructed from the mentioned term field; in this case, against the manufacturer.raw field. By default, the term query runs in the query context and hence calculates scores.

The response looks like the following (only the partial response is included):

{
...
"hits": {
"total" : {
"value" : 3,
"relation" : "eq"
},
"max_score": 5.965414,
"hits": [
{
"_index": "amazon_products",
"_type": "products",
"_id": "AV5rBfPNNI_2eZGciIHC",
"_score": 5.965414,
...

As we can see, each document is scored by default. To run the term query in the filter context without scoring, it needs to be wrapped inside a constant_score filter:

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

This query will now return results with a score of one for all matching documents. We will look at the constant_score query later in the chapter. For now, you can imagine that it turns a scoring query into a non-scoring query. In all queries where we don't need to know how well a document fits the query, we can speed up the query by wrapping it inside constant_score with a filter. There are also other types of compound queries that can help in converting different types of queries and combining other queries; we will look at them when we examine compound queries.

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

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