0

I'm using ES version 6.0.1 and have integrated the Java High level rest client having version 6.0.1 in my application.

I am currently trying to build this script based sorting query using the Java High Level Rest client API of elastic search:

{
  "sort": {
    "_script": {
      "type": "number",
      "script": {
        "lang": "painless",
        "params": {
          "ids": [3, 2, 1570]
        },
        "source": """
          int idsCount = params.ids.size();
          int id = (int)doc['id'].value;
          int foundIdx = params.ids.indexOf(id);
          return foundIdx > -1 ? foundIdx: idsCount + 1;
        """
      }
    }
  }
}

But I couldn't find any documentation regarding the script based sorting queries for the java client. I would appreciate if someone will help me out in implementing the above query using java API.

Evaldas Buinauskas
  • 13,739
  • 11
  • 55
  • 107

1 Answers1

0

I am not sure about ES version 6.0.1. I am using ES version 7.9.0

This works for me.

Map<String, List<int>> params = new HashMap<String, List<int>>();
List<int> list = Arrays.asList(3, 2, 1570);
params.put("ids", list);

SearchRequest searchRequest = new SearchRequest(index);
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder()
            .size(size)
            .from(from);

Script inlineScript = new Script(ScriptType.INLINE, "painless", "int idsCount = params.ids.size();
                                                                 int id = (int)doc['id'].value;
                                                                 int foundIdx = params.ids.indexOf(id);
                                                                 return foundIdx > -1 ? foundIdx: idsCount + 1;", params);
                
ScriptSortBuilder ssb = new ScriptSortBuilder(inlineScript, ScriptSortType.NUMBER).order(SortOrder.ASC);
searchSourceBuilder.sort(ssb);
searchRequest.source(searchSourceBuilder);
searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
SearchHits hits = searchResponse.getHits();
Manonandan S K
  • 462
  • 1
  • 5
  • 17