如何构建动态查询字符串以在 spark-sql 2.3.1 数据帧上执行?

How to build a dynamic query string to execute on a spark-sql 2.3.1 dataframe?

我需要获取用户传递的 where 条件作为程序参数。根据where条件查询源数据库

我正在使用 spark-sql.2.3.1 如何构建和pass/executive动态构建查询?

示例查询:

select ProductId, COUNT(*) AS ProductSaleCount
 from productsale
 where to_date(Date) >= "2015-12-17"
 and to_date(Date) <= "2015-12-31"
 group by ProductId

在您的场景中,您所要做的就是创建一个类似于以下内容的查询字符串:

val query = "select ProductId, COUNT(*) AS ProductSaleCount from productsale where to_date(Date) >= "+ fromDate +" and to_date(Date) <= " + toDate + " group by ProductId"

fromDate 和 toDate,你可能会从你的论据中得到。

然而,要使用它是一个不同的问题,它取决于您的数据库

对于配置单元,您只需使用 enableHiveSupport

注册您的 spark 会话
val spark = SparkSession.builder().appName("My App").enableHiveSupport().config("spark.sql.warehouse.dir", warehouseLocation).getOrCreate()

val data = spark.sqlContext.sql(query)

如果数据在数据框中并且您想查询它,则必须创建一个视图然后运行您的查询

finalDataFrame.createOrReplaceTempView("productsale")

val data = spark.sqlContext.sql(query)

希望对您有所帮助