笔记参考:
https://note.youdao.com/ynoteshare/index.html?id=dc7be4dfa0d34d984223d4b87139b9c2&type=note&_time=1631514908776
range 查询和 exists 查询
prefix 查询
wildcard 查询和 regexp 查询

这些查询都可以用在组合查询中



简单查询不用 must,term相当于等号

post /product_db/_search
{
  "from": 0,
  "size": 10,
  "query": {
    "term": {
      "categoryId": 19
    }
  }
}

例子1:根据时间范围 和 用户Id查询

must 相当于and

get voucher_record_form/_search
{
  "from": 5,
  "size": 5,
  "query": {
    "bool": {
      "must": {
        "range": {
          "createTime": {
            "gte": 1601091496,
            "lte": 1601609835
          }
        }
      },
      "filter": [
        {
          "term": {
            "useUid": 2583692
          }
        }
      ]
    }
  },
  "sort": [
    {
      "_id": "desc"
    }
  ]
}



实现:查询用户ID为?,并且按 时间查询
get voucher_record_form/_search
{
  "from": 0,
  "size": 5,
  "query": {
    "bool": {
      "must": {  
          "term" : {"createTime": 1601177491}  
      },
      "filter": [
        {
          "term": {
            "useUid": 2583692
          }
        }
      ]
    }
  },
  "sort": [
    {
      "_id": "desc"
    }
  ]
}


实现:查询用户ID为?,并且按 时间查询
get voucher_record_form/_search
{
  "from": 0,
  "size": 5,
  "query": {
    "bool": {
      "must": [

{  
          "term" : {"createTime": 1601177491} 
      } ,

{
        "term": {
            "useUid": 2583692
          }
      }
      ]
    }
  },
  "sort": [
    {
      "_id": "desc"
    }
  ]
}



查询结果如sql语句中的: isDeal =0 and (uid=1235 or isGlobal=1)        先 and 再 or 查询

must里面再包含bool查询,相当于子查询,里面的bool中的should相当于or查询

POST /message/_search
{
    "query": {
        "bool": {
            "must": [
                { 
                    "match": { "isDeal": false } 
                },
                {
                    "bool": {
                        "should": [
                            { "match": { "uid": 1448626 } },
                            { "match": {  "isGlobal": true } }
                        ]
                    }
                }
            ]
        }
    }
}


should里面用term也行,term为精确查询 match为模糊查询

multi_match 查询
多个字段上执行匹配相同的查询,叫做"multi_match"查询。比如:
POST /kibana_sample_data_flights/_search
{
"query": {
"multi_match": {
"query":"AT",
"fields":["DestCountry", "OriginCountry"]
}
}
}

post /message/_search
{"query":{"bool": {"must": [{"match": {"isDeal": false }},{"bool":{"should":[{"term":{"uid":1448626}},{"term":{"isGlobal":true}}]}}]}}
}

相当于sql :    select * from message where isDeal=false and (uid=1448626 or isGlobal = true)

bool组合查询可用的布尔类型子句包括must、filter、should 和must_not 四 种,它们接收参数值的类型为数组。
must 查询结果中必须要包含的内容,影响相关度
filter 查询结果中必须要包含的内容,
不会影响相关度 should 查询结果非必须包含项,
包含了会提高分数,影响相关度 must_not 查询结果中不能包含的内容,不会影响相关度

must 相当于 and

should   相当于 or

must_not  相当于not

当 should 子句与 must 子句或 filter 子句同时出现在子句 中时,should 子句将不会过滤结果(should失效)


参考:

elasticsearch7常见查询(term、match、bool、filter)_未知的风fly-CSDN博客_elasticsearch7 查询



相当于Mysql中的多个and查询

term为精确查询 match为模糊查询 ,分页查询 条数

POST /message/_search
{
    "query": {
        "bool": {
            "must": [                
                      {"match": {"receiveShopId": 14950828}},
                      {"match": { "isDeal": false } },
                      {"match": {  "type": 28 }}                
            ]
        }
    }
}



POST /message/_search
{
  "from":0,
  "size":20,
    "query": {
        "bool": {
            "must": [
                
                      {"term": {"receiveShopId": 14950828}},
                        {"term": { "isDeal": false } },
                        {"term": {  "type": 28 }}
                
            ]
        }
    }
}



.1 创建索引库
put product_db
{"mappings": {"properties": {"id": {  "type": "long"  },"name": {  "type": "text", "analyzer": "ik_max_word"  },"keywords": {  "type": "text", "analyzer": "ik_max_word"  },"subTitle": {  "type": "text", "analyzer": "ik_max_word"  },"salecount":{  "type": "long"  },"putawayDate":{ "type": "date"  }, "price": {  "type": "double"  }, "promotionPrice": {  "type": "keyword"  },"originalPrice": {  "type": "keyword"  },"pic": {  "type": "keyword"  }, "sale": {  "type": "long"  },"hasStock": {  "type": "boolean"  }, "brandId": {  "type": "long"  },"brandName": {  "type": "keyword"  },"brandImg": {  "type": "keyword"  }, "categoryId": {  "type": "long"  }, "categoryName": {  "type": "keyword"  },"attrs": {  "type": "nested","properties": {  "attrId": {  "type": "long"  },"attrName": { "type": "keyword"  }, "attrValue": {  "type": "keyword"  } }  } }}
}

索引数据准备

