Hive insertar consulta como SQL


Soy nuevo en hive, y quiero saber si hay de todos modos para insertar datos en la tabla hive como lo hacemos en SQL. Quiero insertar mis datos en la colmena como

INSERT INTO tablename VALUES (value1,value2..)

He leído que puede cargar los datos de un archivo a la tabla de la colmena o puede importar datos de una tabla a la tabla de la colmena, pero ¿hay alguna manera de anexar los datos como en SQL?

Author: Y0gesh Gupta, 2013-07-02

13 answers

Algunas de las respuestas aquí están desactualizadas a partir de Hive 0.14

Https://cwiki.apache.org/confluence/display/Hive/LanguageManual+DML#LanguageManualDML-InsertingvaluesintotablesfromSQL

Ahora es posible insertar usando sintaxis como:

CREATE TABLE students (name VARCHAR(64), age INT, gpa DECIMAL(3, 2));

INSERT INTO TABLE students
  VALUES ('fred flintstone', 35, 1.28), ('barney rubble', 32, 2.32);
 81
Author: mattinbits,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-07-27 14:55:27

Puede usar la pila de funciones de generación de tablas para insertar valores literales en una tabla.

Primero necesita una tabla ficticia que contenga solo una línea. Puede generarlo con la ayuda de límite.

CREATE TABLE one AS
SELECT 1 AS one
FROM any_table_in_your_database
LIMIT 1;

Ahora puede crear una nueva tabla con valores literales como este:

CREATE TABLE my_table AS
SELECT stack(3
  , "row1", 1
  , "row2", 2
  , "row3", 3
) AS (column1, column2)
FROM one
;

El primer argumento de stack es el número de filas que está generando.

También puede agregar valores a una tabla existente:

INSERT INTO TABLE my_table
SELECT stack(2
  , "row4", 1
  , "row5", 2
) AS (column1, column2)
FROM one
;
 16
Author: unique2,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-09-20 08:55:44

La versión ligeramente mejor de la sugerencia unique2 está a continuación:

insert overwrite table target_table
select * from 
(
select stack(
    3,                 # generating new table with 3 records
    'John', 80,        # record_1
    'Bill', 61         # record_2
    'Martha', 101      # record_3
    ) 
) s;

Que no requiere el hack con el uso de una tabla ya salir.

 11
Author: Habdank,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-03-04 15:34:04

Definitivamente podría agregar datos a una tabla existente. (Pero en realidad no es un apéndice a nivel HDFS). Es solo que cada vez que realice una operación de CARGA o INSERCIÓN en una tabla Colmena existente sin la cláusula OVERWRITE, los nuevos datos se colocarán sin reemplazar los datos antiguos. Se creará un nuevo archivo para estos datos recién insertados dentro del directorio correspondiente a esa tabla. Por ejemplo :

Tengo un archivo llamado demo.txt que tiene 2 líneas:

ABC
XYZ

Crear una tabla y cargue este archivo en él

hive> create table demo(foo string);
hive> load data inpath '/demo.txt' into table demo;

Ahora, si hago una SELECCIÓN en esta tabla me dará:

hive> select * from demo;                        
OK    
ABC    
XYZ

Supongamos que tengo un archivo más llamado demo2.txt que tiene:

PQR

Y hago una CARGA de nuevo en esta tabla sin usar sobrescribir,

hive> load data inpath '/demo2.txt' into table demo;

Ahora, si hago una SELECCIÓN ahora, me dará,

hive> select * from demo;                       
OK
ABC
XYZ
PQR

HTH

 5
Author: Tariq,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-07-03 14:52:52

Puede utilizar el siguiente enfoque. Con esto, no necesita crear una tabla temporal O un archivo txt/csv para seleccionar y cargar más, respectivamente.

INSERT INTO TABLE tablename SELECT value1,value2 FROM tempTable_with_atleast_one_records LIMIT 1.

Donde tempTable_with_atleast_one_records es cualquier mesa con al menos un registro.

Pero el problema con este enfoque es que si tiene la instrucción INSERT que inserta varias filas como debajo de una.

INSERT INTO yourTable values (1 , 'value1') , (2 , 'value2') , (3 , 'value3') ;

Luego, debe tener una instrucción INSERT hive separada para cada fila. Véase más adelante.

