RestClient查询文档快速入门
文章目录
- RestClient查询文档快速入门
- 1.1、match_all
- 1.2、全文检索查询
- 1.3、精确查询
- 1.4、复合查询-boolean query
- 1.5、排序和分页
- 1.6、高亮(解析查询高亮结果)
1.1、match_all
package cn.mannor.hotel;
import org.apache.http.HttpHost;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import static cn.mannor.hotel.constants.HotelConstants.MAPPING_TEMPLATE;
public class HotelSearchTest {
private RestHighLevelClient restHighLevelClient; // 高级REST客户端,用于与Elasticsearch进行交互
@Test
void testMatchAll() throws IOException {
//1.准备Request
SearchRequest hotelRequest = new SearchRequest("hotel");
//2.准备DSL
hotelRequest.source().query(QueryBuilders.matchAllQuery());
//3.发送请求
SearchResponse response = restHighLevelClient.search(hotelRequest, RequestOptions.DEFAULT);
System.out.println(response);
}
/**
* 初始化测试环境,创建并配置RestHighLevelClient实例。
*/
@BeforeEach
void setUp() {
this.restHighLevelClient = new RestHighLevelClient(RestClient.builder(
HttpHost.create("http://192.168.12.131:9200") // 设置Elasticsearch的地址和端口
));
}
/**
* 测试结束后清理资源,关闭RestHighLevelClient实例。
*
* @throws IOException 如果关闭客户端时发生IO错误
*/
@AfterEach
void tearDown() throws IOException {
this.restHighLevelClient.close(); // 关闭高级REST客户端,释放资源
}
}
注:下面的内容我只会放置测试方法。
完整获取:
@Test
void testMatchAll() throws IOException {
//1.准备Request
SearchRequest hotelRequest = new SearchRequest("hotel");
//2.准备DSL
hotelRequest.source().query(QueryBuilders.matchAllQuery());
//3.发送请求
SearchResponse response = restHighLevelClient.search(hotelRequest, RequestOptions.DEFAULT);
//4.解析响应
SearchHits searchHits = response.getHits();
//4.1获取总条数
long total = searchHits.getTotalHits().value;
//4.2文档数组
SearchHit[] hits = searchHits.getHits();
//4.3遍历
for (SearchHit hit : hits) {
//获取文档source
String json = hit.getSourceAsString();
//反序列化
HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);
System.out.println("hoteldoc:" + hotelDoc);
}
System.out.println(response);
}
其中,核心API包含所有方法:
-
hotelRequest.source()
-
QueryBuilders
1.2、全文检索查询
// 单字段查询
QueryBuilders.matchQuery("name", "上海");
// 多字段查询
QueryBuilders.multiMatchQuery("如家", "name", "business");
1.3、精确查询
// 词条查询
QueryBuilders.termQuery("city", "杭州");
// 范围查询
QueryBuilders.rangeQuery("price").gte(100).lte(150);
例如:
@Test
void testMatch() throws IOException {
//1.准备Request
SearchRequest hotelRequest = new SearchRequest("hotel");
//2.准备DSL
//2.1词条查询
hotelRequest.source().query(QueryBuilders.termQuery("hotelName", "酒店"));
//2.2范围查询
// hotelRequest.source().query(QueryBuilders.rangeQuery("price").lt(300).gt(1000));
//3.发送请求
SearchResponse response = restHighLevelClient.search(hotelRequest, RequestOptions.DEFAULT);
//4.解析响应(方法抽出来了)
handelResponse(response);
}
1.4、复合查询-boolean query
// 创建布尔查询
BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
// 添加must条件
boolQuery.must(QueryBuilders.termQuery("city", "杭州"));
// 添加filter条件
boolQuery.filter(QueryBuilders.rangeQuery("price").lte(250));
例:
@Test
void testBooleQuery() throws IOException {
//1.准备Request
SearchRequest hotelRequest = new SearchRequest("hotel");
//2.准备DSL
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
// 添加must条件
boolQueryBuilder.must(QueryBuilders.matchQuery("city", "上海"));
// 添加filter条件
boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").lt(250));
hotelRequest.source().query(boolQueryBuilder);
//3.发送请求
SearchResponse response = restHighLevelClient.search(hotelRequest, RequestOptions.DEFAULT);
//4.解析响应(方法抽出来了)
handelResponse(response);
}
基于上述几种查询,只需要记住核心API:QueryBuilders
1.5、排序和分页
@Test
void testPageAndSort() throws IOException {
//页码,每页大小
int page = 1, size = 5;
//1.准备Request
SearchRequest hotelRequest = new SearchRequest("hotel");
//2.准备DSL
hotelRequest.source().query(QueryBuilders.matchAllQuery());
//分页from ,size 排序sort
hotelRequest.source().from((page-1)*size).size(5).sort("price", SortOrder.DESC);
//3.发送请求
SearchResponse response = restHighLevelClient.search(hotelRequest, RequestOptions.DEFAULT);
//4.解析响应
handelResponse(response);
}
1.6、高亮(解析查询高亮结果)
@Test
void testHighlight() throws IOException {
//1.准备Request
SearchRequest hotelRequest = new SearchRequest("hotel");
//2.准备DSL
hotelRequest.source().query(QueryBuilders.matchQuery("name", "酒店"));
//分页from ,size 排序sort
hotelRequest.source().highlighter(new HighlightBuilder()
.field("name")
.requireFieldMatch(false));
//3.发送请求
SearchResponse response = restHighLevelClient.search(hotelRequest, RequestOptions.DEFAULT);
//高亮解析
//4.解析响应
SearchHits searchHits = response.getHits();
//4.1获取总条数
long total = searchHits.getTotalHits().value;
System.out.println("查询到的数据总条数为:" + total);
//4.2文档数组
SearchHit[] hits = searchHits.getHits();
//4.3遍历
for (SearchHit hit : hits) {
//获取文档source
String json = hit.getSourceAsString();
//反序列化
HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);
//获取高亮结果
Map<String, HighlightField> highlightFields = hit.getHighlightFields();
if (!CollectionUtils.isEmpty(highlightFields)) {
// 根据字段名获取高亮结果
HighlightField highlightField = highlightFields.get("name");
if (highlightField != null) {
//获取高亮值
String name = highlightField.getFragments()[0].string();
//覆盖非高亮结果
hotelDoc.setName(name);
}
}
System.out.println("hoteldoc:" + hotelDoc);
}
System.out.println(response);
}
查询结果: