Search elasticsearch with java client using JSON query

Here is an update for current ES API on master (untested)

String content = "{\"query\":{\"match_all\":{}}}";
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
SearchModule searchModule = new SearchModule(Settings.EMPTY, false, Collections.emptyList());
try (XContentParser parser = XContentFactory.xContent(XContentType.JSON)
                .createParser(NamedXContentRegistry.EMPTY, content)) {
    searchSourceBuilder.parseXContent(new QueryParseContext(parser));
}
SearchRequestBuilder searchRequestBuilder = new SearchRequestBuilder(client, SearchAction.INSTANCE);
SearchResponse searchResponse = searchRequestBuilder.setSource(searchSourceBuilder)
            .execute().actionGet();

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.

4 Likes