springboot操作elasticsearch

tech2022-07-16  209

1:使用ElasticsearchRestTemplate

# 查询 SearchRequest searchRequest = new SearchRequest("stu"); SearchSourceBuilder searchSourceBuilder = searchRequest.source(); MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("name", "哈哈"); # 高亮 HighlightBuilder highlightBuilder = new HighlightBuilder().field("name"); # 高亮的前缀 highlightBuilder.preTags("<span color='red'>"); # 高亮的后缀 highlightBuilder.postTags("</span>"); NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchQueryBuilder) .withPageable(PageRequest.of(0, 5)) .withHighlightBuilder(highlightBuilder).build(); SearchHits<Stu> search1 = elasticsearchRestTemplate.search(searchQuery, Stu.class); List<SearchHit<Stu>> searchHits = search1.getSearchHits(); for (SearchHit<Stu> searchHit : searchHits) { Stu content = searchHit.getContent(); // 重新设置高亮 String hi = searchHit.getHighlightField("name").get(0); content.setName(hi); System.out.println(content); }

2 使用restHighLevelClient

SearchRequest searchRequest = new SearchRequest("stu"); SearchSourceBuilder searchSourceBuilder = searchRequest.source(); searchSourceBuilder.query(matchQueryBuilder); searchSourceBuilder.from(0); searchSourceBuilder.size(10); searchSourceBuilder.sort("id", SortOrder.DESC); SearchResponse search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT); long value = search.getHits().getTotalHits().value; System.out.println(value); for (org.elasticsearch.search.SearchHit hit : search.getHits()) { Map<String, Object> sourceAsMap = hit.getSourceAsMap(); }
最新回复(0)