SearchResponse response =
client.prepareSearch()
.setIndices("myindex")
.setTypes("log-type")
.setSearchType(SearchType.QUERY_AND_FETCH)
.setQuery(query) //query is of type QueryBuilder
.execute().actionGet();
But not able to covert the json-string to QueryBuilder object properly. Can you help me on this?
Hi Jörg,
this snippet doesn't work in ES 5.2.0. The Createparser method needs an additional NamedXContentRegistry. Also getQueryParserRegistry() doesn't exist anymore and the parseFieldMatcher is deprecated and will possibly break in the future.
I think it should be possible to query a json query with the offical api without touching the ES internals.
The idea is to peek into the source code and see how RestSearchAction works. RestSearchAction must always translate an external JSON string into ES SearchRequest Java API. Unwrapping the code paths around RestSearchAction, and following a pattern where XContentParser runs over the JSON string and passes the result to the SearchSourceBuilder method that accepts XContent should do the trick. The example is of course a simplification and can not handle all real-world queries.
Your mileage may vary if you need to deal also with custom query/aggregations plugins, they have to be registered via SearchModule, and plugins might bring in other complications. For instance, "ext": { ... } won't work, see SearchExtBuilder. The ES developers have added some data binding features to XContent API, but I assume NamedXContentRegistry.EMPTY is safe as long as only ordinary JSON-encoded queries are parsed.
Unfortunately NamedXContentRegistry.EMPTY doesn't work for parsing QueryBuilders without registering the built-in queries first, but they should be available through searchModule.getNamedXContents(). So to create the parser in the above example you can use
I don't understand what the need is for using the java api, yet sending json requests that are manually handled. The java api helps sending request and composing them using its own objects. I would recommend to move over to the low level rest client for these cases where json is sent instead.
Query parsing was moved to the coordinating node with 5.0 and the java api must now send parsed objects. I wouldn't recommend doing the parsing on the client side, that is a work-around that may not work in the future. The on thing that should work though is using WrapperQueryBuilder, which allows to provide a query (not the whole search request, only the query part of it) as a string, and its parsing is actually performed on the data nodes rather than on the coordinating node.
Apache, Apache Lucene, Apache Hadoop, Hadoop, HDFS and the yellow elephant
logo are trademarks of the
Apache Software Foundation
in the United States and/or other countries.