Spark Scala – 将查询结果存储为 Scala 整数类型

huangapple go评论45阅读模式
英文:

Spark Scala - store query result as scala integer type

问题

val max_val_frame = spark.sql(f"""select max(val) as max_val from temp_table_1""");

//将max_val_frame转换为整数的代码

var max_val = //从max_val_frame转换而来的值

var init_val = 1;

while (init_val <= max_val) {

    print(init_val);

    init_val = init_val + 1;

}
英文:

I am trying to take the result of a spark sql query, which is expected to be a single column/row integer value, and store it in a scala variable to use further down. Here is my code:

val max_val_frame = spark.sql(f"""select max(val) as max_val from temp_table_1""");

//code to cast max_val_frame to integer

var max_val = //casted value from max_val_frame

var init_val = 1;

while (init_val <= max_val) {

    print(init_val);

init_val = init_val + 1;

}

Does anyone know how I can cast that spark dataframe object to a scala integer?

I have tried a number of things, including casting the entire dataframe to a string first, then an int, but it does not properly extract the value as an int.

答案1

得分: 1

你可以使用以下表达式:

val max_val = max_val_frame.collect().head.getInt(0)

首个 .head(0) 获取第一行,然后可以使用 getInt(0)getDouble(0) 解析行中索引为 0 的元素。

英文:

You can use the following expression:

val max_val = max_val_frame.collect().head.getInt(0)

The first .head or (0) takes the first row, then you can use getInt(0) or getDouble(0) to parse element with index 0 of the row.

huangapple
  • 本文由 发表于 2023年5月17日 23:38:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/76273852.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定