ClickHouse Java多参UDF

一、环境版本

环境 版本
docker clickhouse 22.3.10.22
docker pull clickhouse/clickhouse-server:22.3.10.22

二、XML配置

2.1 配置文件

# 创建udf配置文件
vim /etc/clickhouse-server/demo_function.xml
<functions>
    <function>
        <type>executabletype>
        
        <name>demo_clickhouse_udfname>
        
        <return_type>Stringreturn_type>
        
        
        <return_name>resultreturn_name>
        
        
        <argument>
            <type>UInt64type>
            <name>argument_1name>
        argument>
        <argument>
            <type>UInt64type>
            <name>argument_2name>
        argument>
        
        <format>JSONEachRowformat>
        
        <execute_direct>0execute_direct>
        
        <command>/usr/bin/java -jar /var/lib/clickhouse/user_scripts/demo_clickhouse_udf-1.0-SNAPSHOT-jar-with-dependencies.jarcommand>
    function>
functions>

三、Java代码

新建Maven项目

3.1 pom.xml


<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0modelVersion>

    <groupId>org.examplegroupId>
    <artifactId>demo_clickhouse_udfartifactId>
    <version>1.0-SNAPSHOTversion>

    <properties>
        <maven.compiler.source>8maven.compiler.source>
        <maven.compiler.target>8maven.compiler.target>
        <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
    properties>
    <dependencies>
        <dependency>
            <groupId>com.google.code.gsongroupId>
            <artifactId>gsonartifactId>
            <version>2.10.1version>
        dependency>
    dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.pluginsgroupId>
                <artifactId>maven-assembly-pluginartifactId>
                <version>3.3.0version>
                <configuration>
                    <archive>
                        <manifest>
                            <mainClass>org.example.MainmainClass>
                        manifest>
                    archive>
                    <descriptorRefs>
                        <descriptorRef>jar-with-dependenciesdescriptorRef>
                    descriptorRefs>
                configuration>
                <executions>
                    <execution>
                        <id>assemble-allid>
                        <phase>packagephase>
                        <goals>
                            <goal>singlegoal>
                        goals>
                    execution>
                executions>
            plugin>
        plugins>
    build>
project>

3.2 Main.java

package org.example;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.annotations.Expose;
import java.io.BufferedInputStream;
import java.io.DataInputStream;


