Understanding query_string and simple_query_string Queries

Madhusudhan Konda
3 min readJan 29, 2023
Excerpts taken from my upcoming book: Elasticsearch in Action

Me @ Medium || LinkedIn || Twitter || GitHub

The query_string query

The query_stringquery is strict on syntax, and errors in the input are not forgiven. For example, the following query in the next listing throws an error because the input has some parsing issues (purposely, we added a quote to the input criteria).

GET books/_search
{
"query": {
"query_string": {
"query": "title:Java\""
}
}
}

This query will not be parsed. Elasticsearch throws an exception, mentioning that the syntax was violated:

"error" : {
"root_cause" : [{
"type" : "json_parse_exception",
"reason" : "Unexpected character ('\"' (code 34)): was expecting comma to separate Object entries\n at ...]"
}],
...
}

The query threw a JSON parse exception to the user, thus validating the stricter syntax for query_stringqueries. However, if you want Elasticsearch to ignore syntactical errors and go with the job, here’s an alternative: use a simple_query_stringquery.

The simple_query_string query

As the name suggests, the simple_query_stringquery is a variant of the query_stringquery with a simple and limited syntax. We can use operators such as +, -, |, *, ~ and so forth for constructing the query. For example, searching for “Java + Cay” produces a Java book written by Cay as the next listing shows.

GET books/_search
{
"query": {
"simple_query_string": {
"query": "Java + Cay"
}
}
}

The + operator in the query allows the query to search for Java AND Cay across all fields. We can specify the fields if we want to check a set of fields instead of all the fields by setting the fieldsarray. The table shown below describes the set of operators that we can use in simple_query_string.

Table : Operators for a simple query string

Unlike the query_stringquery, the simple_query_stringquery doesn’t respond with errors if there’s any syntax error in the input criteria. It takes a quieter side of not returning anything should there be a syntactic error in the query as the code in the following listing demonstrates.

GET books/_search
{
"query": {
"simple_query_string": {
"query": "title:Java\""
}
}
}

Though the same query with incorrect syntax (extra quote at the end) was issued, there is no error returned to the user, except no return documents. The simple_query_stringquery is helpful in such situations.

Me @ Medium || LinkedIn || Twitter || GitHub

These short articles are condensed excerpts taken from my book Elasticsearch in Action, Second Edition. The code is available in my GitHub repository.

Elasticsearch in Action

--

--

Madhusudhan Konda
Madhusudhan Konda

Written by Madhusudhan Konda

Madhusudhan Konda is a full-stack lead engineer, mentor, and conference speaker. He delivers live online training on Elasticsearch, Elastic Stack &Spring Cloud

No responses yet