簡體   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