如何计算百分位数?

问题描述 投票:9回答:2

我将以下访问日志存储在mongodb实例中:

Time                           Service                      Latency
[27/08/2013:11:19:22 +0000]    "POST Service A HTTP/1.1"    403
[27/08/2013:11:19:24 +0000]    "POST Service B HTTP/1.1"    1022 
[27/08/2013:11:22:10 +0000]    "POST Service A HTTP/1.1"    455 

Oracle中是否有类似PERCENTILE_DISC的分析功能来计算百分位数?

我想计算一段时间内的延迟百分比。

mongodb mongodb-query percentile
2个回答
9
投票

似乎仍然没有原生方法来计算百分位数,但是通过组合一些聚合运算符,您可以获得相同的结果。

db.items.aggregate([
        {'$group': {
            '_id': {
                'league': '$league',
                'base': '$base',
                'type': '$type'
            },
            'value': {'$push': '$chaosequiv'}
        }},
        {'$unwind': '$value'},
        {'$sort': {'value': 1}},
        {'$group': {'_id': '$_id', 'value': {'$push': '$value'}}},
        {'$project': {
            '_id': 1,
            'value': {'$arrayElemAt': ['$value', {'$floor': {'$multiply': [0.25, {'$size': '$value'}]}}]}
        }}
    ], allowDiskUse=True)

[注意,我在pymongo中编写了我的原始代码,用于解决一个问题,该问题需要对第一组中的3个字段进行分组,因此这可能比单个字段所需的更为复杂。我将针对此问题编写解决方案,但我认为没有足够的具体信息。


0
投票

[开始Mongo 4.4$group阶段有了一个新的聚合运算符$accumulator,当通过javascript用户定义的函数对文档进行分组时,允许对它们进行自定义累积。

因此,为了找到第20个百分位数:

$accumulator

累加器:

  • 累积在字段// { "a" : 25, "b" : 12 } // { "a" : 89, "b" : 73 } // { "a" : 25, "b" : 7 } // { "a" : 25, "b" : 17 } // { "a" : 89, "b" : 14 } // { "a" : 89, "b" : 17 } // { "a" : 25, "b" : 24 } // { "a" : 25, "b" : 15 } // { "a" : 25, "b" : 22 } // { "a" : 25, "b" : 94 } db.collection.aggregate([ { $group: { _id: "$a", percentile: { $accumulator: { accumulateArgs: ["$b"], init: function() { return []; }, accumulate: function(bs, b) { return bs.concat(b); }, merge: function(bs1, bs2) { return bs1.concat(bs2); }, finalize: function(bs) { bs.sort(function(a, b) { return a - b }); return bs[Math.floor(bs.length*.2) + 1]; }, lang: "js" } } }} ]) // { "_id" : 89, "percentile" : 17 } // { "_id" : 25, "percentile" : 15 } b
  • 初始化为空数组(accumulateArgs
  • 在数组(initb)中累积accumulate个项目
  • 最后对merge个项目(b)执行百分位计算
© www.soinside.com 2019 - 2024. All rights reserved.