微服务es搜索关键词,实现关键词高亮,来自头条的总结
在实现微服务中的Elasticsearch关键字高亮时,可以使用Elasticsearch的highlight
功能。以下是一个简单的例子,展示了如何在Spring Boot应用中使用Elasticsearch RestHighLevelClient来执行搜索并实现关键字高亮。
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.util.Map;
@Service
public class SearchService {
@Autowired
private RestHighLevelClient client;
public SearchResponse searchWithHighlight(String index, String field, String keyword) throws IOException {
SearchRequest searchRequest = new SearchRequest(index);
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
HighlightBuilder highlightBuilder = new HighlightBuilder();
highlightBuilder.field(field).requireFieldMatch(false);
searchSourceBuilder.highlighter(highlightBuilder);
searchSourceBuilder.query(QueryBuilders.matchQuery(field, keyword));
searchRequest.source(searchSourceBuilder);
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
return searchResponse;
}
public void processSearchResponseWithHighlight(SearchResponse searchResponse) {
for (var hit : searchResponse.getHits().getHits()) {
Map<String, HighlightField> highlightFields = hit.getHighlightFields();
HighlightField highlightField = highlightFields.get(/* 你要高亮的字段名 */);
if (highlightField != null) {
System.out.println(highlightField.getFragments()[0].string());
}
}
评论已关闭