HM-SpringCloud微服务系列6.3【RestClient查询文档及结果处理】
1 快速入门(以match_all查询为例)
1.1 发起查询请求
- 代码解读:
- 第一步,创建
SearchRequest
对象,指定索引库名 - 第二步,利用
request.source()
构建DSL,DSL中可以包含查询、分页、排序、高亮等query()
:代表查询条件,利用QueryBuilders.matchAllQuery()
构建一个match_all查询的DSL
- 第三步,利用client.search()发送请求,得到响应
- 第一步,创建
- 这里关键的API有两个,一个是
request.source()
,其中包含了查询、排序、分页、高亮等所有功能:
- 另一个是
QueryBuilders
,其中包含match、term、function_score、bool等各种查询:
- 测试
1.2 解析响应结果
elasticsearch返回的结果是一个JSON字符串,结构包含:
hits
:命中的结果total
:总条数,其中的value是具体的总条数值max_score
:所有结果中得分最高的文档的相关性算分hits
:搜索结果的文档数组,其中的每个文档都是一个json对象_source
:文档中的原始数据,也是json对象
因此,我们解析响应结果,就是逐层解析JSON字符串,流程如下:
SearchHits
:通过response.getHits()获取,就是JSON中的最外层的hits,代表命中的结果SearchHits#getTotalHits().value
:获取总条数信息SearchHits#getHits()
:获取SearchHit数组,也就是文档数组SearchHit#getSourceAsString()
:获取文档结果中的_source,也就是原始的json文档数据
1.3 完整代码
点击查看代码
package com.yppah.hoteldemo;
import com.alibaba.fastjson.JSON;
import com.yppah.hoteldemo.pojo.HotelDoc;
import org.apache.http.HttpHost;
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.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import java.io.IOException;
import static com.yppah.hoteldemo.constants.HotelIndexConstants.MAPPING_TEMPLATE;
@SpringBootTest
public class HotelSearchTest {
private RestHighLevelClient client;
@Test
void testInit(){
System.out.println(client);
}
@BeforeEach
void setUp() {
client = new RestHighLevelClient(RestClient.builder(
HttpHost.create("http://10.193.193.141:9200")
));
}
@AfterEach
void tearDown() throws IOException {
client.close();
}
@Test
void testMatchAll() throws IOException {
//1 准备Request
SearchRequest request = new SearchRequest("hotel");
//2 准备DSL
request.source().query(QueryBuilders.matchAllQuery());
//3 发送请求
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
System.out.println(response);
//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) {
//4.3.1 获取文档source
String json = hit.getSourceAsString();
//4.3.2 反序列化解析json
HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);
System.out.println("hotelDoc=" + hotelDoc);
}
}
}
1.4 小结
查询的基本步骤:
- 创建SearchRequest对象
- 准备Request.source(),也就是DSL。
① QueryBuilders来构建查询条件
② 传入Request.source() 的 query() 方法 - 发送请求,得到结果
- 解析结果(参考JSON结果,从外到内,逐层解析)
2 match查询
- Java代码上的差异主要是request.source().query()中的参数了
点击查看代码
/**
* match查询
* @throws IOException
*/
@Test
void testMatch() throws IOException {
//1 准备Request
SearchRequest request = new SearchRequest("hotel");
//2 准备DSL
request.source()
.query(QueryBuilders.matchQuery("all", "如家"));
//3 发送请求
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
System.out.println(response);
//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) {
//4.3.1 获取文档source
String json = hit.getSourceAsString();
//4.3.2 反序列化解析json
HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);
System.out.println("hotelDoc=" + hotelDoc);
}
}
- 而结果解析代码则完全一致,可以抽取并共享
IDEA代码块抽取为方法的快捷键:
ctrl+alt+m
点击查看代码
package com.yppah.hoteldemo;
import com.alibaba.fastjson.JSON;
import com.yppah.hoteldemo.pojo.HotelDoc;
import org.apache.http.HttpHost;
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.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import java.io.IOException;
import static com.yppah.hoteldemo.constants.HotelIndexConstants.MAPPING_TEMPLATE;
@SpringBootTest
public class HotelSearchTest {
private RestHighLevelClient client;
@Test
void testInit(){
System.out.println(client);
}
@BeforeEach
void setUp() {
client = new RestHighLevelClient(RestClient.builder(
HttpHost.create("http://10.193.193.141:9200")
));
}
@AfterEach
void tearDown() throws IOException {
client.close();
}
/**
* 快速入门
* @throws IOException
*/
@Test
void testMatchAll() throws IOException {
//1 准备Request
SearchRequest request = new SearchRequest("hotel");
//2 准备DSL
request.source().query(QueryBuilders.matchAllQuery());
//3 发送请求
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
System.out.println(response);
//4 解析响应
handleResponse(response);
}
/**
* match查询
* @throws IOException
*/
@Test
void testMatch() throws IOException {
//1 准备Request
SearchRequest request = new SearchRequest("hotel");
//2 准备DSL
request.source()
.query(QueryBuilders.matchQuery("all", "如家"));
//3 发送请求
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
System.out.println(response);
handleResponse(response);
}
private void handleResponse(SearchResponse response) {
//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) {
//4.3.1 获取文档source
String json = hit.getSourceAsString();
//4.3.2 反序列化解析json
HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);
System.out.println("hotelDoc=" + hotelDoc);
}
}
}
3 精确查询
4 布尔查询
可以看到,API与其它查询的差别同样是在查询条件的构建,QueryBuilders,结果解析等其他代码完全不变。
点击查看代码
/**
* 复合查询(含精确查询、布尔查询)
* @throws IOException
*/
@Test
void testBool() throws IOException {
//1 准备Request
SearchRequest request = new SearchRequest("hotel");
//2 准备DSL
//2.1 准备BooleanQuery
BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
//2.2 添加term
boolQuery.must(QueryBuilders.termQuery("city", "杭州"));
//2.3 添加range
boolQuery.filter(QueryBuilders.rangeQuery("price").lte(250)); //价格低于250元
request.source().query(boolQuery);
//3 发送请求
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
System.out.println(response);
handleResponse(response);
}
5 排序、分页
搜索结果的排序和分页是与query同级的参数,因此同样是使用request.source()来设置。
对应的API如下:
点击查看代码
/**
* 查询结果处理之排序&分页
* @throws IOException
*/
@Test
void testPageAndSort() throws IOException {
//1 准备Request
SearchRequest request = new SearchRequest("hotel");
//2 准备DSL
//2.1 query
request.source().query(QueryBuilders.matchAllQuery());
//2.2 排序sort
request.source().sort("price", SortOrder.ASC);
//2.3 分页from&size
int page = 1, size = 5; //实际应用中这两个参数应该是前端传过来的
request.source().from((page-1)*size).size(size); //链式编程
//3 发送请求
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
System.out.println(response);
handleResponse(response);
}
第一页
第二页
6 高亮
高亮的代码与之前代码差异较大,有两点:
- 查询的DSL:其中除了查询条件,还需要添加高亮条件,同样是与query同级。
- 结果解析:结果除了要解析_source文档数据,还要解析高亮结果
6.1 高亮请求构建
高亮请求的构建API如下:
上述代码省略了查询条件部分,但是大家不要忘了:高亮查询必须使用全文检索查询,并且要有搜索关键字,将来才可以对关键字高亮。
完整代码如下:
点击查看代码
/**
* 查询结果处理之高亮
* @throws IOException
*/
@Test
void testHighlight() throws IOException {
//1 准备Request
SearchRequest request = new SearchRequest("hotel");
//2 准备DSL
//2.1 query
request.source().query(QueryBuilders.matchQuery("all", "如家"));
//2.2 highlight
request.source().highlighter(new HighlightBuilder().field("name").requireFieldMatch(false)); //RestAPI均支持链式编程
//3 发送请求
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
System.out.println(response);
handleResponse(response);
}
6.2 高亮结果解析
高亮的结果与查询的文档结果默认是分离的,并不在一起。
因此解析高亮的代码需要额外处理:
代码解读:
- 第一步:从结果中获取source。hit.getSourceAsString(),这部分是非高亮结果,json字符串。还需要反序列为HotelDoc对象
- 第二步:获取高亮结果。hit.getHighlightFields(),返回值是一个Map,key是高亮字段名称,值是HighlightField对象,代表高亮值
- 第三步:从map中根据高亮字段名称,获取高亮字段值对象HighlightField
- 第四步:从HighlightField中获取Fragments,并且转为字符串。这部分就是真正的高亮字符串了
- 第五步:用高亮的结果替换HotelDoc中的非高亮结果
完整代码如下:
点击查看代码
/**
* 查询结果处理之高亮
* @throws IOException
*/
@Test
void testHighlight() throws IOException {
//1 准备Request
SearchRequest request = new SearchRequest("hotel");
//2 准备DSL
//2.1 query
request.source().query(QueryBuilders.matchQuery("all", "如家"));
//2.2 highlight
request.source().highlighter(new HighlightBuilder().field("name").requireFieldMatch(false)); //RestAPI均支持链式编程
//3 发送请求
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
System.out.println(response);
handleResponse2(response);
}
private void handleResponse2(SearchResponse response) {
//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) {
//4.3.1 获取文档source
String json = hit.getSourceAsString();
//4.3.2 反序列化解析json
HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);
// 5 高亮结果解析
Map<String, HighlightField> highlightFields = hit.getHighlightFields();
/*
CollectionUtils是spring提供的工具类可以判断map是否为空
效果同if (highlightFields==null || highlightFields.size()==0)
*/
if (!CollectionUtils.isEmpty(highlightFields)) {
// 5.1 根据字段名获取高亮结果
HighlightField highlightField = highlightFields.get("name");
if (highlightField != null) {
// 5.2 获取高亮值
String name = highlightField.getFragments()[0].string();
System.out.println(name);
// 5.3 覆盖原数据中的非高亮结果
hotelDoc.setName(name);
}
}
System.out.println("hotelDoc=" + hotelDoc);
}
}
7 总结