似乎SpringData ES不提供类来获取ES返回的突出显示。Spring Data可以返回对象列表,但是ES返回的Json中的高亮部分位于单独的部分中,该部分未由“ ElasticSearchTemplate”类处理。
代码示例:-
QueryBuilder query = QueryBuilders.matchQuery("name","tom"); SearchQuery searchQuery =new NativeSearchQueryBuilder().withQuery(query). with HighlightFields(new Field("name")).build(); List<ESDocument> publications = elasticsearchTemplate.queryForList (searchQuery, ESDocument.class);
我可能是错的,但是我无法弄清楚仅使用SpringDataES。有人可以发布一个示例,说明如何使用Spring Data ES获得亮点吗?
提前致谢 !
从spring数据elasticsearch中的测试用例中,我找到了解决方案:
这会有所帮助。
@Test public void shouldReturnHighlightedFieldsForGivenQueryAndFields() { //given String documentId = randomNumeric(5); String actualMessage = "some test message"; String highlightedMessage = "some <em>test</em> message"; SampleEntity sampleEntity = SampleEntity.builder().id(documentId) .message(actualMessage) .version(System.currentTimeMillis()).build(); IndexQuery indexQuery = getIndexQuery(sampleEntity); elasticsearchTemplate.index(indexQuery); elasticsearchTemplate.refresh(SampleEntity.class); SearchQuery searchQuery = new NativeSearchQueryBuilder() .withQuery(termQuery("message", "test")) .withHighlightFields(new HighlightBuilder.Field("message")) .build(); Page<SampleEntity> sampleEntities = elasticsearchTemplate.queryForPage(searchQuery, SampleEntity.class, new SearchResultMapper() { @Override public <T> Page<T> mapResults(SearchResponse response, Class<T> clazz, Pageable pageable) { List<SampleEntity> chunk = new ArrayList<SampleEntity>(); for (SearchHit searchHit : response.getHits()) { if (response.getHits().getHits().length <= 0) { return null; } SampleEntity user = new SampleEntity(); user.setId(searchHit.getId()); user.setMessage((String) searchHit.getSource().get("message")); user.setHighlightedMessage(searchHit.getHighlightFields().get("message").fragments()[0].toString()); chunk.add(user); } if (chunk.size() > 0) { return new PageImpl<T>((List<T>) chunk); } return null; } }); assertThat(sampleEntities.getContent().get(0).getHighlightedMessage(), is(highlightedMessage)); }