【问题标题】:Spark - SELECT WHERE or filtering?Spark - 选择 WHERE 还是过滤?
【发布时间】:2016-12-16 11:41:55
【问题描述】:

在 Spark 中使用 where 子句进行选择和过滤有什么区别?
有没有一种比另一种更合适的用例?

什么时候使用

DataFrame newdf = df.select(df.col("*")).where(df.col("somecol").leq(10))

什么时候

DataFrame newdf = df.select(df.col("*")).filter("somecol <= 10")

比较合适?

【问题讨论】:

    标签: apache-spark apache-spark-sql


    【解决方案1】:

    根据spark documentationwhere()filter()的别名

    filter(condition) 使用给定条件过滤行。 where()filter() 的别名。

    参数:条件 - Columntypes.BooleanType 或 SQL 表达式字符串。

    >>> df.filter(df.age > 3).collect()
    [Row(age=5, name=u'Bob')]
    >>> df.where(df.age == 2).collect()
    [Row(age=2, name=u'Alice')]
    
    >>> df.filter("age > 3").collect()
    [Row(age=5, name=u'Bob')]
    >>> df.where("age = 2").collect()
    [Row(age=2, name=u'Alice')]
    

    【讨论】:

    • 我知道您已经有一段时间没有回答这个问题了,但是使用 Column 或使用 sql 字符串进行过滤之间是否存在显着的性能差异?
    • @Megan - 过滤时使用列或字符串之间没有显着的性能差异。它们都生成相同的物理计划,因此它们的执行方式相同。有关详细信息,请参阅我的答案。
    【解决方案2】:

    正如 Yaron 所说,wherefilter 之间没有任何区别。

    filter 是一个采用列或字符串参数的重载方法。无论您使用何种语法,性能都是相同的。

    我们可以使用explain() 来查看所有不同的过滤语法生成相同的物理计划。假设您有一个包含 person_nameperson_country 列的数据集。以下所有代码 sn-ps 将返回以下相同的物理计划:

    df.where("person_country = 'Cuba'").explain()
    df.where($"person_country" === "Cuba").explain()
    df.where('person_country === "Cuba").explain()
    df.filter("person_country = 'Cuba'").explain()
    

    这些都返回这个物理计划:

    == Physical Plan ==
    *(1) Project [person_name#152, person_country#153]
    +- *(1) Filter (isnotnull(person_country#153) && (person_country#153 = Cuba))
       +- *(1) FileScan csv [person_name#152,person_country#153] Batched: false, Format: CSV, Location: InMemoryFileIndex[file:/Users/matthewpowers/Documents/code/my_apps/mungingdata/spark2/src/test/re..., PartitionFilters: [], PushedFilters: [IsNotNull(person_country), EqualTo(person_country,Cuba)], ReadSchema: struct<person_name:string,person_country:string>
    

    语法不会改变过滤器在后台的执行方式,但执行查询的文件格式/数据库会改变。 Spark 将在 Postgres(支持谓词下推过滤)、Parquet(列修剪)和 CSV 文件上以不同方式执行相同的查询。 See here了解更多详情。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-22
      • 2023-03-08
      • 1970-01-01
      • 2018-01-26
      • 1970-01-01
      • 1970-01-01
      • 2020-12-17
      • 2020-07-13
      相关资源
      最近更新 更多