imay commented on a change in pull request #1432: Add percentile_approx 
aggregate function
URL: https://github.com/apache/incubator-doris/pull/1432#discussion_r302101549
 
 

 ##########
 File path: be/src/exprs/aggregate_functions.cpp
 ##########
 @@ -231,6 +232,81 @@ void AggregateFunctions::avg_update(FunctionContext* ctx, 
const T& src, StringVa
     ++avg->count;
 }
 
+struct PercentileApproxState {
+public:
+    PercentileApproxState() {
+        digest = new TDigest();
+    }
+    ~PercentileApproxState() {
+        delete digest;
+    }
+    
+    TDigest *digest = nullptr;
+    double targetQuantile = -1.0;
+};
+
+void AggregateFunctions::percentile_approx_init(FunctionContext* ctx, 
StringVal* dst) {
+    dst->is_null = false;
+    dst->len = sizeof(PercentileApproxState);
+    dst->ptr = (uint8_t*) new PercentileApproxState();
+};
+
+template<typename T>
+void AggregateFunctions::percentile_approx_update(FunctionContext* ctx, const 
T& src, const DoubleVal& quantile, StringVal* dst) {
+    if (src.is_null) {
+        return;
+    }
+    DCHECK(dst->ptr != NULL);
+    DCHECK_EQ(sizeof(PercentileApproxState), dst->len);
+
+    PercentileApproxState* percentile = 
reinterpret_cast<PercentileApproxState*>(dst->ptr);
+    percentile->digest->add(src.val);
+    percentile->targetQuantile = quantile.val;
+}
+
+StringVal AggregateFunctions::percentile_approx_serialize(FunctionContext* 
ctx, const StringVal& src) {
+    DCHECK(!src.is_null);
+
+    PercentileApproxState *percentile = 
reinterpret_cast<PercentileApproxState*>(src.ptr);
+    uint32_t serialized_size = percentile->digest->serialized_size();
+    StringVal result(ctx, sizeof(double) + serialized_size);
+    memcpy(result.ptr, &percentile->targetQuantile, sizeof(double));
+    percentile->digest->serialize(result.ptr + sizeof(double));
+
+    delete percentile;
+    return result;
+}
+
+void AggregateFunctions::percentile_approx_merge(FunctionContext* ctx, const 
StringVal& src, StringVal* dst) {
+    DCHECK(dst->ptr != NULL);
+    DCHECK_EQ(sizeof(PercentileApproxState), dst->len);
+
+    double quantile;
+    memcpy(&quantile, src.ptr, sizeof(double));
+
+    PercentileApproxState *src_percentile = new PercentileApproxState();
+    src_percentile->targetQuantile = quantile;
+    src_percentile->digest = new TDigest();
 
 Review comment:
   no need to new another TDigest, this will lead to memory leak

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
[email protected]


With regards,
Apache Git Services

---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to