2015-11-04 66 views
4

我有以下数据结构:Seq.contains在SQL中的星火据帧

  • id: int
  • records: Seq[String]
  • other: boolean

在一个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只使用SQL等于true下过滤出记录。

我可以通过做一个filter(见下文),但它可以被使用SQL只是做了什么?

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

回答

5

星火SQL支持绝大多数的蜂巢功能,从而可以使用array_contains做的工作:

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

注:火花1.5sqlContext.jsonRDD弃用,改用以下:

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

太棒了。谢谢。 –