I'm using a spring ElasticsearchRepository to query Elasticsearch:
@Repository
public interface MyDocumentRepository extends ElasticsearchRepository<MyDocument, String>{
}
I can successfully run a search query and retrieve a list of elasticsearch results mapped in MyDocument bean
private final MyDocumentRepository myDocumentRepository;
...
Pageable pageable = PageRequest.of(0, 10);
QueryBuilder query = QueryBuilders.boolQuery().must(queryStringQuery("my query"));
SearchQuery searchQuery = new NativeSearchQueryBuilder()
.withQuery(query)
.withPageable(pageable)
.withHighlightFields(
new HighlightBuilder.Field("field1"),
new HighlightBuilder.Field("field2"))
.build();
Iterable<MyDocument> = myDocumentRepository.search(searchQuery);
Although the query sent to elasticsearch and response are correct (I can see the highlight block in the debug log) and results are also appropriate, I do not know how to get the highlight information in my java code.
I would like not to use ElasticsearchTemplate and a ResultExtractor to get the highlight information.
Thanks in advance!
Returning additional information in an SearchHit
is a feature implemented in the current master branch which is available in the snaphot build. It will be released with the next release (4.0)
This is not the SearchHit
class from Elasticsearch but a new introduced class in Spring Data Elasticsearch.
With the current version (3.2.x) this is only possible using a custom result mapper (which will not be available anymore in 4.0)
Edit:
As for the configuration in the upcoming version 4, check https://docs.spring.io/spring-data/elasticsearch/docs/current-SNAPSHOT/reference/html/#elasticsearch.clients.rest
With this configuration you then can inject an ElasticsearchOperations
instance into your code, this bean is defined in the AbstractElasticsearchConfiguration
class. The necessary code fragments:
@Autowired ElasticsearchOperations operations;
...
SearchHits<MyDocument> searchHits = operations.search(searchQuery,
MyDocument.class,
IndexCoordinates.of("index-name");
As for more information about the returned data check https://docs.spring.io/spring-data/elasticsearch/docs/current-SNAPSHOT/reference/html/#elasticsearch.operations.searchresulttypes
We know there are quite some deprecations and some breaking changes in version 4.0, but we we'll have a cleaner API and we will have the possibility to return all this search result metadata, this was not possible in 3.2