gpt4 book ai didi

scala - Spark Dataframe 中 SQL 中的 Seq.contains

转载 作者:行者123 更新时间:2023-12-02 12:58:58 24 4
gpt4 key购买 nike

我有以下数据结构:

  • id:整数
  • 记录:Seq[String]
  • 其他: bool 值

在json文件中,为了方便测试:

var data = sc.makeRDD(Seq[String](
"{\"id\":1, \"records\": [\"one\", \"two\", \"three\"], \"other\": true}",
"{\"id\": 2, \"records\": [\"two\"], \"other\": true}",
"{\"id\": 3, \"records\": [\"one\"], \"other\": false }"))
sqlContext.jsonRDD(data).registerTempTable("temp")

我想筛选出 records 字段中 oneother 等于 true< 的记录 仅使用 SQL。

我可以通过过滤器(见下文)来完成此操作,但可以仅使用 SQL 来完成吗?

sqlContext
.sql("select id, records from temp where other = true")
.rdd.filter(t => t.getAs[Seq[String]]("records").contains("one"))
.collect()

最佳答案

Spark SQL 支持绝大多数 Hive 功能,因此您可以使用 array_contains 来完成这项工作:

spark.sql("select id, records from temp where other = true and array_contains(records,'one')").show
# +---+-----------------+
# | id| records|
# +---+-----------------+
# | 1|[one, two, three]|
# +---+-----------------+

注意:spark 1.5 中,sqlContext.jsonRDD弃用,请改用以下内容: p>

sqlContext.read.format("json").json(data).registerTempTable("temp")

关于scala - Spark Dataframe 中 SQL 中的 Seq.contains,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33521663/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com