【问题标题】:How to use NOT IN from a CSV file in Spark如何在 Spark 中使用 CSV 文件中的 NOT IN
【发布时间】:2016-11-11 02:23:54
【问题描述】:

我使用 Spark sql 将数据加载到这样的val

val customers = sqlContext.sql("SELECT * FROM customers")

但我有一个单独的 txt 文件,其中包含一列 CUST_ID 和 50,00 行。即

CUST_ID
1
2
3

我希望我的customers val 拥有customers 表中不在 TXT 文件中的所有客户。

使用 Sql 我会通过 SELECT * FROM customers NOT IN cust_id ('1','2','3') 做到这一点

如何使用 Spark 做到这一点?

我已经阅读了 textFile 并且可以打印它的行,但我不确定如何将它与我的 sql 查询匹配

scala> val custids = sc.textFile("cust_ids.txt")
scala> custids.take(4).foreach(println)
CUST_ID
1
2
3

【问题讨论】:

    标签: scala apache-spark apache-spark-sql


    【解决方案1】:

    您可以将文本文件作为数据框导入并进行左外连接:

    val customers = Seq(("1", "AAA", "shipped"), ("2", "ADA", "delivered") , ("3", "FGA", "never received")).toDF("id","name","status")
    val custId = Seq(1,2).toDF("custId")
    
    customers.join(custId,'id === 'custId,"leftOuter")
             .where('custId.isNull)
             .drop("custId")
             .show()
    
    
    +---+----+--------------+
    | id|name|        status|
    +---+----+--------------+
    |  3| FGA|never received|
    +---+----+--------------+
    

    【讨论】:

    • 我在尝试重新创建示例的 spark-shell 中遇到此错误:val test1 = Seq(1,2).toDF("custId") 错误:error: value toDF is not a member of Seq[Int]
    • 您使用的是 2.0 之前的 Spark 版本吗?然后 sc.parallelize(Seq(1,2)).toDF("custId")
    • 我的 spark 版本是 version 1.5.0,scala 版本是 Using Scala version 2.10.4
    • 我在这里添加了另一个问题stackoverflow.com/questions/40534744/…
    猜你喜欢
    • 2019-04-21
    • 2017-11-26
    • 1970-01-01
    • 2016-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多