elasticsearch8.5版本集成springboot高版本3.0.0开发

2023-12-22 19:57:09

基础环境

jdk版本:17
springboot 版本:3.0.0
springcloud版本:2022.0.0
elasticserch版本:8.5.1

Maven 配置

     <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.0.0</version>
        <relativePath/>
    </parent>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <dependency>
                <groupId>com.alibaba.cloud</groupId>
                <artifactId>spring-cloud-alibaba-dependencies</artifactId>
                <version>${sping-cloud-alibaba.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
        </dependency>
        <dependency>
            <groupId>co.elastic.clients</groupId>
            <artifactId>elasticsearch-java</artifactId>
        </dependency>

业务常规开发

多条件&排序搜索文档数据

    public List<ProductResp> queryProductDoc(ProductReq req) {
        List<ProductResp> productList = Lists.newArrayList();
		List<Query> queries = getQueryConditions(req);
		
 		SearchResponse<ProductResp> search  = elasticsearchClient.search(s -> s
                        .index("product")
                        .query(q->q.bool(b->b.must(queries)))
                        //分页查询,从第0页开始查询size个document
                        .from(req.getPageNum()-1)
                        .size(req.getPageSize())
                        //按createTime降序、状态升序排序
                        .sort(f->f.field(o->o.field("createTime").order(SortOrder.Desc)))
                        .sort(f->f.field(o->o.field("status").order(SortOrder.Asc)))
                        ,ProductResp.class);
       for (Hit<ProductResp> hit : search.hits().hits()) {
            ProductResp resp = hit.source();
            productList.add(resp);
       }
       return productList;
   }
 /**
     * 组装查询的条件
     * @param req
     * @return
     */
    private List<Query> getQueryConditions(ProductReq req){
        List<Query> queries = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(req.getBrandIds())){
            List<FieldValue> values = new ArrayList<>();
            for (String id : req.getBrandIds()) {
                values.add(FieldValue.of(id));
            }
            //brandId字段精确查询
            Query brandQuery = TermsQuery.of(t -> t.field("brandId").terms(new TermsQueryField.Builder()
                    .value(values).build()
            ))._toQuery();

            queries.add(brandQuery);
        }

        if(!Objects.isNull(req.getCategoryCodes())&&req.getCategoryCodes()!=0){
            List<FieldValue> values = new ArrayList<>();
            values.add(FieldValue.of(req.getCategoryCodes()));
            //categoryCodes精确匹配多个枚举值(类似sql in查询: where categoryCodes in (values))
            Query mallL5CategoriesQuery = TermsQuery.of(t->t.field("categoryCodes").terms(new TermsQueryField.Builder()
                    .value(values).build()))._toQuery();
            queries.add(mallL5CategoriesQuery);
        }
      

        if(!Objects.isNull(req.getIsHaveStock())){
            if(req.getIsHaveStock()==1){
                JsonData stockFlag = JsonData.of(0);
                //availableStock范围查询(类似sql:where availableStock>xxx)
                Query hasStockQuery = RangeQuery.of(t->t.field("availableStock").gt(stockFlag))._toQuery();
                queries.add(hasStockQuery);
            }else{
                JsonData stockFlag = JsonData.of(0);
                Query hasStockQuery = RangeQuery.of(t->t.field("availableStock").lte(stockFlag))._toQuery();
                queries.add(hasStockQuery);
            }
        }

        if(StringUtils.isNotBlank(req.getKeyWord())){
            String keyword = req.getKeyWord();
            if (req.getKeyWord().contains("|")) {
                keyword = keyword.replace("|", "");
            } else {
                keyword = req.getKeyWord();
            }
            final String finalKeyWord = keyword;
			//前端传一个关键字匹配多字段,类似sql语句(where name like '%keyword%' or code like '%keyword%' or desc like '%keyword%' )
            Query nameQuery= MatchQuery.of(m->m.field("name").query(req.getKeyWord()))._toQuery();
            Query codeQuery= MatchQuery.of(m->m.field("code").query(finalKeyWord))._toQuery();
            Query descQuery= MatchQuery.of(m->m.field("desc").query(finalKeyWord))._toQuery();
            List<Query> newQuery = Arrays.asList(nameQuery, codeQuery, descQuery);
            Query query = BoolQuery.of(m -> m.should(newQuery))._toQuery();
            //skuCode //productSize
            queries.add(query);
        }
        return queries;
    }

文章来源:https://blog.csdn.net/AiMaiShanHuHai/article/details/135159457
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。