文章目录
- DSL查询文档
- RestClient查询文档
- 快速入门
- 旅游案例
DSL查询文档
RestClient查询文档
快速入门
@Testvoid testMatchAll() throws IOException {//1.准备RequestSearchRequest request = new SearchRequest("hotel");//2.准备DSLrequest.source().query(QueryBuilders.matchAllQuery());//3.发送请求SearchResponse search = client.search(request, RequestOptions.DEFAULT);System.out.println(search);}
@Testvoid testBool() throws IOException {//1.准备RequestSearchRequest request = new SearchRequest("hotel");//2.准备DSL//2.1准备BooleanQueryBoolQueryBuilder boolQuery = QueryBuilders.boolQuery();//2.2添加term
// boolQuery.must(QueryBuilders.termQuery("city", "杭州"));//2.3添加rangeboolQuery.filter(QueryBuilders.rangeQuery("price").lte(250));request.source().query(boolQuery);//3.发送请求SearchResponse search = client.search(request, RequestOptions.DEFAULT);//4.解析响应handleResponse(search);}
旅游案例
Controller层
@RestController
@RequestMapping("/hotel")
public class HotelController {@Autowiredprivate IHotelService hotelService;@PostMapping("/list")public PageResult search(@RequestBody RequestParams params){return hotelService.search(params);}
}
Service实现类
@Service
public class HotelService extends ServiceImpl<HotelMapper, Hotel> implements IHotelService {@Autowiredprivate RestHighLevelClient client;@Overridepublic PageResult search(RequestParams params) {try {//1.准备RequestSearchRequest request = new SearchRequest("hotel");//2.准备DSL//2.1queryString key = params.getKey();if (key == null||"".equals(key)){request.source().query(QueryBuilders.matchAllQuery());}else{request.source().query(QueryBuilders.matchQuery("all",key));}//2.2分页int page = params.getPage();int size = params.getSize();request.source().from(page-1).size(size);//3.发送请求,得到响应SearchResponse response = client.search(request, RequestOptions.DEFAULT);//4.解析响应return handleResponse(response);} catch (IOException e) {throw new RuntimeException(e);}}private PageResult handleResponse(SearchResponse response) {//解析响应SearchHits searchHits = response.getHits();//获取总条数long total = searchHits.getTotalHits().value;System.out.println("共有:"+total);//文档数组SearchHit[] hits = searchHits.getHits();//遍历List<HotelDoc> hote ls = new ArrayList<>();for (SearchHit hit : hits) {//获取文档sourceString 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);}}hotels.add(hotelDoc);}return new PageResult(total,hotels);}
}
修改Service实现类
@Service
public class HotelService extends ServiceImpl<HotelMapper, Hotel> implements IHotelService {@Autowiredprivate RestHighLevelClient client;@Overridepublic PageResult search(RequestParams params) {try {//1.准备RequestSearchRequest request = new SearchRequest("hotel");//2.准备DSL//2.1query//构建BooleanQueryBoolQueryBuilder boolQuery = buildBasicQuery(params, request);request.source().query(boolQuery);//2.2分页int page = params.getPage();int size = params.getSize();request.source().from(page-1).size(size);//3.发送请求,得到响应SearchResponse response = client.search(request, RequestOptions.DEFAULT);//4.解析响应return handleResponse(response);} catch (IOException e) {throw new RuntimeException(e);}}private BoolQueryBuilder buildBasicQuery(RequestParams params, SearchRequest request) {BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();//全文检索 must关键字搜索String key = params.getKey();if (key == null||"".equals(key)){boolQuery.must(QueryBuilders.matchAllQuery());}else{boolQuery.must(QueryBuilders.matchQuery("all",key));}// 城市条件if (params.getCity() != null && !params.getCity().equals("")){boolQuery.filter(QueryBuilders.termQuery("city", params.getCity()));}request.source().query(boolQuery);// 品牌条件if (params.getBrand() != null && !params.getBrand().equals("")){boolQuery.filter(QueryBuilders.termQuery("brand", params.getBrand()));}// 星级条件if (params.getStarName() != null && !params.getStarName().equals("")){boolQuery.filter(QueryBuilders.termQuery("starName", params.getStarName()));}//价格if (params.getMinPrice() != null && !params.getMinPrice().equals("")){boolQuery.filter(QueryBuilders.rangeQuery("price").gte(params.getMinPrice()).lte(params.getMaxPrice()));}return boolQuery;}private PageResult handleResponse(SearchResponse response) {//解析响应SearchHits searchHits = response.getHits();//获取总条数long total = searchHits.getTotalHits().value;System.out.println("共有:"+total);//文档数组SearchHit[] hits = searchHits.getHits();//遍历List<HotelDoc> hotels = new ArrayList<>();for (SearchHit hit : hits) {//获取文档sourceString 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);}}hotels.add(hotelDoc);}return new PageResult(total,hotels);}
}
修改Service中代码
//2.3排序String location = params.getLocation();if (location != null && !location.equals("")){request.source().sort(SortBuilders.geoDistanceSort("location", new GeoPoint(location)).order(SortOrder.ASC).unit(DistanceUnit.KILOMETERS));}
在解析响应中添加
//获取排序值Object[] sortValues = hit.getSortValues();if (sortValues.length>0){Object sortValue = sortValues[0];hotelDoc.setDistance(sortValue);}
在BooleanSearch中添代码
//2.算分控制FunctionScoreQueryBuilder functionScoreQuery = QueryBuilders.functionScoreQuery(boolQuery,// function score的数组new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{//其中一个function score元素new FunctionScoreQueryBuilder.FilterFunctionBuilder(// 过滤条件QueryBuilders.termQuery("isAD", true),//算分函数ScoreFunctionBuilders.weightFactorFunction(10))});request.source().query(functionScoreQuery);