Spark SQL:如何使用 JAVA 从 DataFrame 操作中调用 UDF [英] Spark SQL: How to call UDF from DataFrame operation using JAVA

查看:50
本文介绍了Spark SQL:如何使用 JAVA 从 DataFrame 操作中调用 UDF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何在 Spark SQL 中使用 JAVA 从特定领域语言 (DSL) 的函数中调用 UDF 函数.

I would like to know how to call UDF function from function of domain-specific language(DSL) in Spark SQL using JAVA.

我有 UDF 函数(只是举例):

I have UDF function (just for example):

UDF2 equals = new UDF2<String, String, Boolean>() {
   @Override
   public Boolean call(String first, String second) throws Exception {
       return first.equals(second);
   }
};

我已将其注册到 sqlContext

I've registered it to sqlContext

sqlContext.udf().register("equals", equals, DataTypes.BooleanType);

当我运行以下查询时,我的 UDF 被调用并得到结果.

When I run following query, my UDF is called and I get a result.

sqlContext.sql("SELECT p0.value FROM values p0 WHERE equals(p0.value, 'someString')");

我会在 Spark SQL 中使用领域特定语言的函数来转换这个查询,但我不知道该怎么做.

I would transfrom this query using functions of domain specific language in Spark SQL, and I am not sure how to do it.

valuesDF.select("value").where(???);

我发现存在 callUDF() 函数,其参数之一是 Function2 fnctn 而不是 UDF2.如何使用 DSL 中的 UDF 和函数?

I found that there exists callUDF() function where one of its parameters is Function2 fnctn but not UDF2. How can I use UDF and functions from DSL?

推荐答案

我找到了一个让我半满意的解决方案.可以将 UDF 称为列条件,例如:

I found a solution with which I am half-satisfied. It is possible to call UDF as a Column Condition such as:

valuesDF.filter("equals(columnName, 'someString')").select("columnName");

但我还是想知道是否可以直接调用UDF.

But I still wonder if it is possible to call UDF directly.

顺便说一句,可以直接调用 udf,例如:

Btw, it is possible to call udf directly e.g:

df.where(callUdf("equals", scala.collection.JavaConversions.asScalaBuffer(
                        Arrays.asList(col("columnName"), col("otherColumnName"))
                    ).seq())).select("columnName");

需要导入 org. apache. spark. sql. functions.

import of org.​apache.​spark.​sql.​functions is required.

这篇关于Spark SQL:如何使用 JAVA 从 DataFrame 操作中调用 UDF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