Java: Getting the average of a calculation

Hi,

I am using ElasticSearch 6.3 and I want to do a calculation on two fields and get the average of the results.

First I tried with org.elasticsearch.client : transport as noted in the doc, but noticed some things were deprecated in favor of the high level rest api.

So I tried with this:

RestHighLevelClient client = new RestHighLevelClient(
	RestClient.builder(
    	new HttpHost("hostname", 443, "https")));

I tried a simple subtract:

SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); 
 searchSourceBuilder.query(QueryBuilders.scriptQuery(new Script("doc['someFieldName'].value  - doc['someOtherFieldName'].value")));

SearchRequest searchRequest = new SearchRequest(); 
searchRequest.source(searchSourceBuilder);
SearchResponse searchResponse = client.search(searchRequest);

SearchHits hits = searchResponse.getHits();
SearchHit[] searchHits = hits.getHits();
for (SearchHit hit : searchHits) {
System.out.println(hit.toString());
	}

client.close();

I got a huge amount of errors like:
"search_phase_execution_exception","reason":"all shards failed"

Even when I added a simpler script I got the same:
searchSourceBuilder.query(QueryBuilders.scriptQuery(new Script("doc['someFieldName'].value")));

So the questions are:
-How to specify in the above which index I am searching in?
-How to add other fields to filter to the above? Like I want to add a filter to search only where the xyzField=TestValue
-How to specify a time range in the mentioned query?

Many thanks,
TZ

Your script does not generate a boolean value AFAICS. I believe this is the problem.
Note that if you share the full error message we might be able to tell more or confirm.

Few advices:

  • before going to the java code, I'd try to solve everything with a simple Kibana script which runs in the dev console. Once you have it working, you can work on translating the code to Java. We can help for that.
  • do not use scripts if you can avoid them. Like if you can compute things at index time like x = b - a, that will be a great win.
  • upgrade. 6.3 is super old. Go to 6.8 or better 7.2. Also the java rest client is completely implemented in 6.8/7.2 which might not be the case with a 6.3 client.

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.