Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the first value from spark.sql.Row

I have the following json format :

{"Request": {"TrancheList": {"Tranche": [{"TrancheId": "500192163","OwnedAmt": "26500000",    "Curr": "USD" }, {  "TrancheId": "500213369", "OwnedAmt": "41000000","Curr": "USD"}]},"FxRatesList": {"FxRatesContract": [{"Currency": "CHF","FxRate": "0.97919983706115"},{"Currency": "AUD", "FxRate": "1.2966804979253"},{ "Currency": "USD","FxRate": "1"},{"Currency": "SEK","FxRate": "8.1561012531034"},{"Currency": "NOK", "FxRate": "8.2454981641398"},{"Currency": "JPY","FxRate": "111.79999785344"},{"Currency": "HKD","FxRate": "7.7568025218916"},{"Currency": "GBP","FxRate": "0.69425159677867"}, {"Currency": "EUR","FxRate": "0.88991723769689"},{"Currency": "DKK", "FxRate": "6.629598372301"}]},"isExcludeDeals": "true","baseCurrency": "USD"}}

The json is read from hdfs :

val hdfsRequest = spark.read.json("hdfs://localhost/user/request.json")
val baseCurrency = hdfsRequest.select("Request.baseCurrency").map(_.getString(0)).collect.headOption
var fxRates = hdfsRequest.select("Request.FxRatesList.FxRatesContract")
val fxRatesDF = fxRates.select(explode(fxRates("FxRatesContract"))).toDF("FxRatesContract").select("FxRatesContract.Currency", "FxRatesContract.FxRate").filter($"Currency"===baseCurrency.get)
fxRatesDF.show()

The output that I am getting for fxRatesDF is :

fxRatesDF: org.apache.spark.sql.Dataset[org.apache.spark.sql.Row] = [Currency: string, FxRate: string]
+--------+------+
|Currency|FxRate|
+--------+------+
|     USD|     1|

How can I grab the value of first row of Fxrate column?

like image 988
user3290807 Avatar asked Nov 17 '16 17:11

user3290807


3 Answers

Here is the function that you need to use

Use like this:

fxRatesDF.first().FxRate
like image 198
Thiago Baldim Avatar answered Oct 19 '22 18:10

Thiago Baldim


You can use

fxRatesDF.select(col("FxRate")).first.getString(0)
like image 31
abaghel Avatar answered Oct 19 '22 20:10

abaghel


Perhaps this way:

fxRatesDF.take(1)[0][1]

or

fxRatesDF.collect()[0][1]

or

fxRatesDF.first()[1]
like image 8
Val Avatar answered Oct 19 '22 18:10

Val