17

elasticsearch 实现聚合后两个字段相除、相加、相减、相乘,运算

 2 years ago
source link: https://segmentfault.com/a/1190000040082906
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

elasticsearch 实现聚合后两个字段相除、相加、相减、相乘,运算

有个需求,在sql中的计算方式是:

sum(cost) / 100 / sum(view_count) * 1000

统计出平均千次展现均价,成本按分存储。

在es中需要聚合cost和view_count 之后再运算。折腾了半天,记录下:

"aggs" => [
    'total_cost_count' => [
        'sum' => [
            'field' => 'cost'
        ]
    ],
    'total_view_count' => [
        'sum' => [
            'field' => 'view_count'
        ]
    ],
    '(total_cost / total_view)' => [
        'bucket_script' => [
            'buckets_path' => [
                'cost' => 'total_cost_count',
                'view_count' => 'total_view_count',
            ],
            'script' => [
                'source' => "params.cost / params.unit / params.view_count * params.days",
                'params' => [
                    'unit' => 100,
                    'days' => 1000,
                ]
            ]
        ]
    ]
],

调试过程中报错信息:

  • Only sibling pipeline aggregations are allowed at the top level

    • 在顶层只允许兄弟管道聚合。也就是聚合运算只能在同一个桶内。

参考文档:https://www.elastic.co/guide/en/elasticsearch/painless/7.13/painless-bucket-script-agg-context.html


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK