hivecontext.sql(“插入到”)

uxhixvfz  于 2021-06-26  发布在  Hive
关注(0)|答案(2)|浏览(395)

我尝试用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\u id”和“data”。

w8biq8rn

w8biq8rn1#

据我所知,配置单元不支持只在某些列中插入值
从文档中
values子句中列出的每一行都插入到表tablename中。
必须为表中的每一列提供值。尚不支持允许用户仅在某些列中插入值的标准sql语法。为了模仿标准sql,可以为用户不希望赋值的列提供null。
所以你应该试试这个:

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

此处引用

jv2fixgn

jv2fixgn2#

如果您使用的是行-列文件格式(如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>

相关问题