首页 > 解决方案 > 如何计算 Elasticsearch 中每个产品的平均评分

问题描述

我有products以下映射的索引:

{
  "products" : {
    "mappings" : {
      "properties" : {
        "@timestamp" : {
          "type" : "date"
        },
        "name":{
          "type": "text"
        }, 
        "price" : {
          "type" : "integer"
        },
        "product_review_rel" : {
          "type" : "join",
          "eager_global_ordinals" : true,
          "relations" : {
            "product" : "review"
          }
        },
        "rate" : {
          "type" : "integer"
        }
      }
    }
  }
}

该索引包含产品和评论,您可以在product_review_rel字段中看到。产品包含名称、价格、...字段。评论包含费率、... 字段。

我想获得每种产品的平均评分。怎么做?另一个问题,是否可以在同一请求中从以下查询返回的产品中返回平均评分:

{
  "query": {
    "nested": {
      "path": "translations",
      "query": {
        "multi_match": {
          "query": "kem chống nắng",
          "fields": [
            "name"
          ],
          "analyzer":"vi_analyzer"
        }
      }
    }
  }
}

更新 1:复合聚合

GET products/_search
{
  "query": {
    "nested": {
      "path": "translations",
      "query": {
        "multi_match": {
          "query": "kem chống nắng",
          "fields": [
            "translations.name",
            "translations.description"
          ],
          "analyzer": "vi_analyzer"
        }
      }
    }
  },
  "aggs": {
    "products": {
      "composite": {
        "sources": [
          {
            "id": {
              "terms": {
                "field": "_id"
              }
            }
          }
        ]
      },
      "aggs": {
        "reviews": {
          "children": {
            "type": "review"
          },
          "aggs": {
            "rating": {
              "avg": {
                "field": "rate"
              }
            }
          }
        }
      }
    }
  }
}```

标签: elasticsearchaggregate

解决方案


推荐阅读