Spark 将 DataFrame 作为 HTTP Post 请求的正文发送

Am1*_*3zA 3 rest scala apache-spark

我有一个数据帧,我想将其作为请求正文发送HTTP Post,最好的Sparky方法是什么?
如何控制HTTP请求的数量?如果记录数量变大,有没有办法将发送数据帧拆分为多个 HTTP Post 调用?

假设我的数据框是这样的:

+--------------------------------------+------------+------------+------------------+
|               user_id                |    city    | user_name  |   facebook_id    |
+--------------------------------------+------------+------------+------------------+
| 55c3c59d-0163-46a2-b495-bc352a8de883 | Toronto    | username_x | 0123482174440907 |
| e2ddv22d-4132-c211-4425-9933aa8de454 | Washington | username_y | 0432982476780234 |
+--------------------------------------+------------+------------+------------------+
Run Code Online (Sandbox Code Playgroud)

我想要在 HTTP Post 请求正文中包含user_id和到此端点facebook_idlocalhost:8080/api/spark

rog*_*one 7

您可以使用foreachPartitionDataframe 上的方法来实现此目的。我假设您想并行地对 Dataframe 中的每一行进行 Http 调用。foreachPartition并行操作 Dataframe 的每个分区。如果您想在单个 HTTP post 调用中批量处理多行,也可以通过将方法的签名makeHttpCall从更改RowIterator[Row]

  def test(): Unit = {
    val df: DataFrame = null
    df.foreachPartition(_.foreach(x => makeHttpCall(x)))
  }

  def makeHttpCall(row: Row) = {
    val json = Json.obj("user_name" -> row.getString(2), "facebook_id" -> row.getString(3))
    /**
      * code make Http call
      */
  }
Run Code Online (Sandbox Code Playgroud)

用于发出批量 Http 请求makeHttpCall。确保数据框中有足够数量的分区,以便每个分区足够小以发出 Http Post 请求。

import org.apache.spark.sql.{DataFrame, Row}
import play.api.libs.json.Json

  def test(): Unit = {
    val df: DataFrame = null
    df.foreachPartition(x => makeHttpCall(x))
  }

  def makeHttpCall(row: Iterator[Row]) = {
    val json = Json.arr(row.toSeq.map(x => Json.obj("user_name" -> x.getString(2), "facebook_id" -> x.getString(3))))
    /**
      * code make Http call
      */
  }
Run Code Online (Sandbox Code Playgroud)