zoukankan      html  css  js  c++  java
  • How to provide highlighting with Spring data elasticsearch

    How to provide highlighting with Spring data 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));
    }
  • 相关阅读:
    jsonp 跨域解决 spring
    goEasy消息推送,pushlet 向特写用户实时推送
    支持中文加密解密
    webservice 小小例子
    DES加密
    线程、异步
    mysql数据库导出模型到powerdesigner,PDM图形窗口中显示数据列的中文注释
    Log4j按级别输出到不同文件
    niginx 负载均衡
    node-webkit安装及简单实现
  • 原文地址:https://www.cnblogs.com/softidea/p/6102792.html
Copyright © 2011-2022 走看看