PUT /product_db/_doc/1
{"id": "26", "name": "小米 11 手机","keywords": "小米手机", "subTitle": "AI智慧全面屏 6GB +64GB 亮黑色 全网通版 移动联通电信4G手机 双卡双待","price": "3999", "promotionPrice": "2999", "originalPrice": "5999","pic": "http://macro‐oss.oss‐cn‐shenzhen.aliyuncs.com/mall/images/20180615/xi aomi.jpg","sale": 999,"hasStock": true,"salecount": 999,"putawayDate": "2021-04-01","brandId": 6, "brandName": "小米","brandImg": "http://macro‐oss.oss‐cn‐shenzhen.aliyuncs.com/mall/images/20190129/1e34aef2a409119018a4c6258e39ecfb_222_222.png", "categoryId": 19, "categoryName": "手机通讯","attrs": [ { "attrId": 1,"attrName": "cpu","attrValue": "2核"}, { "attrId": 2,"attrName": "颜色", "attrValue": "黑色"}]
}PUT /product_db/_doc/2
{"id": "27","name": "小米 10 手机","keywords": "小米手机","subTitle": "AI智慧全面屏 4GB +64GB 亮白色 全网通版 移动联通电信4G手机 双卡双待 双 卡双待","price": "2999","promotionPrice": "1999","originalPrice": "3999","pic": "http://macro‐oss.oss‐cn‐shenzhen.aliyuncs.com/mall/images/20180615/xi aomi.jpg","sale": 999,"hasStock": false,"salecount": 99,"putawayDate": "2021-04-02","brandId": 6,"brandName": "小米","brandImg": "http://macro‐oss.oss‐cn‐shenzhen.aliyuncs.com/mall/images/201901 29/1e34aef2a409119018a4c6258e39ecfb_222_222.png","categoryId": 19,"categoryName": "手机通讯","attrs": [{"attrId": 1,"attrName": "cpu","attrValue": "4核"},{"attrId": 2,"attrName": "颜色","attrValue": "白色"}]
} PUT /product_db/_doc/3
{"id": "28","name": "小米 手机","keywords": "小米手机","subTitle": "AI智慧全面屏 4GB +64GB 亮蓝色 全网通版 移动联通电信4G手机 双卡双待 双 卡双待","price": "2999","promotionPrice": "1999","originalPrice": "3999","pic": "http://macro‐oss.oss‐cn‐shenzhen.aliyuncs.com/mall/images/20180615/xi aomi.jpg","sale": 999,"hasStock": true,"salecount": 199,"putawayDate": "2021-04-03","brandId": 6,"brandName": "小米","brandImg": "http://macro‐oss.oss‐cn‐shenzhen.aliyuncs.com/mall/images/201901 29/1e34aef2a409119018a4c6258e39ecfb_222_222.png","categoryId": 19,"categoryName": "手机通讯","attrs": [{"attrId": 1,"attrName": "cpu","attrValue": "2核"},{"attrId": 2,"attrName": "颜色","attrValue": "蓝色"}]
} PUT /product_db/_doc/4
{"id": "29","name": "Apple iPhone 8 Plus 64GB 金色特别版 移动联通电信4G手机","keywords": "苹果手机","subTitle": "苹果手机 Apple产品年中狂欢节,好物尽享,美在智慧!速来 >> 勾选[保障服 务][原厂保2年],获得AppleCare+全方位服务计划,原厂延保售后无忧。","price": "5999","promotionPrice": "4999","originalPrice": "7999","pic": "http://macro-oss.oss-cn-shenzhen.aliyuncs.com/mall/images/20180615/5a cc5248N6a5f81cd.jpg","sale": 999,"hasStock": true,"salecount": 1199,"putawayDate": "2021-04-04","brandId": 51,"brandName": "苹果","brandImg": "http://macro-oss.oss-cn-shenzhen.aliyuncs.com/mall/images/201806 07/timg.jpg","categoryId": 19,"categoryName": "手机通讯","attrs": [{"attrId": 1,"attrName": "cpu","attrValue": "4核"},{"attrId": 2,"attrName": "颜色","attrValue": "金色"}]
}PUT /product_db/_doc/5
{"id": "30","name": "HLA海澜之家简约动物印花短袖T恤","keywords": "海澜之家衣服","subTitle": "HLA海澜之家短袖T恤","price": "199","promotionPrice": "99","originalPrice": "299","pic": "http://macro-oss.oss-cn-shenzhen.aliyuncs.com/mall/images/20180615/5a d83a4fN6ff67ecd.jpg!cc_350x449.jpg","sale": 999,"hasStock": true,"salecount": 19,"putawayDate": "2021-04-05","brandId": 50,"brandName": "海澜之家","brandImg": "http://macro-oss.oss-cn-shenzhen.aliyuncs.com/mall/images/201901 29/99d3279f1029d32b929343b09d3c72de_222_222.jpg","categoryId": 8,"categoryName": "T恤","attrs": [{"attrId": 3,"attrName": "尺寸","attrValue": "M"},{"attrId": 4,"attrName": "颜色","attrValue": "黑色"}]
} PUT /product_db/_doc/6
{"id": "31","name": "HLA海澜之家蓝灰花纹圆领针织布短袖T恤","keywords": "海澜之家衣服","subTitle": "HLA海澜之家短袖T恤","price": "299","promotionPrice": "199","originalPrice": "299","pic": "http://macro-oss.oss-cn-shenzhen.aliyuncs.com/mall/images/20180615/5a c98b64N70acd82f.jpg!cc_350x449.jpg","sale": 999,"hasStock": true,"salecount": 399,"putawayDate": "2021-04-06","brandId": 50,"brandName": "海澜之家","brandImg": "http://macro-oss.oss-cn-shenzhen.aliyuncs.com/mall/images/201901 29/99d3279f1029d32b929343b09d3c72de_222_222.jpg","categoryId": 8,"categoryName": "T恤","attrs": [{"attrId": 3,"attrName": "尺寸","attrValue": "X"},{"attrId": 4,"attrName": "颜色","attrValue": "蓝灰"}]
} PUT /product_db/_doc/7
{"id": "32","name": "HLA海澜之家短袖T恤男基础款","keywords": "海澜之家衣服","subTitle": "HLA海澜之家短袖T恤","price": "269","promotionPrice": "169","originalPrice": "399","pic": "http://macro-oss.oss-cn-shenzhen.aliyuncs.com/mall/images/20180615/5a 51eb88Na4797877.jpg","sale": 999,"hasStock": true,"salecount": 399,"putawayDate": "2021-04-07","brandId": 50,"brandName": "海澜之家","brandImg": "http://macro-oss.oss-cn-shenzhen.aliyuncs.com/mall/images/201901 29/99d3279f1029d32b929343b09d3c72de_222_222.jpg","categoryId": 8,"categoryName": "T恤","attrs": [{"attrId": 3,"attrName": "尺寸","attrValue": "L"},{"attrId": 4,"attrName": "颜色","attrValue": "蓝色"}]
} PUT /product_db/_doc/8
{"id": "33","name": "小米(MI)小米电视4A ","keywords": "小米电视机家用电器","subTitle": "小米(MI)小米电视4A 55英寸 L55M5-AZ/L55M5-AD 2GB+8GB HDR 4K超高清 人工智能网络液晶平板电视","price": "2269","promotionPrice": "2169","originalPrice": "2399","pic": "http://macro-oss.oss-cn-shenzhen.aliyuncs.com/mall/images/20180615/5b 02804dN66004d73.jpg","sale": 999,"hasStock": true,"salecount": 132,"putawayDate": "2021-04-09","brandId": 6,"brandName": "小米","brandImg": "http://macro-oss.oss-cn-shenzhen.aliyuncs.com/mall/images/201901 29/1e34aef2a409119018a4c6258e39ecfb_222_222.png","categoryId": 35,"categoryName": "手机数码","attrs": [{"attrId": 5,"attrName": "屏幕尺寸","attrValue": "52"},{"attrId": 6,"attrName": "机身颜色","attrValue": "黑色"}]
} PUT /product_db/_doc/9
{"id": "34","name": "小米(MI)小米电视4A 65英寸","keywords": "小米电视机家用电器","subTitle": "小米(MI)小米电视4A 65英寸 L55M5-AZ/L55M5-AD 2GB+8GB HDR 4K超高清 人工智能网络液晶平板电视","price": "3269","promotionPrice": "3169","originalPrice": "3399","pic": "http://macro-oss.oss-cn-shenzhen.aliyuncs.com/mall/images/20180615/5b 028530N51eee7d4.jpg","sale": 999,"hasStock": true,"salecount": 999,"putawayDate": "2021-04-10","brandId": 6,"brandName": "小米","brandImg": "http://macro-oss.oss-cn-shenzhen.aliyuncs.com/mall/images/201901 29/1e34aef2a409119018a4c6258e39ecfb_222_222.png","categoryId": 35,"categoryName": "手机数码","attrs": [{"attrId": 5,"attrName": "屏幕尺寸","attrValue": "65"},{"attrId": 6,"attrName": "机身颜色","attrValue": "金色"}]
}PUT /product_db/_doc/10
{"id": "35","name": "耐克NIKE 男子 休闲鞋 ROSHE RUN 运动鞋 511881-010黑色41码","keywords": "耐克运动鞋 鞋子","subTitle": "耐克NIKE 男子 休闲鞋 ROSHE RUN 运动鞋 511881-010黑色41码","price": "569","promotionPrice": "369","originalPrice": "899","pic": "http://macro-oss.oss-cn-shenzhen.aliyuncs.com/mall/images/20180615/5b 235bb9Nf606460b.jpg","sale": 999,"hasStock": true,"salecount": 399,"putawayDate": "2021-04-11","brandId": 58,"brandName": "NIKE","brandImg": "http://macro-oss.oss-cn-shenzhen.aliyuncs.com/mall/images/201806 15/timg (51).jpg","categoryId": 29,"categoryName": "男鞋","attrs": [{"attrId": 7,"attrName": "尺码","attrValue": "42"},{"attrId": 8,"attrName": "颜色","attrValue": "黑色"}]
} PUT /product_db/_doc/11
{"id": "36","name": "耐克NIKE 男子 气垫 休闲鞋 AIR MAX 90 ESSENTIAL 运动鞋 AJ1285-101白色41 码","keywords": "耐克运动鞋 鞋子","subTitle": "AIR MAX 90 ESSENTIAL 运动鞋 AJ1285-101白色","price": "769","promotionPrice": "469","originalPrice": "999","pic": "http://macro-oss.oss-cn-shenzhen.aliyuncs.com/mall/images/20180615/5b 19403eN9f0b3cb8.jpg","sale": 999,"hasStock": true,"salecount": 499,"putawayDate": "2021-04-13","brandId": 58,"brandName": "NIKE","brandImg": "http://macro-oss.oss-cn-shenzhen.aliyuncs.com/mall/images/201806 15/timg (51).jpg","categoryId": 29,"categoryName": "男鞋","attrs": [{"attrId": 7,"attrName": "尺码","attrValue": "44"},{"attrId": 8,"attrName": "颜色","attrValue": "白色"}]
}PUT /product_db/_doc/12
{"id": "37","name": "(华为)HUAWEI MateBook X Pro 2019款 13.9英寸3K触控全面屏 轻薄笔记本","keywords": "轻薄笔记本华为 笔记本电脑","subTitle": "轻薄华为笔记本 电脑","price": "4769","promotionPrice": "4469","originalPrice": "4999","pic": "http://tuling-mall.oss-cn-shenzhen.aliyuncs.com/tulingmall/images/202 00317/800_800_1555752016264mp.png","sale": 999,"hasStock": true,"salecount": 699,"putawayDate": "2021-04-14","brandId": 3,"brandName": "华为","brandImg": "http://macro-oss.oss-cn-shenzhen.aliyuncs.com/mall/images/201901 29/17f2dd9756d9d333bee8e60ce8c03e4c_222_222.jpg","categoryId": 19,"categoryName": "手机通讯","attrs": [{"attrId": 9,"attrName": "容量","attrValue": "16G"},{"attrId": 10,"attrName": "网络","attrValue": "4G"}]
} PUT /product_db/_doc/13
{"id": "38","name": "华为nova6se 手机 绮境森林 全网通(8G+128G)","keywords": "轻薄笔记本华为 手机","subTitle": "华为nova6se 手机","price": "6769","promotionPrice": "6469","originalPrice": "6999","pic": "http://macro-oss.oss-cn-shenzhen.aliyuncs.com/mall/images/20180607/5a c1bf58Ndefaac16.jpg","sale": 999,"hasStock": true,"salecount": 899,"putawayDate": "2021-04-15","brandId": 3,"brandName": "华为","brandImg": "http://macro-oss.oss-cn-shenzhen.aliyuncs.com/mall/images/201901 29/17f2dd9756d9d333bee8e60ce8c03e4c_222_222.jpg","categoryId": 19,"categoryName": "手机通讯","attrs": [{"attrId": 9,"attrName": "容量","attrValue": "64G"},{"attrId": 10,"attrName": "网络","attrValue": "5G"}]
}PUT /product_db/_doc/14
{"id": "39","name": "iPhone7/6s/8钢化膜苹果8Plus全屏复盖抗蓝光防窥防偷看手机膜","keywords": "手机膜","subTitle": "iPhone7/6s/8钢化膜苹果8Plus全屏复盖抗蓝光防窥防偷看手机膜","price": "29","promotionPrice": "39","originalPrice": "49","pic": "http://tuling-mall.oss-cn-shenzhen.aliyuncs.com/tulingmall/images/202 00311/6df99dab78bb2014.jpg","sale": 999,"hasStock": true,"salecount": 799,"putawayDate": "2021-04-16","brandId": 51,"brandName": "苹果","brandImg": "http://tuling-mall.oss-cn-shenzhen.aliyuncs.com/tulingmall/image s/20200311/2b84746650fc122d67749a876c453619.png","categoryId": 30,"categoryName": "手机配件","attrs": [{"attrId": 11,"attrName": "手机膜-材料","attrValue": "钢化"},{"attrId": 12,"attrName": "手机膜-颜色","attrValue": "白色"}]
} PUT /product_db/_doc/15
{"id": "40","name": "七匹狼短袖T恤男纯棉舒适春夏修身运动休闲短袖三条装 圆领3条装","keywords": "七匹狼服装 衣服","subTitle": "七匹狼短袖T恤男纯棉舒适春夏修身运动休闲短袖三条装 圆领3条装","price": "129","promotionPrice": "139","originalPrice": "149","pic": "http://tuling-mall.oss-cn-shenzhen.aliyuncs.com/tulingmall/images/202 00311/19e846e727dff337.jpg","sale": 999,"hasStock": true,"salecount": 199,"putawayDate": "2021-04-20","brandId": 49,"brandName": "七匹狼","brandImg": "http://macro-oss.oss-cn-shenzhen.aliyuncs.com/mall/images/201901 29/18d8bc3eb13533fab466d702a0d3fd1f40345bcd.jpg","categoryId": 8,"categoryName": "T恤","attrs": [{"attrId": 3,"attrName": "尺寸","attrValue": "M"},{"attrId": 4,"attrName": "颜色","attrValue": "白色"}]
} PUT /product_db/_doc/16
{"id": "41","name": "华为P40 Pro手机","keywords": "华为手机","subTitle": "华为P40 Pro手机","price": "2129","promotionPrice": "2139","originalPrice": "2149","pic": "http://macro-oss.oss-cn-shenzhen.aliyuncs.com/mall/images/20180607/5a c1bf58Ndefaac16.jpg","sale": 999,"hasStock": true,"salecount": 199,"putawayDate": "2021-05-03","brandId": 3,"brandName": "华为","brandImg": "http://macro-oss.oss-cn-shenzhen.aliyuncs.com/mall/images/201901 29/17f2dd9756d9d333bee8e60ce8c03e4c_222_222.jpg","categoryId": 19,"categoryName": "手机通讯","attrs": [{"attrId": 9,"attrName": "容量","attrValue": "128G"},{"attrId": 10,"attrName": "网络","attrValue": "5G"}]
} PUT /product_db/_doc/17
{"id": "42","name": "朵唯智能手机 4G全网通 老人学生双卡双待手机","keywords": "朵唯手机","subTitle": "朵唯手机后置双摄,国产虎贲芯片!优化散热结构!浅薄机身!朵唯4月特 惠!","price": "3129","promotionPrice": "3139","originalPrice": "3249","pic": "http://macro-oss.oss-cn-shenzhen.aliyuncs.com/mall/images/20180615/xi aomi.jpg","sale": 999,"hasStock": true,"salecount": 1199,"putawayDate": "2021-06-01","brandId": 59,"brandName": "朵唯","brandImg": "http://tuling-mall.oss-cn-shenzhen.aliyuncs.com/tulingmall/image s/20200311/2b84746650fc122d67749a876c453619.png","categoryId": 19,"categoryName": "手机通讯","attrs": [{"attrId": 9,"attrName": "容量","attrValue": "32G"},{"attrId": 10,"attrName": "网络","attrValue": "4G"}]
}

