Reputation: 3036
I am performing a Query String Query on a Text
Field. When I use a query with wrong syntax (e.g., "/xyz"
) I get an exception indicating that ElasticSearch failed to parse the query on all shards:
Caused by: java.util.concurrent.ExecutionException: RemoteTransportException[[PZCU_1Z][127.0.0.1:9300][indices:data/read/search]]; nested: SearchPhaseExecutionException[all shards failed]; nested: QueryShardException[Failed to parse query [/xyz]]; nested: NotSerializableExceptionWrapper[parse_exception: Cannot parse '/xyz': Lexical error at line 1, column 5. Encountered: <EOF> after : "/xyz"]; nested: NotSerializableExceptionWrapper[token_mgr_error: Lexical error at line 1, column 5. Encountered: <EOF> after : "/xyz"];
Is there a way to detect that this query has a wrong syntax before performing the query itself. Something like parsing the query in advance or matching it against a regular expression?
Update:
Sorry if my question was unclear. I am aware of the fact that this query has a wrong syntax as it uses some of the reserved characters and it, actually, was intended to be used as a regex query. What I need though is to provide a meaningful error message to the client indicating that his query has a wrong syntax before performing the query.
Upvotes: 2
Views: 1414
Reputation: 217304
The forward slash is a reserved character in the query string query syntax for searching via regular expressions, so you need to escape it.
Instead of "/xyz"
you need to use "\\/xyz"
Note that not even Kibana parses the user input for correctness. If you want to check beforehand that the query is valid, you could use Lucene's StandardQueryParser
to try to parse the query before sending it to ES.
Handing out the power of the query string to end users is dangerous. If you really need to provide them with some kind of free text search, consider using simple_query_string
instead, as it will not throw any exceptions.
Upvotes: 2