HiveContext.sql(“插入到”)

时间:2017-12-19 08:18:32

标签: scala hive apache-spark-sql hivecontext

我正在尝试使用 HiveContext 插入数据,如下所示:

/* table filedata
CREATE TABLE `filedata`(
  `host_id` string,
  `reportbatch` string,
  `url` string,
  `datatype` string,
  `data` string,
  `created_at` string,
  `if_del` boolean)
*/
hiveContext.sql("insert into filedata (host_id, data) values (\"a1e1\", \"welcome\")")

错误并尝试使用“选择”:

hiveContext.sql("select \"a1e1\" as host_id, \"welcome\"as data").write.mode("append").saveAsTable("filedata")
/*
stack trace 
java.lang.ArrayIndexOutOfBoundsException: 2
*/

它需要像这样的所有列:

hc.sql("select \"a1e1\" as host_id,
          \"xx\" as reportbatch,
          \"xx\" as url,
          \"xx\" as datatype,
          \"welcome\" as data,
          \"2017\" as created_at, 
          1 as if_del").write.mode("append").saveAsTable("filedata")

有没有办法插入指定的列?例如,只插入列“host_id”和“data”。

2 个答案:

答案 0 :(得分:1)

据我所知,Hive不支持仅将值插入某些列

来自文档

  

VALUES子句中列出的每一行都插入到表tablename中。

     

必须为表中的每一列提供值。标准   SQL语法,允许用户仅将值插入一些   列尚不支持。要模仿标准SQL,可以使用null   为用户不希望为其赋值的列提供。

所以你应该试试这个:

  val data = sqlc.sql("select 'a1e1', null, null, null, 'welcome', null, null, null")
  data.write.mode("append").insertInto("filedata")

参考here

答案 1 :(得分:0)

如果使用行列式文件格式(如ORC),则可以执行此操作。请参阅下面的工作示例。此示例位于Hive中,但与HiveContext一起使用效果非常好。

hive> use default;
OK
Time taken: 1.735 seconds
hive> create table test_insert (a string, b string, c string, d int) stored as orc;
OK
Time taken: 0.132 seconds
hive> insert into test_insert (a,c) values('x','y');
Query ID = user_20171219190337_b293c372-5225-4084-94a1-dec1df9e930d
Total jobs = 1
Launching Job 1 out of 1


Status: Running (Executing on YARN cluster with App id application_1507021764560_1375895)

--------------------------------------------------------------------------------
        VERTICES      STATUS  TOTAL  COMPLETED  RUNNING  PENDING  FAILED  KILLED
--------------------------------------------------------------------------------
Map 1 ..........   SUCCEEDED      1          1        0        0       0       0
--------------------------------------------------------------------------------
VERTICES: 01/01  [==========================>>] 100%  ELAPSED TIME: 4.06 s
--------------------------------------------------------------------------------
Loading data to table default.test_insert
Table default.test_insert stats: [numFiles=1, numRows=1, totalSize=417, rawDataSize=254]
OK
Time taken: 6.828 seconds
hive> select * from test_insert;
OK
x       NULL    y       NULL
Time taken: 0.142 seconds, Fetched: 1 row(s)
hive>