检索DSL语句构建

第1步:先查询 名字 和 是否有库存 和价格区间

第2步:排序

第3步 聚合统计查询

第4步 属性嵌套查询

post /product_db/_search
{"from": 0,"size": 10,"query": {"bool": {"must": [{"match": {"name": "手机"}}],"filter": [{"term": {"hasStock": true}},{"range": {"price": {"from": "1","to": "5000"}}}]}},"sort": [{"salecount": {"order": "desc"}}],"aggs": {"brand_aggs": {"terms": {"field": "brandId","size": 10},"aggs": {"brand_name_aggs": {"terms": {"field": "brandName"}},"brand_img_aggs": {"terms": {"field": "brandImg"}}}},"category_aggs": {"terms": {"field": "categoryId","size": 10},"aggs": {"cate_name_aggs": {"terms": {"field": "categoryName"}}}},"attrs_aggs": {"nested": {"path": "attrs"},"aggs": {"attr_id_aggs": {"terms": {"field": "attrs.attrId"},"aggs": {"attr_name_aggs": {"terms": {"field": "attrs.attrName"}},"arrt_val_aggs": {"terms": {"field": "attrs.attrValue"}}}}}}},"highlight": {"pre_tags": ["<b style='color:red'>"],"post_tags": ["</b>"],"fields": [{"name": {}}]}
}


