4
votes

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.

1

1 Answers

11
votes

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...
});