使用Spark中的数据帧以写入时间写入Cassandra

时间:2018-07-02 10:16:41

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

我有以下代码:-

  val kafkaStream = KafkaUtils.createStream[String, String, StringDecoder, StringDecoder](ssc, kafkaParams, topics, StorageLevel.MEMORY_AND_DISK_SER)
  val collection = kafkaStream.map(_._2).map(parser)
    collection.foreachRDD(rdd =>
      {
        if (!rdd.partitions.isEmpty) {
          try {
            val dfs = rdd.toDF() 
dfs.write.format("org.apache.spark.sql.cassandra").options(Map("table" -> "tablename", "keyspace" -> "dbname"))
              .mode(SaveMode.Append).save()
          } catch {
            case e: Exception => e.printStackTrace
          }
        } else {
          println("blank rdd")
        }
      })

在上面的示例中,我使用数据帧将火花流保存到cassandra。现在,我希望df的每一行都应有其特定的写入时间,类似于此命令-

insert into table (imei , date , gpsdt ) VALUES ( '1345','2010-10-12','2010-10-12 10:10:10') USING TIMESTAMP 1530313803922977;

因此,基本上,每行的写入时间应等于该行的gpsdt列。在搜索中,我找到了此链接,但它显示了RDD的示例,我想要类似数据框的用例-https://github.com/datastax/spark-cassandra-connector/blob/master/doc/5_saving.md任何建议,谢谢

1 个答案:

答案 0 :(得分:0)

据我所知,DataFrame版本中没有这样的功能(有相应的JIRA:https://datastax-oss.atlassian.net/browse/SPARKC-416)。但是无论如何,您都有RDD,可以将其转换为DataFrame-为什么不使用引述链接中所述的saveToCassandra

P.S。检查空度(http://www.waitingforcode.com/apache-spark/isEmpty-trap-spark/read)时可能会出现性能问题