在 must里面可以搜索分类ID不过性能没有Filter里面的好

在filter里面也能用

嵌套nested组合查询

post /product_db/_search
{"from": 0,"size": 10,"query": {"nested": {"path": "attrs","query": {"bool": {"must": [{"term": {"attrs.attrId" : 9}}]}}}}
}

非组合查询用下面这段就行了

post /product_db/_search
{"from": 0,"size": 10,"query": {"nested": {"path": "attrs","query": {"term": {"attrs.attrId": 9}}}}
}
post /product_db/_search
{"from": 0,"size": 10,"query": {"bool": {"must": [{"match": {"name": "手机"}},{"nested": {"path": "attrs","query": {"bool": {"must": [{"term": {"attrs.attrId": 9}}]}}}}],"filter": [{"term": {"hasStock": true}},{"term": {"categoryId": 19}},{"term": {"brandId": 59}},{"range": {"price": {"from": "1","to": "5000"}}}]}},"sort": [{"salecount": {"order": "desc"}}],"highlight": {"pre_tags": ["<b style='color:red'>"],"post_tags": ["</b>"],"fields": [{"name": {}}]}
}

非组合查询用下面这段就行了

post /product_db/_search
{"from": 0,"size": 10,"query": {"bool": {"must": [{"match": {"name": "手机"}},{"nested": {"path": "attrs","query": {"term": {"attrs.attrId": 9}}}}],"filter": [{"term": {"hasStock": true}},{"term": {"categoryId": 19}},{"term": {"brandId": 59}},{"range": {"price": {"from": "1","to": "5000"}}}]}},"sort": [{"salecount": {"order": "desc"}}],"highlight": {"pre_tags": ["<b style='color:red'>"],"post_tags": ["</b>"],"fields": [{"name": {}}]}
}


