The query_string query
The query_string
query 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_string
queries. However, if you want Elasticsearch to ignore syntactical errors and go with the job, here’s an alternative: use a simple_query_string
query.
The simple_query_string query
As the name suggests, the simple_query_string
query is a variant of the query_string
query 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 fields
array. The table shown below describes the set of operators that we can use in simple_query_string
.
Unlike the query_string
query, the simple_query_string
query 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_string
query is helpful in such situations.