微服务Day6

文章目录

DSL查询文档



















RestClient查询文档

快速入门

java 复制代码
    @Test
    void testMatchAll() throws IOException {
        //1.准备Request
        SearchRequest request = new SearchRequest("hotel");
        //2.准备DSL
        request.source().query(QueryBuilders.matchAllQuery());
        //3.发送请求
        SearchResponse search = client.search(request, RequestOptions.DEFAULT);
        System.out.println(search);
    }





java 复制代码
    @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));
        request.source().query(boolQuery);
        //3.发送请求
        SearchResponse search = client.search(request, RequestOptions.DEFAULT);
        //4.解析响应
        handleResponse(search);
    }

旅游案例


Controller层

java 复制代码
@RestController
@RequestMapping("/hotel")
public class HotelController {
    @Autowired
    private IHotelService hotelService;

    @PostMapping("/list")
    public PageResult search(@RequestBody RequestParams params){
        return hotelService.search(params);
    }
}

Service实现类

java 复制代码
@Service
public class HotelService extends ServiceImpl<HotelMapper, Hotel> implements IHotelService {
    @Autowired
    private RestHighLevelClient client;

    @Override
    public PageResult search(RequestParams params) {
        try {
        //1.准备Request
        SearchRequest request = new SearchRequest("hotel");
        //2.准备DSL
        //2.1query
        String 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) {
            //获取文档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);
                }
            }
            hotels.add(hotelDoc);
        }

        return new PageResult(total,hotels);
    }
}

修改Service实现类

java 复制代码
@Service
public class HotelService extends ServiceImpl<HotelMapper, Hotel> implements IHotelService {
    @Autowired
    private RestHighLevelClient client;

    @Override
    public PageResult search(RequestParams params) {
        try {
        //1.准备Request
        SearchRequest request = new SearchRequest("hotel");
        //2.准备DSL
        //2.1query
        //构建BooleanQuery
        BoolQueryBuilder 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) {
            //获取文档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);
                }
            }
            hotels.add(hotelDoc);
        }

        return new PageResult(total,hotels);
    }
}

修改Service中代码

java 复制代码
        //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)
                    );
        }

在解析响应中添加

java 复制代码
            //获取排序值
            Object[] sortValues = hit.getSortValues();
            if (sortValues.length>0){
                Object sortValue = sortValues[0];
                hotelDoc.setDistance(sortValue);
            }



在BooleanSearch中添代码

java 复制代码
        //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);
相关推荐
加油,旭杏3 分钟前
【go语言】变量和常量
服务器·开发语言·golang
H.209 分钟前
centos7执行yum操作时报错Could not retrieve mirrorlist http://mirrorlist.centos.org解决
linux·centos
wanhengidc22 分钟前
网站服务器中的文件被自动删除的原因
运维·服务器
9毫米的幻想43 分钟前
【Linux系统】—— 编译器 gcc/g++ 的使用
linux·运维·服务器·c语言·c++
helloliyh1 小时前
Windows和Linux系统安装东方通
linux·运维·windows
小深ai硬件分享2 小时前
Keras、TensorFlow、PyTorch框架对比及服务器配置揭秘
服务器·人工智能·深度学习
van叶~3 小时前
Linux探秘坊-------4.进度条小程序
linux·运维·小程序
秋风&萧瑟3 小时前
【数据结构】顺序队列与链式队列
linux·数据结构·windows
我科绝伦(Huanhuan Zhou)3 小时前
Linux 系统服务开机自启动指导手册
java·linux·服务器
超级阿飞4 小时前
利用Kubespray安装生产环境的k8s集群-实施篇
elasticsearch·容器·kubernetes