Elasticsearch Queries

Here you can find practical Elasticsearch queries on real data. Note that these queries only used for educational purpose.

Simple Match Query

This is a simple match query that only returns documents where the specified field matches the given text value.


GET /users/_search
{
"query": {
    "match": {
    "firstName": "Max"
     }
    }
}
        

Match Query with Options

You can use the match query with options to specify how the query should behave. For example, you can use the operator:OR option to match documents containing either of the specified terms.


GET /users/_search
{
"query": {
    "match": {
    "address": {
        "query": "tehran london",
        "operator": "or"
    }
    }
}
}
        

use operator: and
The following query will match documents containing both tehran AND london.

GET /users/_search
{
    "query": {
    "match": {
        "address": {
        "query": "tehran azadi",
        "operator": "and"
        }
    }
    }
}
    

"fuzziness": 2,
"operator": "and"


In the following example, add the fuzziness parameter, permitting a maximum of 2 edits per word, which results in increasing the number of returned hits, while changing the relevance of the results. it can get Tehran or Tehran in iran ...

GET /users/_search
{
    "query": {
    "match": {
        "address": {
        "query": "tehran iran",
        "fuzziness": 2, 
        "operator": "and"
        }
    }
    }
}
                    

"minimum_should_match": 2,
"operator": "or"


An optional parameter of type string that represents the minimum number of matching clauses for a document to be returned. minimum 2 words to be matched in this example it can return docs with Tehran paris or Tehran iran or paris London ...

GET /users/_search
{
    "query": {
    "match": {
        "address": {
        "query": "tehran iran paris london",
        "minimum_should_match": 2, 
        "operator": "or"
        }
    }
    }
}
                    

Structure of bool query

structure of bool query


"bool": {
    "must": [],
    "must_not": [],
    "filter": [],
    "should": [],
    "minimum_should_match" : 1
}
            

show usage of must and should example

following query will return users with firstName: hamed and his address is iran or france

and the sort will shuffle the order of docs


GET /users/_search
{
    "query": {
        "bool": {
            "must": [
                {
                    "term": {"firstName": "hamed"}
                },
                {
                    "bool": {
                        "should": [
                            {"term": {"address": "iran"}},
                            {"term": {"address": "france"}}
                        ]
                    }
                }
            ]
        }
    },
    "sort": {
        "_script": {
            "type": "number",
            "script": {
                "source": "Math.random()",
                "lang": "painless"
            },
            "order": "asc"
        }
    }
}
                
                            

Match phrase query

Word proximity is taken into account by the match phrase query, which requires the words to be located within a customizable "slop" or distance. The match phrase example below searches the people index for users with the phrase "john" in their firstName.


GET /users/_search
{
  "query": {
    "match_phrase": {
      "firstName": "Max"
    }
  }
}
                    

Note: Phrase matching cannot be utilized with fuzzy search.


The following query will match: it will return tehran country iran, tehran everything iran but it don't return tehran some word iran


GET /users/_search
{
  "query": {
    "match_phrase": {
      "address": {
        "query": "Tehran iran",
        "slop": 1 
      }
    }
  }
}
                    

Multi match query

the following search to lookup a single word over several fields.


GET /users/_search
{
    "query": {
    "multi_match": {
        "query": "william",
        "fields": [
        "address",
        "firstName",
        "lastName"
        ]
    }
    }
}
                                    

Wildcards can be used to specify fields as shown in the example below (*Name)


GET /users/_search
{
    "query": {
    "multi_match" : {
        "query":    "william",
        "fields": [ "address", "*Name" ] 
    }
    }
}
            

The caret (^) notation can be used to boost scores of specific fields. In the following example, the address field receives a boost of 2.


GET /users/_search
{
    "query": {
    "multi_match": {
        "query": "william",
        "fields": [
        "address^2",
        "firstName"
        ]
    }
    }
}
                            

*. * extracting all fields from the mapping that are appropriate for term queries, in addition to filtering the metadata fields.


GET /users/_search
{
    "query": {
    "multi_match": {
        "query": "william",
        "fields": [
        "*.*"
        ]
    }
    }
}
                

- Best fields: This setting finds documents that match any field while using the score from the field with the highest score. The best fields type is the most useful when looking for numerous terms that are most frequently found in a single field. "android programming" in a single field is more pertinent than android in one field and programming in another, as seen in the example below.


GET /users/_search
{
    "query": {
        "multi_match": {
        "query": "android programming",
        "type":       "best_fields",
        "fields": [
            "skills",
            "abilites"
        ],
        "tie_breaker": 0.3
        }
    }
}                    
                                    

