Jane Wayne Jane Wayne - 8 months ago 35
Java Question

how do i issue a raw query using the java client in elasticsearch?

I found a SO post on how to get random records from ElasticSearch at Random order & pagination Elasticsearch.

curl -XGET 'localhost:9200/_search' -d '{
"query": {
"function_score" : {
"query" : { "match_all": {} },
"random_score" : {}

I have stored this file as a resource and load it as follows.

String query = ResourceUtil.getResource("path/to/json/query");
SearchRequestBuilder srb = getSafeClient()
_logger.debug("search = {}", srb.toString());

However, I keep getting a parse failure. When I log the SearchRequestBuilder, I notice that a comma keeps getting prepended as follows.

search = {, "query" : "function_score": { "query": { "match_all": {} }, "random_score": {}} }

The QueryParsingException I see reads as follows.

QueryParsingException[[myindex] [_na] query malformed, must start with start_object

Any ideas on what I am doing wrong? Is it possible to express random query purely using the Java client API? I am using ElasticSearch v1.1.


Nevermind, I tinkered and found how to express the query programmatically. In case anyone is interested the code snippet is below.

FunctionScoreQueryBuilder fsqb = new FunctionScoreQueryBuilder(QueryBuilders.matchAllQuery());
fsqb.add(ScoreFunctionBuilders.randomFunction((new Date()).getTime()));
SearchRequestBuilder srb = getSafeClient()