ES小总结

组合查询

java 复制代码
FunctionScoreQueryBuilder functionScoreQuery = 
    QueryBuilders.functionScoreQuery(
        boolQuery,
        new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                        QueryBuilders.termQuery("isAD",true),
                        ScoreFunctionBuilders.weightFactorFunction(200)
                )
        });

总代码:

java 复制代码
public PageResult search(RequestParams params) {
        try {
            SearchRequest request = new SearchRequest("hotel");
            //准备DSL
            String key = params.getKey();
            //query
            //构建BooleanQuery
            BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
            //关键字搜索--> must
            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()));
            }
            //品牌条件
            if (params.getBrand() != null && !params.getBrand().equals("")) {

            }
            //星级条件
            if (params.getStarName() != null && !params.getStarName().equals("")) {

            }
            //价格
            if (params.getMinPrice() != null && params.getMaxPrice() != null) {
                //range过滤
                boolQuery.filter(QueryBuilders.rangeQuery("price").lte(params.getMaxPrice()).gte(params.getMinPrice()));
            }
            //分页
            int page = params.getPage();
            int size = params.getSize();
            request.source().from((page - 1) * size).size(size);
            //排序
            String location = params.getLocation();
            if (location != null && !location.equals("")) {
                request.source().sort(SortBuilders.geoDistanceSort("location", new GeoPoint(location))
                        .unit(DistanceUnit.KILOMETERS)
                        .order(SortOrder.ASC)
                );
            }

            //算分控制
            FunctionScoreQueryBuilder functionScoreQuery = QueryBuilders.functionScoreQuery(
                    boolQuery,
                    new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                            new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                    QueryBuilders.termQuery("isAD",true),
                                    ScoreFunctionBuilders.weightFactorFunction(200)
                            )
                    });
            request.source().query(functionScoreQuery);

            //发送请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            return handleResponse(response);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private PageResult handleResponse(SearchResponse response) {
        //解析响应
        SearchHits searchHits = response.getHits();
        //获取总条数
        Long total = searchHits.getTotalHits().value;
        //获取文档数组
        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);
            //获取sort值
            Object[] sortValues = hit.getSortValues();
            if (sortValues.length > 0) {
                Object sortValue = sortValues[0];
                hotelDoc.setDistance(sortValue);
            }
            hotels.add(hotelDoc);
        }
        //构造返回对象
        PageResult result = new PageResult(hotels, total);
        return result;
    }

步骤总结:

  1. 准备request
  2. 准备DSL
  3. 利用client来发送请求
  4. 解析client的返回值

准备request

request分为创建、查询、删除、更新等操作。

Document文档的操作

创建

java 复制代码
    void testAddDocument() throws IOException {
        Hotel hotel = hotelService.getById(61083L);
        HotelDoc hotelDoc=new HotelDoc(hotel);

        //创建request对象
        IndexRequest request=new IndexRequest("hotel").id(hotelDoc.getId().toString());
        //准备JSON文档
        request.source(JSON.toJSONString(hotelDoc),XContentType.JSON);
        //发送请求
        client.index(request,RequestOptions.DEFAULT);
    }

查询

java 复制代码
    void testGetDocumentById() throws IOException {
        GetRequest request=new GetRequest("hotel","61083");
        //获取响应
        GetResponse response=client.get(request,RequestOptions.DEFAULT);

        String json = response.getSourceAsString();
        HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);
        System.out.println(hotelDoc);
    }

删除

java 复制代码
    void DeleteDocument() throws IOException {
        DeleteRequest request=new DeleteRequest("hotel","61083");
        client.delete(request,RequestOptions.DEFAULT);
    }

更新

java 复制代码
    void testUpdateDocument() throws IOException {
        UpdateRequest request=new UpdateRequest("hotel","61083");
        //准备发送请求
        request.doc(
                "price","123"
        );
        client.update(request,RequestOptions.DEFAULT);
    }

Index索引的操作

创建

java 复制代码
    void createHotelIndex() throws IOException {
        //创建Request对象
        CreateIndexRequest request = new CreateIndexRequest("hotel");
        //准备请求参数,DSL语句
        request.source(MAPPING_TEMPLATE, XContentType.JSON);
        //发送请求
        client.indices().create(request, RequestOptions.DEFAULT);
    }

删除

java 复制代码
    void DeleteHotelIndex() throws IOException {

        //创建对象
        DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest("hotel");
        //发送请求
        client.indices().delete(deleteIndexRequest, RequestOptions.DEFAULT);
    }

Bool复合查询

java 复制代码
BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();//创建boolQuery

//根据must、should、filter等来填写查询条件

boolQuery.must(QueryBuilders.matchQuery("all", key));

boolQuery.filter(QueryBuilders.termQuboolQuery.filter(QueryBuilders.rangeQuery("price").lte(params.getMaxPrice()).gte(params.getMinPrice()));ery("city", params.getCity()));
相关推荐
字节跳动数据平台1 小时前
代码量减少 70%、GPU 利用率达 95%:火山引擎多模态数据湖如何释放模思智能的算法生产力
大数据
得物技术2 小时前
深入剖析Spark UI界面:参数与界面详解|得物技术
大数据·后端·spark
武子康4 小时前
大数据-238 离线数仓 - 广告业务 Hive分析实战:ADS 点击率、购买率与 Top100 排名避坑
大数据·后端·apache hive
武子康1 天前
大数据-237 离线数仓 - Hive 广告业务实战:ODS→DWD 事件解析、广告明细与转化分析落地
大数据·后端·apache hive
大大大大晴天1 天前
Flink生产问题排障-Kryo serializer scala extensions are not available
大数据·flink
Elasticsearch2 天前
如何使用 Agent Builder 排查 Kubernetes Pod 重启和 OOMKilled 事件
elasticsearch
Elasticsearch3 天前
通用表达式语言 ( CEL ): CEL 输入如何改进 Elastic Agent 集成中的数据收集
elasticsearch
武子康3 天前
大数据-236 离线数仓 - 会员指标验证、DataX 导出与广告业务 ODS/DWD/ADS 全流程
大数据·后端·apache hive
武子康4 天前
大数据-235 离线数仓 - 实战:Flume+HDFS+Hive 搭建 ODS/DWD/DWS/ADS 会员分析链路
大数据·后端·apache hive
DianSan_ERP5 天前
电商API接口全链路监控:构建坚不可摧的线上运维防线
大数据·运维·网络·人工智能·git·servlet