Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Elastic Search Results to POJO

I have a project using the spring-data-elasticsearch library. I've got my system returning results, but I was wondering how to get my results in the form of my domain POJO class.

I'm not seeing too much documentation on how to accomplish this, but I don't know what the right question I should be Googling for.

Currently, my code looks like this, and in my tests, it retrieves the right results, but not as a POJO.

    QueryBuilder matchQuery = QueryBuilders.queryStringQuery(searchTerm).defaultOperator(QueryStringQueryBuilder.Operator.AND);

    Client client = elasticsearchTemplate.getClient();

    SearchRequestBuilder request = client
            .prepareSearch("mediaitem")
            .setSearchType(SearchType.QUERY_THEN_FETCH)
            .setQuery(matchQuery)
            .setFrom(0)
            .setSize(100)
            .addFields("title", "description", "department");
    System.out.println("SEARCH QUERY: " + request.toString());

    SearchResponse response = request.execute().actionGet();
    SearchHits searchHits = response.getHits();
    SearchHit[] hits = searchHits.getHits();

Any help is greatly appreciated.

like image 843
Black Dynamite Avatar asked Dec 19 '22 05:12

Black Dynamite


1 Answers

One option is to use jackson-databind to map JSON from the search hits to POJOs.

For example:

ObjectMapper objectMapper = new ObjectMapper();
SearchHit[] hits = searchHits.getHits();
Arrays.stream(hits).forEach(hit -> {
    String source = hit.getSourceAsString();
    MediaItem mediaItem = objectMapper.readValue(source, MediaItem.class);
    // Use media item...
});
like image 79
ck1 Avatar answered Jan 12 '23 00:01

ck1