简体   繁体   English

使用Java使用Spark Column从Java Map读取值

[英]Read values from Java Map using Spark Column using java

I have tried below code to get Map values via spark column in java but getting null value expecting exact value from Map as per key search.我已经尝试在下面的代码中通过 java 中的 spark 列获取Map值,但是根据键搜索从 Map 获取期望值的null值。

and Spark Dataset contains one column and name is KEY and dataset name dataset1 Spark 数据集包含一列,名称为KEY ,数据集名称为 dataset1

values in dataset :数据集中的值:

KEY
1
2 

Java Code - Java代码 -

Map<String,string> map1 = new HashMap<>();
map1.put("1","CUST1");
map1.put("2","CUST2");


dataset1.withColumn("ABCD", functions.lit(map1.get(col("KEY"))));

Current Output is:电流输出为:

ABCD (Column name)
null
null

Expected Output :预期输出:

ABCD (Column name)
CUST1
CUST2

please me get this expected output.请我得到这个预期的输出。

The reason why you get this output is pretty simple.你得到这个输出的原因很简单。 The get function in java can take any object as input. java 中的get函数可以将任何对象作为输入。 If that object is not in the map, the result is null.如果该对象不在地图中,则结果为空。

The lit function in spark is used to create a single value column (all rows have the same value). spark 中的lit函数用于创建单个值列(所有行具有相同的值)。 eg lit(1) creates a column that takes the value 1 for each row.例如lit(1)创建一个列,每行取值为 1。

Here, map1.get(col("KEY")) (that is executed on the driver), asks map1 the value corresponding to a column object (not the value inside the column, the java/scala object representing the column).这里, map1.get(col("KEY")) (在驱动程序上执行),向map1询问与列对象对应的值(不是列内的值,代表列的 java/scala 对象)。 The map does not contain that object so the result is null.地图不包含该对象,因此结果为空。 Therefore, you could as well write lit(null) .因此,您也可以编写lit(null) This is why you get a null result inside your dataset.这就是您在数据集中得到空结果的原因。

To solve your problem, you could wrap your map access within a UDF for instance.例如,为了解决您的问题,您可以将地图访问权限封装在 UDF 中。 Something like:就像是:

UserDefinedFunction map_udf = udf(new UDF1<String, String>() {
            @Override
            public String call(String x) {
                return map1.get(x);
            }
        }, DataTypes.StringType );

spark.udf().register("map_udf", map_udf);
result.withColumn("ABCD", expr("map_udf(KEY)"));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM