The query_string uses a parser with strict syntax. Hence, it returns an error if the query term provided contains incorrect syntax. This is different from the simple query string.
Let us look at how we can use the query_string in Elasticsearch.
To understand how to use the query_string query, we will look at a few examples.
Elasticsearch Query_string Usage Examples
In this tutorial, we will use the global kibana_sample_data_flights index.
Example 1
Suppose we want to fetch the documents where the DestCityName is Denver? We can create a simple query as:
The example is a simple query that searches the DestCityName field where the value is Denver.
Here is an illustration of the example resulting records:
We can also implement the above query using the query_string parameter, as shown below:
{
"query": {
"query_string": {
"default_field": "DestCityName",
"query": "Denver"
}
}
}
The above example performs a similar functionality as the single-liner one shown previously. However, the one above is more readable and easy to expand and apply filters.
Example 2
We can also use Boolean operators such as where DestCityName is either Denver or Sydney.
To do this, we can perform a query as:
{
"query": {
"query_string": {
"default_field": "DestCityName",
"query": "(Sydney) OR (Denver)"
}
}
}
In the example above, the DestCityName can be either Denver or Sydney.
Example output:
Example 3
Suppose you want to get the documents where the flight time is greater than 10 hrs but less than 15 hrs.
In such an example, we can use Boolean AND as shown:
{
"query": {
"query_string": {
"default_field": "FlightTimeHour",
"query": "(>=10) AND (<=15)"
}
}
}
The resulting documents include:
Example 4
Suppose we want to search multiple fields? We can pass the target fields using the fields in an array as:
{
"query": {
"query_string": {
"fields": ["DestCityName", "DestWeather"],
"query": "Denver AND Rain"
}
}
}
In the example above, we search for documents where the DestCityName is Denver and DestWeather is Rain.
We can get example results as:
Closing
This guide taught you to use the Elasticsearch query_string query to fetch documents matching a specific query string.