INSERT INTO TABLE yourTable SELECT 1 , 'value1' FROM tempTable_with_atleast_one_records LIMIT 1;
INSERT INTO TABLE yourTable SELECT 2 , 'value2' FROM tempTable_with_atleast_one_records LIMIT 1;
INSERT INTO TABLE yourTable SELECT 3 , 'value3' FROM tempTable_with_atleast_one_records LIMIT 1;
 5
Author: Sanjiv,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-11-11 07:09:23

No. Esta sintaxis INSERT INTO tablename VALUES (x,y,z) actualmente no está soportada en Hive.

 3
Author: Lukas Vermeer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-07-02 12:48:20

Sí se puede insertar pero no tan similar a SQL.

En SQL podemos insertar los datos de nivel de fila, pero aquí se puede insertar por campos (columnas).

Durante esto debe asegurarse de que la tabla de destino y la consulta deben tener el mismo tipo de datos y el mismo número de columnas.

Eg:

CREATE TABLE test(stu_name STRING,stu_id INT,stu_marks INT)
ROW FORMAT DELIMITED
FIELDS TERMINATED BY ','
STORED AS TEXTFILE;

INSERT OVERWRITE TABLE test SELECT lang_name, lang_id, lang_legacy_id FROM export_table;
 2
Author: user3279425,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-03-04 11:30:43

Insertar datos completos de table2 en table1. A continuación se muestra una consulta:

INSERT INTO TABLE table1 SELECT * FROM table2; 
 2
Author: Ramesh babu M,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-12 13:16:34

No puede hacer insert into para insertar un solo registro. No es compatible con Hive. Puede colocar todos los registros nuevos que desee insertar en un archivo y cargar ese archivo en una tabla temporal en el subárbol. A continuación, utilizando insertar sobrescribir..seleccionar comando insertar esas filas en una nueva partición de la tabla principal de la colmena. La restricción aquí es que su tabla principal tendrá que ser pre particionada. Si no usa la partición, entonces toda su tabla será reemplazada con estos nuevos registros.

 1
Author: Arijit Banerjee,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-07-03 06:11:48

Introduzca el siguiente comando para insertar datos en la tabla testlog con alguna condición:

INSERT INTO TABLE testlog SELECT * FROM table1 WHERE some condition;
 1
Author: Don,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-22 16:03:09

Creo que en tales escenarios se debe utilizar HBASE que facilita este tipo de inserción, pero no proporciona ningún tipo de lenguaje de consulta SQL. Es necesario utilizar Java API de HBASE como el método put para hacer este tipo de inserción. Además, HBASE es una base de datos no-sql orientada a columnas.

 0
Author: Binary01,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-07-03 12:50:26

Sí podemos usar Insertar consulta en el subárbol.

Colmena > crear prueba de tabla (id int, cadena de nombre);

INSÉRTESE : INSÉRTESE...Los VALORES están disponibles a partir de la versión: Hive 0.14.

Colmena > insertar en la tabla valores de prueba(1, 'mytest');

Esto va a funcionar para insert. tenemos que usar valores palabra clave.

Nota: El usuario no puede insertar datos en una columna de tipo de datos complejo (array, map, struct, union) utilizando * * INSERT EN...Cláusula values.

 0
Author: Viraj.Hadoop,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-12 07:20:51

Formas de insertar datos en la tabla de la colmena: para la demostración, estoy usando el nombre de la tabla como table1 y table2

1) create table table2 as select * from table1 where 1=1; o create table table2 as select * from table1;

2) insert overwrite table table2 select * from table1; -- insertará datos de uno a otro. Nota: Actualizará el destino.

3) insert into table table2 select * from table1; -- insertará datos de uno a otro. Nota: Se agregará al destino.

4) load data local inpath 'local_path' overwrite into table table1; -- cargará los datos del local en la tabla de destino y también actualizará el destino tabla.

5) load data inpath 'hdfs_path' overwrite into table table1; -- cargará datos de la ubicación hdfs y también actualizará la tabla de destino. o

create table table2(
    col1 string,
    col2 string,
    col3 string)
    row format delimited fields terminated by ','
    location 'hdfs_location'; 

6) load data local inpath 'local_path' into table table1; -- cargará datos desde local y también se agregará a la tabla de destino.

7) load data inpath 'hdfs_path' into table table1; -- cargará datos desde la ubicación de hdfs y también se agregará a la tabla de destino.

8) insert into table2 values('aa','bb','cc'); -- Digamos que table2 tiene solo 3 columnas.

9) Inserción múltiple en la tabla de la colmena

 0
Author: Brijesh Mishra,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-10 08:51:57