优秀的编程知识分享平台

网站首页 > 技术文章 正文

在ClickHouse中自定义脚本函数(clickhouse create table)

nanyue 2024-10-01 13:07:26 技术文章 7 ℃

在新版本中,该特性又得到了增强,现在进一步支持执行本地文件脚本或者预先定义的 shell 命令。


接下来让我们快速了解该功能如何使用。


首先,在 config.xml 文件中添加如下配置:

<user_defined_executable_functions_config>*_function.xml</user_defined_executable_functions_config>

该配置用于匹配 Executable UDF 的定义文件。


接着,在 user_files 目录下,创建一个函数定义文件 test_executable_udf.xml :

<functions>
    <function>
        <type>executable</type>
        <name>test_executable_udf</name>
        <return_type>String</return_type>
        <argument>
            <type>UInt64</type>
        </argument>
        <format>TabSeparated</format>
        <command>test_executable_udf.py</command>
    </function>
</functions>


最后,在 user_scripts 目录下,放入需要执行的脚本文件,例如

test_executable_udf.py :

#!/usr/bin/python3


import sys


if __name__ == '__main__':
    for line in sys.stdin:
        print("UDF Value is : " + line, end='')
        sys.stdout.flush()


全部搞定之后,我们就能在 ClickHouse 中调用脚本函数了:

SELECT test_executable_udf(toUInt64(2))


如果想执行 Shell 命令,则只需将 *_function.xml 配置文件中,<command> 内的文件名替换成命令文本,并增加 execute_direct 参数,例如:

<command>
cd/; clickhouse-local --input-format TabSeparated --output-formatTabSeparated --structure
'x UInt64, y UInt64'
--query "SELECT x + y FROM table"
</command>
<execute_direct>0</execute_direct>


相关的 PR 地址如下:

https://github.com/ClickHouse/ClickHouse/pull/28803

最近发表
标签列表