Агрегирование по полю, а затем сумма значения другого поля - PullRequest
1 голос
/ 10 июня 2019

Мне нужно агрегировать по одному полю, а затем, в той же агрегации, вычислить сумму с другим значением поля.Но при выполнении запроса первая агрегация в порядке, но сумма всегда равна 0.

Пример индекса:


{
    "mappings": {
        "transaction": {
            "dynamic": "strict",
            "properties": {
                "transaction": {
                    "properties": {
                        "amount": {
                            "type": "double"
                        }
                    }
                },
                "infrastructureElement": {
                    "type": "nested",
                    "properties": {
                        "infrastructureElementSubType": {
                            "type": "keyword"
                        }
                    }
                }
            }
        }
    }
}

В приведенном ниже запросе агрегируйте по infrastructureElement.infrastructureElementSubType, а затем суммируйте значениеtransactionPurchase.amount в другом формате:

{
    "aggs": {
        "group_by_infrastructure_element": {
            "nested": {
                "path": "infrastructureElement"
            },
            "aggs": {
                "group_by_ie_subtype": {
                    "terms": {
                        "field": "infrastructureElement.infrastructureElementSubType"
                    },
                    "aggs": {
                        "revenue": {
                            "sum": {
                                "field": "transactionPurchase.amount"
                            }
                        }
                    }
                }
            }
        }
    }
}

Текущий результат:

{
    "took": 6,
    "timed_out": false,
    "_shards": {
        "total": 5,
        "successful": 5,
        "skipped": 0,
        "failed": 0
    },
    "hits": {
    ...
    },
    "aggregations": {
        "group_by_infrastructure_element": {
            "doc_count": 365,
            "group_by_ie_subtype": {
                "doc_count_error_upper_bound": 0,
                "sum_other_doc_count": 0,
                "buckets": [
                    {
                        "key": "MOBILE",
                        "doc_count": 1,
                        "revenue": {
                            "value": 0
                        }
                    }
                ]
            }
        }
    }
}

Заранее спасибо!

1 Ответ

1 голос
/ 11 июня 2019

Вам потребуется использовать Обратное вложенное агрегирование и затем цепочку в Суммарная агрегация для расчета того, что вы ищете:

Запрос агрегации:

POST <your_index_name>/_search
{  
   "size":0,
   "aggs":{  
      "myterms":{  
         "nested":{  
            "path":"infrastructureElement"
         },
         "aggs":{  
            "myterms":{  
               "terms":{  
                  "field":"infrastructureElement.infrastructureElementSubType",
                  "size":10
               },
               "aggs":{  
                  "reverse":{  
                     "reverse_nested":{},
                     "aggs":{  
                        "revenue":{  
                           "sum":{  
                              "field":"transaction.amount"
                           }
                        }
                     }
                  }
               }
            }
         }
      }
   }
}

Также обратите внимание, как структурировано ваше отображение, поле transaction - это не Nested Type, а простое Object Type. Теперь, если вы находитесь во вложенной агрегации, вам нужно будет вернуться обратно к корню и затем выполнить агрегирование метрик, например, сумма для расчета amount

Обратите внимание на ответ ниже для образцов документов, которые я создал.

POST someaggregation/_doc/1
{
  "transaction":{
    "amount": 100
  },
  "infrastructureElement": [
    {
      "infrastructureElementSubType": "type1"
    },
    {
      "infrastructureElementSubType": "type2"
    }
  ]
}

POST someaggregation/_doc/2
{
  "transaction":{
    "amount": 100
  },
  "infrastructureElement": [
    {
      "infrastructureElementSubType": "type1"
    },
    {
      "infrastructureElementSubType": "type2"
    }
  ]
}

POST someaggregation/_doc/3
{
  "transaction":{
    "amount": 100
  },
  "infrastructureElement": [
    {
      "infrastructureElementSubType": "type3"
    },
    {
      "infrastructureElementSubType": "type4"
    }
  ]
}

Ответ:

{
  "took" : 519,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 3,
      "relation" : "eq"
    },
    "max_score" : null,
    "hits" : [ ]
  },
  "aggregations" : {
    "myterms" : {
      "doc_count" : 6,
      "myterms" : {
        "doc_count_error_upper_bound" : 0,
        "sum_other_doc_count" : 0,
        "buckets" : [
          {
            "key" : "type1",
            "doc_count" : 2,
            "reverse" : {
              "doc_count" : 2,
              "revenue" : {
                "value" : 200.0
              }
            }
          },
          {
            "key" : "type2",
            "doc_count" : 2,
            "reverse" : {
              "doc_count" : 2,
              "revenue" : {
                "value" : 200.0
              }
            }
          },
          {
            "key" : "type3",
            "doc_count" : 1,
            "reverse" : {
              "doc_count" : 1,
              "revenue" : {
                "value" : 100.0
              }
            }
          },
          {
            "key" : "type4",
            "doc_count" : 1,
            "reverse" : {
              "doc_count" : 1,
              "revenue" : {
                "value" : 100.0
              }
            }
          }
        ]
      }
    }
  }
}

Надеюсь, это поможет!

Не стесняйтесь голосовать и / или принимать этот ответ, если вы считаете, что это решит вашу проблему :)

...