The primary field may contain stems, synonyms, and terms without diacritics, as demonstrated in the example below. Shingles may be in a third field, and the original phrases may be in a second field. By combining the scores from the three fields, which enables the matching of as many documents with the primary field as is possible, the most comparable results are pushed to the top of the list using the second and third fields.


GET /users/_search
{
  "query": {
    "multi_match" : {
      "query":      "data mining",
      "type":       "most_fields",
      "fields":     [ "title","title.shingles", "title.original" ]
    }
  }
}
                                    

– Cross_fields: All fields with the same analyzer should be treated as if they were one big field.


GET /users/_search
{
    "query": {
    "multi_match" : {
        "query":      "william max",
        "type":       "cross_fields",
        "fields":     [ "firstName", "lastName" ],
        "operator":   "and"
    }
    }
}
                                

Working with Array

1- Querying for documents with a specific ability type:
This query will retrieve all documents that have an ability with the type "strength" in the "abilities" nested field.


GET /users/_search
{
    "query": {
    "nested": {
        "path": "abilities",
        "query": {
        "bool": {
            "must": [
            {"match": {"abilities.type": "strength"}}
            ]
        }
        }
    }
    }
}
                                

Querying for documents with abilities that have a certain percent value:
This query will retrieve all documents that have an ability in the "abilities" nested field with a percent value greater than or equal to 80.


GET /users/_search
{
    "query": {
        "nested": {
        "path": "abilities",
        "query": {
            "bool": {
            "must": [
                {"range": {"abilities.percent": {"gte": 80}}}
             ]
            }
         }
        }
     }
    }
                                                

Sorting documents by province rank of their abilities:
This query will retrieve all documents that have an ability in the "abilities" nested field and sort them by the province rank of the ability in ascending order.


GET /users/_search
{
    "query": {
        "nested": {
            "path": "abilities",
            "query": {
            "match_all": {}
            }
        }
    },
    "sort": [
        {"abilities.provinceRank": {"order": "asc"}}
    ]
}
            

To add an additional condition to your query, you can use the bool query with a must clause to require that both the nested query and the new query condition must match in order for the document to be retrieved.
This query will retrieve all documents that have an ability percent greater than 60 and less than 95 in the "abilities" nested field and an address field that contains both "tehran" and "Iran".


GET /users/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "nested": {
            "path": "abilities",
            "query": {
              "bool": {
                "must": [
                    {"range": {"abilities.percent": {"gte": 60,"lte": 95}}}
                  ]
              }
            }
          }
        },
        {
          "bool": {
            "must": [
              {"match_phrase": {"address": "tehran"}},
              {"match_phrase": {"address": "iran"}}
            ]
          }
        }
      ]
    }
  }
}
                            

it is possible to sort every object in the abilities array in ascending order based on the value of the provinceRank field. To achieve this, you can add the inner_hits parameter to the nested query and specify a sort order for the inner hits. Here's an example query that should give you the desired result:
This query will retrieve all documents that have an ability in the abilities nested field and sort each ability object within the array by the provinceRank field in ascending order. The inner hits will be returned as a separate response section, which you can access using the hits.inner_hits field in your search response.


GET /users/_search
{
    "query": {
        "nested": {
        "path": "abilities",
        "query": {
            "match_all": {}
        },
        "inner_hits": {
            "sort": [
            {"provinceRank": {"order": "asc"}}
            ]
         }
        }
    }
}
                            

combine Q19 and Q17


GET /users/_search
{
    "query": {
        "nested": {
        "path": "abilities",
        "query": {
            "match_all": {}
        },
        "inner_hits": {
            "sort": [
                {"provinceRank": {"order": "asc"}}
                ]
            }
        }
    }
}
             

if we are looking for someone has python ability and the percent of his/her ability between 80 and 90 we can use following query:


GET /users/_search
{
    "query": {
    "nested": {
        "path": "abilities",
        "query": {
        "bool": {
            "must": [
            {
                "match_phrase": {
                "abilities.title": "python"
                }
            },
            {
            "range": {
                "abilities.percent": {
                "gte": 80,
                "lte": 90
                }
            }
            }
            ]
        }
        }
    }
    }
}
            

below query look like last query but we said find everyone that exist in iran


GET /users/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "nested": {
            "path": "abilities",
            "query": {
              "bool": {
                "must": [
                  {
                    "match_phrase": {
                      "abilities.title": "python"
                    }
                  },
                  {
                    "range": {
                      "abilities.percent": {
                        "gte": 80,
                        "lte": 90
                      }
                    }
                  }
                ],
                "must_not": [
                  {
                    "match_phrase": {
                      "abilities.title": "GitLab"
                    }
                  }
                ]
              }
            }
          }
        },
        {
          "match": {
            "address": "iran"
          }
        }
      ]
    }
  }
}