控制层:
@ResponseBody
@RequestMapping(value = "/searchList")
public CommonResult<ESResponseResult> listPage(ESRequestParam param, HttpServletRequest request) {//1、根据传递来的页面的查询参数,去es中检索商品ESResponseResult searchResult = tulingMallSearchService.search(param);return CommonResult.success(searchResult);
}
服务层:
@Override
public ESResponseResult search(ESRequestParam param) {try {//1、构建检索对象-封装请求相关参数信息SearchRequest searchRequest = startBuildRequestParam(param);//2、进行检索操作SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);//3、分析响应数据,封装成指定的格式ESResponseResult responseResult = startBuildResponseResult(response, param);return responseResult;} catch (Exception e) {e.printStackTrace();}return null;}
/*** 封装请求参数信息* 关键字查询、根据属性、分类、品牌、价格区间、是否有库存等进行过滤、分页、高亮、以及聚合统计品牌分类属性**/
private SearchRequest startBuildRequestParam(ESRequestParam param) {SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();/*** 关键字查询、根据属性、分类、品牌、价格区间、是否有库存等进行过滤、分页、高亮、以及聚合统计品牌分类属性*/BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();//1、if (!StringUtils.isEmpty(param.getKeyword())) {//单字段查询//boolQueryBuilder.must(QueryBuilders.matchQuery("name", param.getKeyword()));//多字段查询boolQueryBuilder.must(QueryBuilders.multiMatchQuery(param.getKeyword(),"name","keywords","subTitle"));}//2、根据类目ID进行过滤if (null != param.getCategoryId()) {boolQueryBuilder.filter(QueryBuilders.termQuery("categoryId", param.getCategoryId()));}//3、根据品牌ID进行过滤if (null != param.getBrandId() && param.getBrandId().size() > 0) {boolQueryBuilder.filter(QueryBuilders.termsQuery("brandId", param.getBrandId()));}//4、根据属性进行相关过滤if (param.getAttrs() != null && param.getAttrs().size() > 0) {param.getAttrs().forEach(item -> {//attrs=1_白色&2_4核BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();//attrs=1_64GString[] s = item.split("_");String attrId = s[0];String[] attrValues = s[1].split(":");//这个属性检索用的值boolQuery.must(QueryBuilders.termQuery("attrs.attrId", attrId));boolQuery.must(QueryBuilders.termsQuery("attrs.attrValue", attrValues));NestedQueryBuilder nestedQueryBuilder = QueryBuilders.nestedQuery("attrs", boolQuery, ScoreMode.None);boolQueryBuilder.filter(nestedQueryBuilder);});}//5、是否有库存if (null != param.getHasStock()) {boolQueryBuilder.filter(QueryBuilders.termQuery("hasStock", param.getHasStock() == 1));}/* if (price.length == 2) {//price: _5000if (param.getPrice().startsWith("_")) {rangeQueryBuilder.lte(price[1]);}else{//price: 1_5000rangeQueryBuilder.gte(price[0]).lte(price[1]);}} else if (price.length == 1) {//price: 1_if (param.getPrice().endsWith("_")) {rangeQueryBuilder.gte(price[0]);}
}*///6、根据价格过滤if (!StringUtils.isEmpty(param.getPrice())) {//价格的输入形式为:10-100(起始价格和最终价格)或-100(不指定起始价格)或10-(不限制最终价格)RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("price");String[] price = param.getPrice().split("_");if (price.length == 2) {rangeQueryBuilder.gte(price[0]).lte(price[1]);} else if (price.length == 1) {if (param.getPrice().startsWith("_")) {rangeQueryBuilder.lte(price[1]);}if (param.getPrice().endsWith("_")) {rangeQueryBuilder.gte(price[0]);}}boolQueryBuilder.filter(rangeQueryBuilder);}//封装所有查询条件searchSourceBuilder.query(boolQueryBuilder);/*** 实现排序、高亮、分页操作*///排序//页面传入的参数值形式 sort=price_asc/descif (!StringUtils.isEmpty(param.getSort())) {String sort = param.getSort();String[] sortFileds = sort.split("_");System.out.println("sortFileds:"+sortFileds.length);if(!StringUtils.isEmpty(sortFileds[0])){SortOrder sortOrder = "asc".equalsIgnoreCase(sortFileds[1]) ? SortOrder.ASC : SortOrder.DESC;searchSourceBuilder.sort(sortFileds[0], sortOrder);}}//分页查询searchSourceBuilder.from((param.getPageNum() - 1) * SearchConstant.PAGE_SIZE);searchSourceBuilder.size(SearchConstant.PAGE_SIZE);//高亮显示if (!StringUtils.isEmpty(param.getKeyword())) {HighlightBuilder highlightBuilder = new HighlightBuilder();highlightBuilder.field("name");highlightBuilder.preTags("<b style='color:red'>");highlightBuilder.postTags("</b>");searchSourceBuilder.highlighter(highlightBuilder);}/*** 对品牌、分类信息、属性信息进行聚合分析*///1. 按照品牌进行聚合TermsAggregationBuilder brand_agg = AggregationBuilders.terms("brand_agg");brand_agg.field("brandId").size(50);//1.1 品牌的子聚合-品牌名聚合brand_agg.subAggregation(AggregationBuilders.terms("brand_name_agg").field("brandName").size(1));//1.2 品牌的子聚合-品牌图片聚合brand_agg.subAggregation(AggregationBuilders.terms("brand_img_agg").field("brandImg").size(1));searchSourceBuilder.aggregation(brand_agg);//2. 按照分类信息进行聚合TermsAggregationBuilder category_agg = AggregationBuilders.terms("category_agg");category_agg.field("categoryId").size(50);category_agg.subAggregation(AggregationBuilders.terms("category_name_agg").field("categoryName").size(1));searchSourceBuilder.aggregation(category_agg);//2. 按照属性信息进行聚合NestedAggregationBuilder attr_agg = AggregationBuilders.nested("attr_agg", "attrs");//2.1 按照属性ID进行聚合TermsAggregationBuilder attr_id_agg = AggregationBuilders.terms("attr_id_agg").field("attrs.attrId");attr_agg.subAggregation(attr_id_agg);//2.1.1 在每个属性ID下,按照属性名进行聚合attr_id_agg.subAggregation(AggregationBuilders.terms("attr_name_agg").field("attrs.attrName").size(1));//2.1.1 在每个属性ID下,按照属性值进行聚合attr_id_agg.subAggregation(AggregationBuilders.terms("attr_value_agg").field("attrs.attrValue").size(50));searchSourceBuilder.aggregation(attr_agg);System.out.println("构建的DSL语句 {}:"+ searchSourceBuilder.toString());SearchRequest searchRequest = new SearchRequest(new String[]{SearchConstant.INDEX_NAME}, searchSourceBuilder);return searchRequest;
}/*** 封装查询到的结果信息* 关键字查询、根据属性、分类、品牌、价格区间、是否有库存等进行过滤、分页、高亮、以及聚合统计品牌分类属性*/
private ESResponseResult startBuildResponseResult(SearchResponse response, ESRequestParam param) {ESResponseResult result = new ESResponseResult();//1、获取查询到的商品信息SearchHits hits = response.getHits();List<EsProduct> esModels = new ArrayList<>();//2、遍历所有商品信息if (hits.getHits() != null && hits.getHits().length > 0) {for (SearchHit hit : hits.getHits()) {String sourceAsString = hit.getSourceAsString();EsProduct esModel = JSON.parseObject(sourceAsString, EsProduct.class);//2.1 判断是否按关键字检索,若是就显示高亮,否则不显示if (!StringUtils.isEmpty(param.getKeyword())) {//2.2 拿到高亮信息显示标题HighlightField name = hit.getHighlightFields().get("name");//2.3 判断name中是否含有查询的关键字(因为是多字段查询,因此可能不包含指定的关键字,假设不包含则显示原始name字段的信息)String nameValue = name!=null ? name.getFragments()[0].string() : esModel.getName();esModel.setName(nameValue);}esModels.add(esModel);}}result.setProducts(esModels);//3、当前商品涉及到的所有品牌信息,小米手机和小米电脑都属于小米品牌,过滤重复品牌信息Set<ESResponseResult.BrandVo> brandVos = new LinkedHashSet<>();//获取到品牌的聚合ParsedLongTerms brandAgg = response.getAggregations().get("brand_agg");for (Terms.Bucket bucket : brandAgg.getBuckets()) {ESResponseResult.BrandVo brandVo = new ESResponseResult.BrandVo();//获取品牌的idlong brandId = bucket.getKeyAsNumber().longValue();brandVo.setBrandId(brandId);//获取品牌的名字ParsedStringTerms brandNameAgg = bucket.getAggregations().get("brand_name_agg");String brandName = brandNameAgg.getBuckets().get(0).getKeyAsString();brandVo.setBrandName(brandName);//获取品牌的LOGOParsedStringTerms brandImgAgg = bucket.getAggregations().get("brand_img_agg");String brandImg = brandImgAgg.getBuckets().get(0).getKeyAsString();brandVo.setBrandImg(brandImg);System.out.println("brandId:"+brandId+"brandName:"+brandName+"brandImg");brandVos.add(brandVo);}System.out.println("brandVos.size:"+brandVos.size());result.setBrands(brandVos);//4、当前商品相关的所有类目信息//获取到分类的聚合List<ESResponseResult.categoryVo> categoryVos = new ArrayList<>();ParsedLongTerms categoryAgg = response.getAggregations().get("category_agg");for (Terms.Bucket bucket : categoryAgg.getBuckets()) {ESResponseResult.categoryVo categoryVo = new ESResponseResult.categoryVo();//获取分类idString keyAsString = bucket.getKeyAsString();categoryVo.setCategoryId(Long.parseLong(keyAsString));//获取分类名ParsedStringTerms categoryNameAgg = bucket.getAggregations().get("category_name_agg");String categoryName = categoryNameAgg.getBuckets().get(0).getKeyAsString();categoryVo.setCategoryName(categoryName);categoryVos.add(categoryVo);}result.setCategorys(categoryVos);//5、获取商品相关的所有属性信息List<ESResponseResult.AttrVo> attrVos = new ArrayList<>();//获取属性信息的聚合ParsedNested attrsAgg = response.getAggregations().get("attr_agg");ParsedLongTerms attrIdAgg = attrsAgg.getAggregations().get("attr_id_agg");for (Terms.Bucket bucket : attrIdAgg.getBuckets()) {ESResponseResult.AttrVo attrVo = new ESResponseResult.AttrVo();//获取属性ID值long attrId = bucket.getKeyAsNumber().longValue();attrVo.setAttrId(attrId);//获取属性的名字ParsedStringTerms attrNameAgg = bucket.getAggregations().get("attr_name_agg");String attrName = attrNameAgg.getBuckets().get(0).getKeyAsString();attrVo.setAttrName(attrName);//获取属性的值ParsedStringTerms attrValueAgg = bucket.getAggregations().get("attr_value_agg");List<String> attrValues = attrValueAgg.getBuckets().stream().map(item -> item.getKeyAsString()).collect(Collectors.toList());attrVo.setAttrValue(attrValues);attrVos.add(attrVo);}result.setAttrs(attrVos);//6、进行分页操作result.setPageNum(param.getPageNum());//获取总记录数long total = hits.getTotalHits().value;result.setTotal(total);//计算总页码int totalPages = (int) total % SearchConstant.PAGE_SIZE == 0 ?(int) total / SearchConstant.PAGE_SIZE : ((int) total / SearchConstant.PAGE_SIZE + 1);result.setTotalPages(totalPages);List<Integer> pageNavs = new ArrayList<>();for (int i = 1; i <= totalPages; i++) {pageNavs.add(i);}result.setPageNavs(pageNavs);return result;
}


匹配  短语的查询如下:

post /xhd-java-app-log/_search
{"query": {"bool": {"must": [{"bool": {"should": [{"match_phrase": {"message": "处理津贴错误"}},{"match_phrase": {"content": "处理津贴错误"}}]}}],"filter": [{"range": {"create_time": {"from": 1636473600000,"to": 1636531490858}}}]}}
}------------------------------------------------------------------------------
--------------------------------------------------------------------------------
post /xhd-java-app-log/_search
{"query": {"bool": {"should": [{"match_phrase": {"message": "处理津贴错误"}},{"match_phrase": {"content": "处理津贴错误"}}],"filter": [{"range": {"create_time": {"from": 1636473600000,"to": 1636531490858}}}]}}
}

elk组合查询 es组合查询相关推荐

  1. 【ES知识】ES基础查询语法一览

    大家好,我是老坛. 更多优质文章资源请关注同名公众号:老坛聊开发 Elasticsearch是一个分布式的RESTful 风格的搜索和数据分析引擎,它使用方便,查询速度快,因此也被越来越多的开发人员使 ...

  2. Elasticsearch(es) 查询语句语法详解

    Elasticsearch 查询语句采用基于 RESTful 风格的接口封装成 JSON 格式的对象,称之为 Query DSL.Elasticsearch 查询分类大致分为全文查询.词项查询.复合查 ...

  3. ES基本查询,filter 查询,组合查询

    Elasticsearch 是功能强大的全文搜索引擎,用它的目的就是为了能快速的查询你想好要的数据 基本查询:利用Elasticsearch内置查询条件进行查询 组合查询:把多个基本查询组合在一起的复 ...

  4. ES组合查询-Boolean Query

    BooleanQuery可以将多个查询语句组合在一起.下面是一个基础的模板: {"query": {"bool" : {"must" : { ...

  5. 01.query的分类-条件查询和组合查询

    文章目录 1. es单个条件查询和组合查询 2.query和filter context 1. query context 2. filter context 3.使用样例 1. es单个条件查询和组 ...

  6. elasticsearch 建立索引、增删改查 及简单查询和组合查询的学习笔记

    创建一个索引(数据库) PUT lagou # 索引名称 {"settings": {"index":{"number_of_shards" ...

  7. MySQL 学习笔记(4)— 组合查询、子查询、插入数据、更新/删除表数据、增加/删除表中的列以及重命名表

    1. 组合查询 1.表的加减法 表的加法,即求 product 和 product2 的并集,UNION 运算会除去重复的记录 SELECT product_id, product_name FROM ...

  8. mysql中实现分类统计查询的步骤_实验07:数据库的组合查询和统计查询

    实验6:数据库的组合查询和统计查询实验 本实验需要 4 学时. 一.实验目的 使学生熟练掌握SQL Server 查询分析器的使用方法,加深对SQL 和Transact-SQL 语言的查询语句的理解. ...

  9. SQL语句汇总(三)——聚合函数、分组、子查询及组合查询

    聚合函数: SQL中提供的聚合函数可以用来统计.求和.求最值等等. 分类: –COUNT:统计行数量 –SUM:获取单个列的合计值 –AVG:计算某个列的平均值 –MAX:计算列的最大值 –MIN:计 ...

最新文章

  1. php_mongo.dll下载(php操作mongoDB需要)
  2. “AI明星”第四范式C轮融资超10亿元,估值约12亿美元
  3. 灰度图像--图像增强 平滑之均值滤波、高斯滤波
  4. 《Effective Java 2nd》第4章 类和接口
  5. 最佳的七十五个网络分析和安全工具
  6. JAVA集合二:HashMap和Hashtable
  7. ‘Microsoft Office Enterprise 2007 在安装过程中出错‘ 的解决方法
  8. 自然语言处理要解决的问题
  9. 一套价值十万的微信公众号采集解决方案
  10. 什么是面向接口编程?
  11. Unity网格编程篇(二) 非常详细的Mesh编程入门文章
  12. 。三十功名尘与土,八千里路云和月。莫等闲,白了少年头,空悲切
  13. 基于Java的亚马逊“手机”评论爬虫的情感分类分析
  14. 苹果cmsV10MXone Pro自适应模板 站长亲测 全网首发
  15. Numpy数组的索引与切片:取数组的特定行列
  16. 来自全国各地的65位高校教师接龙晒工资,供参考
  17. Ubuntu 设置自动切换桌面壁纸
  18. 最有意思的100条英语(转)
  19. 数字组合(算法竞赛进阶指南)
  20. 问题 G: 向右看齐

热门文章

  1. 数据库中索引(index)介绍
  2. kaggle住房预测项目——第2部分(bagging)
  3. 以太坊:C++客户端的安装与定制(二)
  4. MySql设置主键,外键命令
  5. python项目打包部署到linux系统_把python项目打包到linux执行-女性时尚流行美容健康娱乐mv-ida网...
  6. SpringBoot项目打包成war包并部署到服务器上
  7. 手机运行慢可以刷机吗_一加1手机A0001系统运行速度变慢变卡顿了_如何进行刷机教程操作...
  8. find_element_by_xpath画横线不能用
  9. 软件测试常见概念(软件生命周期、软件开发模型、软件质量模型、软件缺陷管理、软件测试概述、软件测试分类、软件测试与软件开发、软件测试原则、黑盒测试方法、白盒测试方法、性能测试)
  10. 为什么我的mac插入耳机耳机没有声音呢?