Elasticsearch Spring JSONObject[“hits”] not found

I'm trying to do full text query search on if i GET http://localhost:8080/search/query/tes it should show users include tes in first or last name. i implemented them. but something is wrong, it says hits not found (JSONObject["hits"] not found). Spring Boot with Elasticsearch





`
@Service
public class SearchService implements ISearchService {

@Value("${api.elasticsearch.uri}")
private String elasticSearchUri;

@Value("${api.elasticsearch.search}")
private String elasticSearchSearchPrefix;

private static final Logger LOGGER = LoggerFactory.getLogger(SearchService.class);

@Override
public ResultQuery searchFromQuery(String query) throws IOException {
String body = HelperFunctions.buildMultiIndexMatchBody(query);
return executeHttpRequest(body);
}

/**

  • Fetch resultQuery from elastic engine for the given body

  • @param body String

  • @return ResultQuery

  • @throws IOException IOException
    */
    private ResultQuery executeHttpRequest(String body) throws IOException{
    try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
    ResultQuery resultQuery = new ResultQuery();
    HttpPost httpPost = new HttpPost(HelperFunctions.buildSearchUri(elasticSearchUri
    , "", elasticSearchSearchPrefix));
    httpPost.setHeader(Accept, application/json);
    httpPost.setHeader(Content-type, application/json);
    try {
    httpPost.setEntity(new StringEntity(body, UTF-8));
    HttpResponse response = httpClient.execute(httpPost);
    String message = EntityUtils.toString(response.getEntity());
    JSONObject myObject = new JSONObject(message);
    if(myObject.getJSONObject(hits)
    .getInt(total) != 0){
    resultQuery
    .setElements(myObject
    .getJSONObject(hits)
    .getJSONArray(hits)
    .toString());
    resultQuery
    .setNumberOfResults(myObject.getJSONObject(hits)
    .getInt(total));
    resultQuery.setTimeTook((float) ((double) myObject.getInt(took) / 1000));
    } else {
    resultQuery.setElements(null);
    resultQuery.setNumberOfResults(0);
    resultQuery.setTimeTook((float) ((double) myObject.getInt(took) / 1000));
    }
    } catch (IOException | JSONException e) {
    LOGGER.error("Error while connecting to elastic engine --> {}", e.getMessage());
    resultQuery.setNumberOfResults(0);
    }

     return resultQuery;
    

    }
    }

}
`

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