How to synchronize current thread with SubmitAsyncSearchRequest?

Hi, guys. Thank you for building such wonderful tools. :grinning:

While I was coding with the guidance of the [SubmitAsyncSearchRequest document](https://www.elastic.co/guide/en/elasticsearch/client/java-rest/current/java-rest-high-asyncsearch-asyncsearch-submit.html), I didn't know what to do in order to wait for the response from the current thread in the context as below.

    @Async
	@CrossOrigin  
	@GetMapping(path="/my/path/{docId}")
	public @ResponseBody ResponseEntity<Result> getAsyncResult(
		@PathVariable Integer docId
	) {
		ClientConfiguration clientConfiguration = ClientConfiguration.builder().connectedTo("localhost:9200").build();
        RestHighLevelClient client = RestClients.create(clientConfiguration).rest();

		SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
		SearchSourceBuilder searchSource = searchSourceBuilder.query(QueryBuilders.matchQuery("_id", docId));
		String[] indices = new String[] {"my_index"};
		SubmitAsyncSearchRequest request
			= new SubmitAsyncSearchRequest(searchSource, indices);

		request.setWaitForCompletionTimeout(TimeValue.timeValueSeconds(1));
		request.setKeepAlive(TimeValue.timeValueDays(365));
		request.setKeepOnCompletion(true);
		
		AsyncSearchClient asyncClient = client.asyncSearch();
		Result result = new Result();

		ActionListener<AsyncSearchResponse> actionListner
			 = new ActionListener<AsyncSearchResponse>() {
				 @Override
				 public void onResponse(AsyncSearchResponse response) {
					if (response.isPartial() == true) {
						logger.info("The response is PARTIAL!");
					} else {
						logger.info("The response is COMPLETE!");
					}

					SearchResponse searchResponse = response.getSearchResponse();
					if (searchResponse != null) {
						SearchHit[] searchHits = searchResponse.getHits().getHits();

						int numHits = searchHits.length;
						logger.info("******* No. hits: " + numHits);

						if (numHits > 0) {
							for (int i=0; i<numHits; i++) {
								logger.info("[" + i + "] : " + searchHits[i].getId());

								String jsonString = searchHits[i].getSourceAsString();

								logger.info(">>> The raw string: " + jsonString);
								
//  SOME BUSINESS LOGIC filling `result`.

							}	// END: for (~)
							logger.info("******* ABOVE: Hit IDs");
						}	// END: if (numHits > 0)
					}	// END: if (searchResponse != null)
				 }	// END: public void onResponse(AsyncSearchResponse response)

				 @Override
				 public void onFailure(Exception e) {
					String expMsg = e.getMessage();
					logger.error("Async Request Failed for error: " + expMsg);
				 }	// END: public void onFailure(Exception e)
			 };		// END: new ActionListener<AsyncSearchResponse>(){}
		
		Cancellable cancellable = asyncClient.submitAsync(request, RequestOptions.DEFAULT, actionListner);
		
		// cancellable.cancel();
		
		// TODO: Wait for request to be done. If the onResponse() finishes, then continue to below. 

		ResponseEntity<Result> result0 = null;
		
		result0 = (result.filled()  == true) ? new ResponseEntity<Result>(minute, HttpStatus.OK)
		: new ResponseEntity<Result>(HttpStatus.INTERNAL_SERVER_ERROR);

		logger.info("BEFORE RETURNING");

		return result0;
	}

According to those log messages, always BEFORE RETURNING appears before the ones in onResponse().

But, I want the current thread(?) to wait until onResponse() is done.

What am I supposed to do?

Thank you for reading my question and answering in advance! :smile:

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