商城项目构建查询商品信息的ES语句测试拼接的DSL语句查询效果-----商城项目

#程序员如何平衡日常编码工作与提升式学习?#
package com.alatus.search.service.impl;

import com.alatus.search.config.MallElasticSearchConfig;
import com.alatus.search.constant.EsConstant;
import com.alatus.search.service.MallSearchService;
import com.alatus.search.vo.SearchParam;
import com.alatus.search.vo.SearchResult;
import org.apache.commons.lang.StringUtils;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.NestedQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.IOException;

@Service
public class MallSearchServiceImpl implements MallSearchService {
    @Autowired
    private RestHighLevelClient client;
    @Override
    public SearchResult search(SearchParam searchParam) {
//        动态构建出查询所需要的DSL语句
        SearchResult searchResult = null;
//        准备检索请求
        SearchRequest searchRequest = buildSearchRequest(searchParam);
        try {
//        执行查询检索请求
            SearchResponse response = client.search(searchRequest, MallElasticSearchConfig.COMMON_OPTIONS);
//            分析响应数据并封装成返回的数据
            searchResult = buildSearchResult();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return null;
    }

    private SearchResult buildSearchResult() {
        return null;
    }

    //准备检索请求
    private SearchRequest buildSearchRequest(SearchParam searchParam) {
//        构建DSL语句
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
//        查询条件,模糊查询,过滤,按照属性,分类品牌,价格区间,库存
//        构建了bool-query
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
//        must
        if(!StringUtils.isEmpty(searchParam.getKeyword())){
            boolQuery.must(QueryBuilders.matchQuery("skuTitle",searchParam.getKeyword()));
        }
//        filter按照三级分类ID查询
        if(searchParam.getCatalog3Id()!=null){
            boolQuery.filter(QueryBuilders.termQuery("catalogId",searchParam.getCatalog3Id()));
        }
//        filter按照品牌ID查询
        if(searchParam.getBrandId()!=null && !searchParam.getBrandId().isEmpty()){
            boolQuery.filter(QueryBuilders.termsQuery("brandId",searchParam.getBrandId()));
        }
//        filter按照属性ID查询
        if(searchParam.getAttrs()!=null && !searchParam.getAttrs().isEmpty()){
            for (String attrStr : searchParam.getAttrs()) {
                BoolQueryBuilder nestedBoolQuery = QueryBuilders.boolQuery();
                String[] attr = attrStr.split("_");
                String attrId = attr[0];//属性ID
                String[] attrValues = attr[1].split(":");//属性值
                nestedBoolQuery.must(QueryBuilders.termQuery("attrs.attrId",attrId));
                nestedBoolQuery.must(QueryBuilders.termsQuery("attrs.attrValue",attrValues));
//                每一个都必须有一个嵌入式的查询
                NestedQueryBuilder attrs = QueryBuilders.nestedQuery("attrs", nestedBoolQuery, ScoreMode.None);
                boolQuery.filter(attrs);
            }
        }
//        按照库存进行查询
        if(searchParam.getHasStock()!=null){
            boolQuery.filter(QueryBuilders.termQuery("hasStock", searchParam.getHasStock()==1));
        }
//        按照价格区间
        if(!StringUtils.isEmpty(searchParam.getSkuPrice())){
            RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("skuPrice");
            String[] price = searchParam.getSkuPrice().split("_");
            if(price.length == 2){
                rangeQuery.gte(price[0]).lte(price[1]);
            }
            else if (price.length == 1) {
                if(searchParam.getSkuPrice().startsWith("_")){
                    rangeQuery.lte(price[0]);
                }
                else if(searchParam.getSkuPrice().endsWith("_")){
                    rangeQuery.gte(price[0]);
                }
            }
            boolQuery.filter(rangeQuery);
        }
//        把所有条件全部封装
        sourceBuilder.query(boolQuery);
//        排序
        if(!StringUtils.isEmpty(searchParam.getSort())){
            String sort = searchParam.getSort();
            String[] sortString = sort.split("_");
            sourceBuilder.sort(sortString[0],sortString[1].equalsIgnoreCase("asc")?SortOrder.ASC:SortOrder.DESC);
        }
//        分页
        if(searchParam.getPageNum()!=null){
            sourceBuilder.from((searchParam.getPageNum()-1)*EsConstant.PRODUCT_PAGESIZE);
            sourceBuilder.size(EsConstant.PRODUCT_PAGESIZE);
        }
//        高亮
        if (!StringUtils.isEmpty(searchParam.getKeyword())){
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field("skuTitle");
            highlightBuilder.preTags("<b style='color:red'>");
            highlightBuilder.postTags("</b>");
            sourceBuilder.highlighter(highlightBuilder);
        }
//        聚合分析
        System.out.println(sourceBuilder.toString());
        return new SearchRequest(new String[]{EsConstant.PRODUCT_INDEX},sourceBuilder);
    }
}
package com.alatus.search.service.impl;

import com.alatus.search.config.MallElasticSearchConfig;
import com.alatus.search.constant.EsConstant;
import com.alatus.search.service.MallSearchService;
import com.alatus.search.vo.SearchParam;
import com.alatus.search.vo.SearchResult;
import org.apache.commons.lang.StringUtils;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.NestedQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.IOException;

@Service
public class MallSearchServiceImpl implements MallSearchService {
    @Autowired
    private RestHighLevelClient client;
    @Override
    public SearchResult search(SearchParam searchParam) {
//        动态构建出查询所需要的DSL语句
        SearchResult searchResult = null;
//        准备检索请求
        SearchRequest searchRequest = buildSearchRequest(searchParam);
        try {
//        执行查询检索请求
            SearchResponse response = client.search(searchRequest, MallElasticSearchConfig.COMMON_OPTIONS);
//            分析响应数据并封装成返回的数据
            searchResult = buildSearchResult();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return null;
    }

    private SearchResult buildSearchResult() {
        return null;
    }

    //准备检索请求
    private SearchRequest buildSearchRequest(SearchParam searchParam) {
//        构建DSL语句
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
//        查询条件,模糊查询,过滤,按照属性,分类品牌,价格区间,库存
//        构建了bool-query
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
//        must
        if(!StringUtils.isEmpty(searchParam.getKeyword())){
            boolQuery.must(QueryBuilders.matchQuery("skuTitle",searchParam.getKeyword()));
        }
//        filter按照三级分类ID查询
        if(searchParam.getCatalog3Id()!=null){
            boolQuery.filter(QueryBuilders.termQuery("catalogId",searchParam.getCatalog3Id()));
        }
//        filter按照品牌ID查询
        if(searchParam.getBrandId()!=null && !searchParam.getBrandId().isEmpty()){
            boolQuery.filter(QueryBuilders.termsQuery("brandId",searchParam.getBrandId()));
        }
//        filter按照属性ID查询
        if(searchParam.getAttrs()!=null && !searchParam.getAttrs().isEmpty()){
            for (String attrStr : searchParam.getAttrs()) {
                BoolQueryBuilder nestedBoolQuery = QueryBuilders.boolQuery();
                String[] attr = attrStr.split("_");
                String attrId = attr[0];//属性ID
                String[] attrValues = attr[1].split(":");//属性值
                nestedBoolQuery.must(QueryBuilders.termQuery("attrs.attrId",attrId));
                nestedBoolQuery.must(QueryBuilders.termsQuery("attrs.attrValue",attrValues));
//                每一个都必须有一个嵌入式的查询
                NestedQueryBuilder attrs = QueryBuilders.nestedQuery("attrs", nestedBoolQuery, ScoreMode.None);
                boolQuery.filter(attrs);
            }
        }
//        按照库存进行查询
        if(searchParam.getHasStock()!=null){
            boolQuery.filter(QueryBuilders.termQuery("hasStock", searchParam.getHasStock()==1));
        }
//        按照价格区间
        if(!StringUtils.isEmpty(searchParam.getSkuPrice())){
            RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("skuPrice");
            String[] price = searchParam.getSkuPrice().split("_");
            if(price.length == 2){
                rangeQuery.gte(price[0]).lte(price[1]);
            }
            else if (price.length == 1) {
                if(searchParam.getSkuPrice().startsWith("_")){
                    rangeQuery.lte(price[0]);
                }
                else if(searchParam.getSkuPrice().endsWith("_")){
                    rangeQuery.gte(price[0]);
                }
            }
            boolQuery.filter(rangeQuery);
        }
//        把所有条件全部封装
        sourceBuilder.query(boolQuery);
//        排序
        if(!StringUtils.isEmpty(searchParam.getSort())){
            String sort = searchParam.getSort();
            String[] sortString = sort.split("_");
            sourceBuilder.sort(sortString[0],sortString[1].equalsIgnoreCase("asc")?SortOrder.ASC:SortOrder.DESC);
        }
//        分页
        if(searchParam.getPageNum()!=null){
            sourceBuilder.from((searchParam.getPageNum()-1)*EsConstant.PRODUCT_PAGESIZE);
            sourceBuilder.size(EsConstant.PRODUCT_PAGESIZE);
        }
//        高亮
        if (!StringUtils.isEmpty(searchParam.getKeyword())){
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field("skuTitle");
            highlightBuilder.preTags("<b style='color:red'>");
            highlightBuilder.postTags("</b>");
            sourceBuilder.highlighter(highlightBuilder);
        }
//        聚合分析
        System.out.println(sourceBuilder.toString());
        return new SearchRequest(new String[]{EsConstant.PRODUCT_INDEX},sourceBuilder);
    }
}
GET alatusmall_product/_search?size=100
{
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "skuTitle": {
              "query": "小米",
              "operator": "OR",
              "prefix_length": 0,
              "max_expansions": 50,
              "fuzzy_transpositions": true,
              "lenient": false,
              "zero_terms_query": "NONE",
              "auto_generate_synonyms_phrase_query": true,
              "boost": 1
            }
          }
        }
      ],
      "filter": [
        {
          "term": {
            "catalogId": {
              "value": 225,
              "boost": 1
            }
          }
        },
        {
          "nested": {
            "query": {
              "bool": {
                "must": [
                  {
                    "term": {
                      "attrs.attrId": {
                        "value": "13",
                        "boost": 1
                      }
                    }
                  },
                  {
                    "terms": {
                      "attrs.attrValue": [
                        "天玑8300",
                        "麒麟9000s"
                      ],
                      "boost": 1
                    }
                  }
                ],
                "adjust_pure_negative": true,
                "boost": 1
              }
            },
            "path": "attrs",
            "ignore_unmapped": false,
            "score_mode": "none",
            "boost": 1
          }
        },
        {
          "nested": {
            "query": {
              "bool": {
                "must": [
                  {
                    "term": {
                      "attrs.attrId": {
                        "value": "15",
                        "boost": 1
                      }
                    }
                  },
                  {
                    "terms": {
                      "attrs.attrValue": [
                        "2023"
                      ],
                      "boost": 1
                    }
                  }
                ],
                "adjust_pure_negative": true,
                "boost": 1
              }
            },
            "path": "attrs",
            "ignore_unmapped": false,
            "score_mode": "none",
            "boost": 1
          }
        },
        {
          "term": {
            "hasStock": {
              "value": false,
              "boost": 1
            }
          }
        },
        {
          "range": {
            "skuPrice": {
              "from": "",
              "to": "6000",
              "include_lower": true,
              "include_upper": true,
              "boost": 1
            }
          }
        }
      ],
      "adjust_pure_negative": true,
      "boost": 1
    }
  },
  "sort": [
    {
      "skuPrice": {
        "order": "asc"
      }
    }
  ],
  "highlight": {
    "pre_tags": [
      "<b style='color:red'>"
    ],
    "post_tags": [
      "</b>"
    ],
    "fields": {
      "skuTitle": {}
    }
  }
}

 GET alatusmall_product/_search?size=100
{
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "skuTitle": {
              "query": "小米",
              "operator": "OR",
              "prefix_length": 0,
              "max_expansions": 50,
              "fuzzy_transpositions": true,
              "lenient": false,
              "zero_terms_query": "NONE",
              "auto_generate_synonyms_phrase_query": true,
              "boost": 1
            }
          }
        }
      ],
      "filter": [
        {
          "term": {
            "catalogId": {
              "value": 225,
              "boost": 1
            }
          }
        },
        {
          "nested": {
            "query": {
              "bool": {
                "must": [
                  {
                    "term": {
                      "attrs.attrId": {
                        "value": "13",
                        "boost": 1
                      }
                    }
                  },
                  {
                    "terms": {
                      "attrs.attrValue": [
                        "天玑8300",
                        "麒麟9000s"
                      ],
                      "boost": 1
                    }
                  }
                ],
                "adjust_pure_negative": true,
                "boost": 1
              }
            },
            "path": "attrs",
            "ignore_unmapped": false,
            "score_mode": "none",
            "boost": 1
          }
        },
        {
          "nested": {
            "query": {
              "bool": {
                "must": [
                  {
                    "term": {
                      "attrs.attrId": {
                        "value": "15",
                        "boost": 1
                      }
                    }
                  },
                  {
                    "terms": {
                      "attrs.attrValue": [
                        "2023"
                      ],
                      "boost": 1
                    }
                  }
                ],
                "adjust_pure_negative": true,
                "boost": 1
              }
            },
            "path": "attrs",
            "ignore_unmapped": false,
            "score_mode": "none",
            "boost": 1
          }
        },
        {
          "term": {
            "hasStock": {
              "value": false,
              "boost": 1
            }
          }
        },
        {
          "range": {
            "skuPrice": {
              "from": "",
              "to": "6000",
              "include_lower": true,
              "include_upper": true,
              "boost": 1
            }
          }
        }
      ],
      "adjust_pure_negative": true,
      "boost": 1
    }
  },
  "sort": [
    {
      "skuPrice": {
        "order": "asc"
      }
    }
  ],
  "highlight": {
    "pre_tags": [
      "<b style='color:red'>"
    ],
    "post_tags": [
      "</b>"
    ],
    "fields": {
      "skuTitle": {}
    }
  }
}

  • 11
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值