public class Main {
    public static void main(String[] args) {
        try {
            DataInputStream in = new DataInputStream(new BufferedInputStream(System.in));
            String s;

            // 逐行读取数据
            while ((s = in.readLine()).length() != 0) {
                // 获取输入参数
                Gson gson = new Gson();
                JsonElement jsonElement = gson.fromJson(s, JsonElement.class);
                JsonObject jsonObject = jsonElement.getAsJsonObject();
                String argument_1 = jsonObject.get("argument_1").getAsString();
                String argument_2 = jsonObject.get("argument_2").getAsString();
                // 封装输出结果
                String resultStr = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create().toJson(new Demo(argument_1, argument_2));
                System.out.println(gson.toJson(new Result(resultStr)));
            }
            System.out.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 返回对象
     */
    public static class Demo{
        @Expose
        private String param1;

        @Expose
        private String param2;

        public Demo(String param1, String param2){
            this.param1 = param1;
            this.param2 = param2;
        }

        public String getParam1() {
            return param1;
        }

        public void setParam1(String param1) {
            this.param1 = param1;
        }

        public String getParam2() {
            return param2;
        }

        public void setParam2(String param2) {
            this.param2 = param2;
        }
    }

    /**
     * 返回结果
     * 返回值名称必须跟xml文件中的return_name一致
     * xml文件return_name默认值result
     * 即: 返回结果为 "{'result': {...}, 'other': {...}, ...}"时
     * 返回值ClickHouse调用函数返回值只去result的值
     */
    public static class Result {
        private String result;

        public String getResult() {
            return result;
        }

        public void setResult(String result) {
            this.result = result;
        }

        public Result(String result){
            this.result = result;
        }
    }
}

3.3 打包将jar包复制到ClickHouse中

docker cp 路径/demo_clickhouse_udf-1.0-SNAPSHOT-jar-with-dependencies.jar 容器id:/var/lib/clickhouse/user_scripts/demo_clickhouse_udf-1.0-SNAPSHOT-jar-with-dependencies.jar

3.4 SQL验证

SYSTEM RELOAD FUNCTIONS; # 刷新函数
SELECT * FROM system.functions WHERE name = 'demo_clickhouse_udf'; # 查询刚添加的udf函数
select demo_clickhouse_udf(1,2)

返回

{"param1":"1","param2":"2"}

3.5 Json字典,数据展开

返回

{"param1":"1","param2":"2"}

数据展开

select
    JSON_VALUE(result, '$.param1') as param1,
    JSON_VALUE(result, '$.param2') as param2
from(
    select demo_clickhouse_udf(1,2) as result
) t1;

3.6 Json数组,数据展开

java例程

	public static void main(String[] args) {
        try {
            DataInputStream in = new DataInputStream(new BufferedInputStream(System.in));
            String s;

            // 逐行读取数据
            while ((s = in.readLine()).length() != 0) {
                // 获取输入参数
                Gson gson = new Gson();
                JsonElement jsonElement = gson.fromJson(s, JsonElement.class);
                JsonObject jsonObject = jsonElement.getAsJsonObject();
                String argument_1 = jsonObject.get("argument_1").getAsString();
                String argument_2 = jsonObject.get("argument_2").getAsString();
                List<Demo> demoList = new ArrayList<>();
                demoList.add(new Demo(argument_1, argument_2));
                demoList.add(new Demo("3", "4"));
                demoList.add(new Demo("5", "6"));
                // 封装输出结果
                String resultStr = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create().toJson(demoList);
                System.out.println(gson.toJson(new Result(resultStr)));
            }
            System.out.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

返回

[{"param1":"1","param2":"2"},{"param1":"3","param2":"4"},{"param1":"5","param2":"6"}]

数据展开

select
    JSONExtractString(arrayElement, 'param1') as param1,
    JSONExtractString(arrayElement, 'param2') as param2
from(
    select demo_clickhouse_udf(1,2) as result
) t1
ARRAY JOIN JSONExtractArrayRaw(result) AS arrayElement;

四、异常问题

4.1 UNKNOWN_FUNCTION

xml文件名称需以function.xml结尾,其它则会添加失败,找不到函数。

# 运行sql
SYSTEM RELOAD FUNCTIONS; # 刷新函数
SELECT * FROM system.functions WHERE name = 'demo_clickhouse_udf'; # 查询刚添加的udf函数
# 报错
Code: 46. DB::Exception: Unknown function demo_clickhouse_udf: While processing demo_clickhouse_udf(1, 2). (UNKNOWN_FUNCTION) (version 22.3.10.22 (official build))

4.2 UNSUPPORTED_METHOD

1.execute_direct需为0

<execute_direct>0execute_direct>

2.command需带上根目录,如/usr/bin/java

<command>/usr/bin/java -jar /var/lib/clickhouse/user_scripts/demo_clickhouse_udf-1.0-SNAPSHOT-jar-with-dependencies.jarcommand>

3.没有安装java等语言环境

4.没有命令或脚本权限

5.版本不支持,如:22.2.3.5

# 报错
Code: 1. DB::Exception: Executable file /usr/bin/java does not exist inside user scripts folder /var/lib/clickhouse/user_scripts/: While processing demo_clickhouse_udf(1, 2). (UNSUPPORTED_METHOD) (version 22.3.10.22 (official build))

4.3 CANNOT_PARSE_QUOTED_STRING

返回字符串格式不对,没有用result封装成json

// 错误的java示例
System.out.println("{'result':1}");
# 报错
Code: 26. DB::ParsingException: Cannot parse JSON string: expected opening quote: While executing ParallelParsingBlockInputFormat: While executing ShellCommandSource: While processing demo_clickhouse_udf(1, 2): (at row 1) . (CANNOT_PARSE_QUOTED_STRING) (version 22.3.10.22 (official build))

五、参考借鉴

ClickHouse Doc
Github Issues

你可能感兴趣的:(ClickHouse,clickhouse,java)