ClickHouse 聚合函数 实践


ClickHouse 学习中,如果有问题,请在下方讨论。

 

为了比较快的了解聚合函数的相关架构,我们选择比较简单的聚合函数。常见比较简单的聚合函数有max/min/sum/average等,我们拿sum为例.

例如: 我们有个SQL 语句 select sum(a) from table;  如果看做是一个简单的求和问题,那么我们就会遍历所有输入的数据,并进行求和计算。 类似

伪码:

long Sum(data){
  let sum = 0;   //遍历列中的数据,并进行计算。   for (auto _data: data) sum += _data;   return sum;
}

    那么在AggregateFunctionSum是如何实现这种抽象的呢. 带着这个疑问,我们找到AggregateFunctionSum.h 文件.

    这个类模板 继承冲击力比较强,需要做一下作者在这类继承关系上的思路。 

/// Counts the sum of the numbers.
template <typename T, typename TResult, typename Data, AggregateFunctionSumType Type>
class AggregateFunctionSum final : public IAggregateFunctionDataHelper<Data, AggregateFunctionSum<T, TResult, Data, Type>>

  以下是推断逻辑:

  某个聚合函数的实际组成是由 函数 + 数据构成 (这里是继承关系)。

      1. 这里类比 AggregateFunctionSum : IAggregateFunctionDataHelpler(从类名称上,继承了Function和 Data的信息,后面会继续进行分解)

      2. IAggregateFunctionDataHelper 本模板类中定义的Data相关的 成员及成员函数,除去Data相关的就是  IAggregateFunctionHelper 的模板类。

      3. IAggregateFunctionHelper 是个Function的Helper类模板,类模板参数中的Derived中应该是一个Function. (AggregateFunctionSum<T,TResult,Data,Type>).

      4. IAggregateFunctionHelper 应该在继承IAggregateFunction的所有成员后,还需要加入一些增强(Helper)的成员。 这里我们看到的是 addFree ,静态方法,因为毕竟IAggregateFunctionHelpler是个Interface(因为其没有实现IAggregateFunction里面所有的pure virtual function,所以不能实例化)。其中也override了一些IAggregateFunction的一些 pure virtual function.  addFree方法 的确是可以通过 static_cast<const Derived &>(*that).add(place, columns, row_column, arena).

 

  5.通过Debug,我们可以看到,一般聚合函数的调用是在这里进行的。(Aggregator.cpp).

      6.我们注册的函数会根据参数类型动态生成对应的聚合函数模板类。 
/** Create an aggregate function with a numeric type in the template parameter, depending on the type of the argument.
  */
template <template <typename> class AggregateFunctionTemplate, typename... TArgs>
static IAggregateFunction * createWithNumericType(const IDataType & argument_type, TArgs && ... args)

  ---未完待续

  

      

#include <iostream>

using namespace std;

class Base{
protected:
    static void f(){cout << "invoke static f method" << endl;}
};

class Derived: public Base{
    public:
    using func_type = void (*)();
    void derivedFunc(){
        this->f();
     //为函数指针赋值 使用&和不使用&结果竟然是一样的。语法兼容性有点强。 func_type x = &f; func_type y = f; y(); x(); } }; int main(){ Derived d; d.derivedFunc(); }

---结果

➜ C++Basic ./accessStaticMethodViaThisPointer

函数指针 赋值 还是太灵活。
invoke static f method
invoke static f method
invoke static f method

 

  


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM