8.1.0 Java Client - SearchRequest example

Hi, I'm struggling to understand how to do convert my code from the HLRC to the new Elasticsearch Java API Client.

Could someone please give me an example? The documentation is very unclear on this subject.

Fonctional HLRC code:

SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
SearchHits searchHits = response.getHits();

// Count the total of hits to determine terms frequency
LinkedHashMap<Integer, Integer> mapFrequency = new LinkedHashMap<Integer, Integer>();
for (SearchHit hit : searchHits.getHits()) {
    Integer id = Integer.valueOf(hit.getId());
    Integer termsFrequency = 0;

    HighlightField fieldFR = hit.getHighlightFields().get(FIELD_CV_FR);
    HighlightField fieldEN = hit.getHighlightFields().get(FIELD_CV_EN);

    Integer hlFR = (fieldFR != null) ? fieldFR.getFragments().length : 0;
    Integer hlEN = (fieldEN != null) ? fieldEN.getFragments().length : 0;
    termsFrequency = (hlFR >= hlEN) ? hlFR : hlEN;

    mapFrequency.put(id, termsFrequency);
}

What I've tried so far:

try {
SearchResponse<CVDocument> response = this.client.search(b -> b
    .index(DOCUMENTS_INDEX)
    .highlight(highlightBuilder.build())
    .source(sourceBuilder),
    CVDocument.class
);

// Count the total of hits to determine terms frequency
LinkedHashMap<Integer, Integer> mapFrequency = new LinkedHashMap<Integer, Integer>();
for (CVDocument hit : response.hits()) {
    // foreach not applicable to type 'co.elastic.clients.elasticsearch.core.search.HitsMetadata<com.intl.service.CVDocument>'
}

My object representing my index :

@Data
class CVDocument {
    @JsonProperty("_id")
    private Integer id;

    @JsonProperty("cvFR")
    private Integer cvFR;

    @JsonProperty("cvEN")
    private Integer cvEN;
}

Can someone help me translate my code and give me a concrete example please?

You probably need to write:

for (Hit<CVDocument> hit : response.hits().hits) {
  
}

Excellent! Looks like it works! Thank you @dadoonet

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