全文检索:
两种查询:
1,macth
2,multi_match (多字段查询)查询与match_all的API基本一致
都是属于query的部分
而两种查询的
差异在于类型和条件上。
请求方式一样路径一样
全文查询 match 和multi_match 查询与match_all的API基本一致
差别是查询条件 也就是query、的部分
精确查询:
term查询和range查询 同样利用QueryBuilders实现:
符合查询—boolean query
@SpringBootTest
class HotelSearchTest {
//l利用service来完成增删改查
@Autowired
private IHotelService hotelService;
private RestHighLevelClient client;
@Test
void testMatchAll() throws IOException {
//准备request对象
SearchRequest request = new SearchRequest("hotel");
//准备DSL
request.source().query(QueryBuilders.matchAllQuery());
//发送请求
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
AllMatch(response);
}
@Test
void testmatch() throws IOException {
//准备REQUEST
SearchRequest request = new SearchRequest("hotel");
//准备DSL
request.source().query(QueryBuilders.matchQuery("all","如家"));
//发送请求
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
AllMatch(response);
}
private void AllMatch(SearchResponse response) {
//解析响应的json
SearchHits hits = response.getHits();
//拉取总条数
long value = hits.getTotalHits().value;
//来取文档数组
SearchHit[] hits1 = hits.getHits();
//遍历数组进行反序列化
for (SearchHit documentFields : hits1) {
//读取文档score
String json = documentFields.getSourceAsString();
HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);
}
System.out.println(response);
}
@Test
private void testBool() throws IOException {
//准备REQUEST
SearchRequest request = new SearchRequest("hotel");
//准备DSL
//BooleanQuery
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
//添加term
boolQueryBuilder.must(QueryBuilders.termQuery("city","杭州"));
//添加range
boolQueryBuilder.must(QueryBuilders.rangeQuery("parice").lt("杭州"));
//发送请求
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
AllMatch(response);
}
@BeforeEach
void setUp() {
client = new RestHighLevelClient(RestClient.builder(
HttpHost.create("http://114.55.210.174:9200")
));
}
@AfterEach
void tearDown() throws IOException {
client.close();
}
}