ElasticSearch进阶:一文全览各种ES查询在Java中的实现
import org.elasticsearch.index.query.QueryBuilders;
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.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
// 假设client是已经配置好的RestHighLevelClient实例
RestHighLevelClient client;
// 简单的全文搜索
SearchRequest searchRequest = new SearchRequest("index_name");
searchRequest.source().query(QueryBuilders.matchQuery("field_name", "text to search"));
// 分页搜索
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
sourceBuilder.from(0);
sourceBuilder.size(10);
sourceBuilder.query(QueryBuilders.matchQuery("field_name", "text to search"));
searchRequest.source(sourceBuilder);
// 排序搜索
SearchSourceBuilder sourceBuilderSort = new SearchSourceBuilder();
sourceBuilderSort.query(QueryBuilders.matchQuery("field_name", "text to search"));
sourceBuilderSort.sort("sort_field", SortOrder.ASC);
searchRequest.source(sourceBuilderSort);
// 高亮搜索
SearchSourceBuilder sourceBuilderHighlight = new SearchSourceBuilder();
sourceBuilderHighlight.query(QueryBuilders.matchQuery("field_name", "text to search"));
sourceBuilderHighlight.highlight(new HighlightBuilder().field("field_name"));
searchRequest.source(sourceBuilderHighlight);
// 执行搜索
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
// 处理搜索结果
// ...
// 注意:以上代码仅为示例,实际使用时需要处理异常和配置客户端实例。
这段代码展示了如何在Java中使用Elasticsearch的RestHighLevelClient来执行不同类型的查询,包括全文搜索、分页、排序和高亮。这些查询可以根据实际需求进行组合,以实现更复杂的搜索功能。
评论已关闭