前言

  • 本文的例子来自铭毅天下,并得到了铭毅天下本人的指导
  • 本文内容对 Elasticsearch 7.17 适用

示例

  • 多商品在不同分类下有不同的排名,取某个分类下的topN
  • 创建 mappings
PUT products
{
  "mappings": {
    "properties": {
      "product_id": {
        "type": "integer"
      },
      "product_name": {
        "type": "keyword"
      },
      "categories": {
        "type": "nested",
        "properties": {
          "category_name": {
            "type": "keyword"
          },
          "rank": {
            "type": "integer"
          }
        }
      }
    }
  }
}
  • 写入样例数据
POST /products/_bulk
{"index":{"_id":1}}
{"product_id":1,"product_name":"智能手机","categories":[{"category_name":"A","rank":1},{"category_name":"B","rank":3},{"category_name":"C","rank":2}]}
{"index":{"_id":2}}
{"product_id":2,"product_name":"耳机","categories":[{"category_name":"A","rank":4},{"category_name":"B","rank":1},{"category_name":"C","rank":3}]}
{"index":{"_id":3}}
{"product_id":3,"product_name":"便携式充电器","categories":[{"category_name":"A","rank":2},{"category_name":"B","rank":5},{"category_name":"C","rank":1}]}
{"index":{"_id":4}}
{"product_id":4,"product_name":"智能手表","categories":[{"category_name":"A","rank":3},{"category_name":"B","rank":2},{"category_name":"C","rank":4}]}
  • 铭毅天下 给的参考查询语句,用到了聚合
GET products/_search
{
  "size": 0,
  "aggs": {
    "filtered_category": {
      "nested": {
        "path": "categories"
      },
      "aggs": {
        "category_name": {
          "filter": {
            "term": {
              "categories.category_name": "A"
            }
          },
          "aggs": {
            "top_products": {
              "top_hits": {
                "size": 3,
                "sort": [
                  {
                    "categories.rank": {
                      "order": "asc"
                    }
                  }
                ]
              }
            }
          }
        }
      }
    }
  }
}
GET products/_search
{
  "sort": [
    {
      "categories.rank": {
        "order": "asc",
        "nested": {
          "path": "categories",
          "filter": {
            "term": {
              "categories.category_name": "A"
            }
          }
        }
      }
    }
  ],
  "size": 3
}

相关文献

本文出自 qbit snap

qbit
271 声望279 粉丝