繁体   English   中英

对于 SPARK 列,将 SCALA ===(三等)转换为 Python

[英]Converting SCALA === (triple equal) to Python for SPARK column

我在 Scala 中有以下代码用于 Python 转换


import org.apache.spark.sql.functions.{col, lit}
import org.apache.spark.sql.{Column, DataFrame, Dataset}

object SearchTermReader {

  def read(
    searchTermsInputTable: DataFrame,
    brand: String,
    posa: String,
    startDate: String,
    endDate: String
  ): Dataset[SearchTerm] = {

    import searchTermsInputTable.sparkSession.implicits._

    val conditionsNoEndDate = getConditions(brand, posa, startDate)
    val searchTermsNoEndDate = searchTermsInputTable
      .where(conditionsNoEndDate)
      .cache()

    searchTermsNoEndDate.count()

    val columnNames = SparkExtensions.getColumns[SearchTerm]

    searchTermsNoEndDate
      .filter(col("report_date").leq(lit(endDate)))
      .select(columnNames: _*)
      .as[SearchTerm]
  }

  def getConditions(
    brand: String,
    posa: String,
    startDate: String
  ): Column = {

    val filterByBrandCondition: Column = {
      if (brand.equals("")) {
        lit(true)
      } else {
        col("brand") === brand
      }
    }
    val filterByPosaCondition: Column = {
      if (posa.equals("")) {
        lit(true)
      } else {
        col("account_name").rlike(getAccountPattern(posa))
      }
    }

    filterByBrandCondition &&
      filterByPosaCondition &&
      col("search_engine") === "GOOGLE" &&
      col("impressions") > 0 &&
      col("report_date").geq(lit(startDate))
  }

  def getAccountPattern(countryCodes: String): String = {
    countryCodes.split(",").map(cc => s":G:$cc:").mkString("|")
  }
}

对于直接转换,这里似乎有两个问题。

  1. 使用了 Pyspark 不支持的数据集
  2. === 用于也不支持的 Column

我如何克服这个问题并将其转换为 Python?

如果您指的是 dataframe 的列,那么您可以像下面这样使用它。

df.filter((col("brand") == "BRAND") & (...))

Pyspark 不支持使用===就像Scala

在 Scala 中, ==使用 equals 方法检查两个引用是否指向同一个 object。 ===的定义取决于上下文/对象。 对于 Spark, ===使用的是equalTo方法。

在 Pyspark 中,您使用=== 话虽如此,在 Pyspark 中,您按照Scala代码执行以下实现以获得相同的结果 -

df.filter("Brand = 'BRAND'")

或者,

df.filter(df.Brand == 'BRAND')

或者,

df.filter(df["Brand"] == 'BRAND')

或者,

from pyspark.sql.functions import *
df.filter(col("Brand") == 'BRAND')

在进一步调查如何将 Scala 中的 === 转换为 python 之后,对于上面的那些特殊情况,它足以在 Python 中使用 ==

所以

val filterByBrandCondition: Column = {
      if (brand.equals("")) {
        lit(true)
      } else {
        col("brand") === brand
      }
    }

转换为

if (brand == ""):
      filterByBrandCondition: Column = lit(True)
    else:
      filterByBrandCondition: Column = (col("brand") == brand) 

col("search_engine") === "GOOGLE"

col("search_engine") == "GOOGLE"

Dataset的使用可以用DataFrame代替。变量

val columnNames = SparkExtensions.getColumns[SearchTerm]

需要替换为将从 dataframe 读取列名称的代码

暂无
暂无

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

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