《Elastic Stack 实战手册》——三、产品能力——3.4.入门篇——3.4.2.Elasticsearch基础应用——3.4.2.7.Nested数据类型(上) https://developer.aliyun.com/article/1230844
定义分组为 Nested 数据结构类型
PUT goods_info_nested { "mappings": { "properties": { "goodsName": { "type": "text", "analyzer": "ik_smart" }, "skuCode": { "type": "keyword" }, "brandName": { "type": "keyword" }, "shopCode": { "type": "keyword" }, "publicPrice": { "type": "float" }, "groupPrice": { "type": "nested", "properties": { "boxLevelPrice": { "type": "float" }, "level": { "type": "keyword" } } } } } } #插入同样的测试数据 POST goods_info_nested/_bulk {"index":{"_id":1}} {"goodsName":"美国苹果","skuCode":"skuCode1","brandName":"美国苹果","shopCode":"sc00001","publicPrice":"8388.88","groupPrice":[{"boxLevelPrice":"4888.00","level":"A"},{"boxLevelPrice":"6888.00","level":"B"}]} {"index":{"_id":2}} {"goodsName":"山东苹果","skuCode":"skuCode2","brandName":"山东苹果","shopCode":"sc00001","publicPrice":"7388.88","groupPrice":[{"boxLevelPrice":"5888.00","level":"A"},{"boxLevelPrice":"4888.00","level":"B"}]} #查询 POST goods_info_nested/_search { "query": { "nested": { "path": "groupPrice", "query": { "bool": { "must": [ { "match": { "groupPrice.level": "A" } }, { "match": { "groupPrice.boxLevelPrice": "4888.00" } } ] } } } } } #返回: "hits" : [ { "_index" : "goods_info_nested", "_type" : "_doc", "_id" : "1", "_score" : 1.3862942, "_source" : { "goodsName" : "美国苹果", "skuCode" : "skuCode1", "brandName" : "美国苹果", "shopCode" : "sc00001", "publicPrice" : "8388.88", "groupPrice" : [ { "boxLevelPrice" : "4888.00", "level" : "A" }, { "boxLevelPrice" : "6888.00", "level" : "B" } ] } } ]
同样查询 groupPrice.boxLevelPrice 为"4888.00" 且 level 为"A"的数据,显然只有文档 1 满足,通过查询也验证了此结论,说明 Nested 查询生效,解决了嵌套查询的问题。
Nested 在 Aggregation 中的应用
在对 Nested Object 进行聚合操作时,我们需要使用到 Nested Aggregation,我们需要聚合查询最大的分组价格( groupPrice )。
POST /goods_info_nested/_search { "query": { "match": { "goodsName": "苹果" } }, "aggs": { "groupPrice": { "nested": { "path": "groupPrice" }, "aggs": { "max_price": { "max": { "field": "groupPrice.boxLevelPrice" } } } } } } #返回 { ..... "aggregations" : { "groupPrice" : { "doc_count" : 4, "max_price" : { "value" : 6888.0 } } } }
创作人简介:
李增胜,Elasticsearch 认证工程师、PMP 项目管理认证,现就职于汇通达网络股份有限公司,任产业交易平台交易域技术经理,从事微服务架构、搜索架构方向开发与管理工作。技术关注:电商、产业互联网等领域。