-1

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()
    .prepareSearch("myindex")
    .setTypes("mytype")
    .setQuery(query);
_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.

Community
  • 1
  • 1
Jane Wayne
  • 8,205
  • 17
  • 75
  • 120

1 Answers1

0

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()
 .prepareSearch("myindex")
 .setTypes("mytype")
 .setQuery(fsqb);
Paul Mougel
  • 16,728
  • 6
  • 57
  • 64
Jane Wayne
  • 8,205
  • 17
  • 75
  • 120