Nice programing

Hive에서 레코드를 삭제하고 업데이트하는 방법

nicepro 2020. 12. 13. 11:06
반응형

Hive에서 레코드를 삭제하고 업데이트하는 방법


Hadoop, Hive, Hive JD BC를 설치했습니다. 나를 위해 잘 돌아가고 있습니다. 하지만 여전히 문제가 있습니다. MySQL의 삭제 또는 업데이트 명령이 하이브에서 작동하지 않기 때문에 Hive를 사용하여 단일 레코드를 삭제하거나 업데이트하는 방법.

감사

hive> delete from student where id=1;
Usage: delete [FILE|JAR|ARCHIVE] <value> [<value>]*
Query returned non-zero code: 1, cause: null

Hive를 일반 RDBMS로 생각해서는 안됩니다. Hive는 매우 큰 불변 데이터 집합에 대한 일괄 처리에 더 적합합니다.

다음은 Hive 0.14 이전 버전에 적용됩니다 . 이후 버전 ashtonium 의 답변을 참조하세요 .

특정 레코드 또는 특정 레코드 집합의 삭제 또는 업데이트에 대해 지원되는 작업이 없습니다. 이것은 나에게 더 나쁜 스키마의 신호입니다.

공식 문서에서 찾을 수있는 내용은 다음과 같습니다 .

Hadoop is a batch processing system and Hadoop jobs tend to have high latency and
incur substantial overheads in job submission and scheduling. As a result -
latency for Hive queries is generally very high (minutes) even when data sets
involved are very small (say a few hundred megabytes). As a result it cannot be
compared with systems such as Oracle where analyses are conducted on a
significantly smaller amount of data but the analyses proceed much more
iteratively with the response times between iterations being less than a few
minutes. Hive aims to provide acceptable (but not optimal) latency for
interactive data browsing, queries over small data sets or test queries.

Hive is not designed for online transaction processing and does not offer
real-time queries and row level updates. It is best used for batch jobs over
large sets of immutable data (like web logs).

이 제한을 해결하는 방법은 파티션을 사용하는 것입니다. ID 가 무엇인지 모르겠지만 다른 ID 배치를 개별적으로 가져 오는 경우 테이블을 다시 디자인하여 ID로 파티션을 나눈 다음 제거하려는 ID에 대한 파티션을 쉽게 삭제할 수 있습니다.


Hive 버전 0.14.0부터 : INSERT ... VALUES, UPDATE 및 DELETE는 이제 완전한 ACID 지원과 함께 사용할 수 있습니다.

INSERT ... VALUES 구문 :

INSERT INTO TABLE tablename [PARTITION (partcol1[=val1], partcol2[=val2] ...)] VALUES values_row [, values_row ...]

여기서 values_row는 : (value [, value ...]) 여기서 값은 null 또는 유효한 SQL 리터럴입니다.

UPDATE 구문 :

UPDATE tablename SET column = value [, column = value ...] [WHERE expression]

DELETE 구문 :

DELETE FROM tablename [WHERE expression]

또한 Hive 트랜잭션 문서에서 :

ACID 쓰기 (삽입, 업데이트, 삭제)에서 테이블을 사용하려면 Hive 0.14.0부터 시작하여 테이블 속성 "트랜잭션"을 해당 테이블에 설정해야합니다. 이 값이 없으면 삽입이 이전 스타일로 수행됩니다. 업데이트 및 삭제는 금지됩니다.

Hive DML 참조 :
https://cwiki.apache.org/confluence/display/Hive/LanguageManual+DML
Hive 트랜잭션 참조 :
https://cwiki.apache.org/confluence/display/Hive/Hive+Transactions


네, 맞습니다. Hive는 UPDATE 옵션을 지원하지 않습니다. 그러나 다음 대안을 사용하여 결과를 얻을 수 있습니다.

에서 레코드 업데이트 partitioned Hive table:

  1. 기본 테이블은 일부 키로 분할 된 것으로 간주됩니다.
  2. 기본 테이블과 동일한 키로 파티션 된 스테이징 테이블에 증분 데이터 (업데이트 할 데이터)를로드합니다.
  3. 아래와 같이 LEFT OUTER JOIN 연산을 사용하여 두 테이블 (기본 및 준비 테이블)을 조인합니다.

덮어 쓰기 테이블 main_table 파티션 (c, d) 삽입 staging_table t2에서 t2.a, t2.b, t2.c, t2.d 선택 t1.a = t2.a의 왼쪽 외부 조인 main_table t1;

위의 예에서 main_table 및 staging_table은 (c, d) 키를 사용하여 분할됩니다. 테이블은 LEFT OUTER JOIN을 통해 조인되고 결과는 main_table의 파티션을 덮어 쓰는 데 사용됩니다.

un-partitioned Hive tableUPDATE 작업 의 경우에도 유사한 접근 방식을 사용할 수 있습니다 .


작업의 결과로 테이블에 남겨 둘 데이터 세트로 테이블을 덮어 쓰는 해결 방법을 사용하여 테이블에서 행을 삭제할 수 있습니다.

insert overwrite table your_table 
    select * from your_table 
    where id <> 1
;

이 해결 방법은 쉽게 식별 할 수있는 행의 대량 삭제에 주로 유용합니다. 또한 분명히 이렇게하면 데이터가 엉망이 될 수 있으므로 테이블 백업을 권장하고 "삭제"규칙을 계획 할 때주의해야합니다.


INSERT, UPDATE, DELETE에 대해 설정할 구성 값 위에 나열된 새 매개 변수 외에도 일부 기존 매개 변수가 INSERT ... VALUES, UPDATE 및 DELETE를 지원하도록 설정되어야합니다.

구성 키로 설정해야합니다.

hive.support.concurrency true (default is false) hive.enforce.bucketing true (default is false) (Not required as of Hive 2.0) hive.exec.dynamic.partition.mode nonstrict (default is strict)

압축을 위해 설정할 구성 값

시스템의 데이터가 Hive 사용자 (예 : Hive 메타 스토어가 실행되는 사용자)가 소유하지 않은 경우 Hive는 압축을 수행하기 위해 데이터를 소유 한 사용자로 실행할 권한이 필요합니다. 사용자를 가장하도록 HiveServer2를 이미 설정 한 경우 추가로 수행 할 작업은 Hive가 Hive 메타 스토어를 실행하는 호스트에서 사용자를 가장 할 권한이 있는지 확인하는 것입니다. 이는 Hadoop의 core-site.xml 파일에있는 hadoop.proxyuser.hive.hosts에 호스트 이름을 추가하여 수행됩니다. 아직이 작업을 수행하지 않은 경우 Hive를 프록시 사용자로 구성해야합니다. 이를 위해서는 Hive 메타 스토어를 실행하는 사용자에 대한 키탭을 설정하고 Hadoop의 core-site.xml 파일에 hadoop.proxyuser.hive.hosts 및 hadoop.proxyuser.hive.groups를 추가해야합니다. 사용중인 Hadoop 버전의 보안 모드에 대한 Hadoop 설명서를 참조하십시오 (예 :

UPDATE 문에는 다음과 같은 제한 사항이 있습니다.

WHERE 절의 식은 Hive SELECT 절에서 지원하는 식이어야합니다.

파티션 및 버킷 열은 업데이트 할 수 없습니다.

UPDATE 문에 대해 쿼리 벡터화가 자동으로 비활성화됩니다. 그러나 업데이트 된 테이블은 여전히 ​​벡터화를 사용하여 쿼리 할 수 ​​있습니다.

SET 문의 오른쪽에는 하위 쿼리가 허용되지 않습니다.

다음 예제는이 문의 올바른 사용법을 보여줍니다.

UPDATE students SET name = null WHERE gpa <= 1.0;

DELETE 문

DELETE 문을 사용하여 Apache Hive에 이미 기록 된 데이터를 삭제합니다.

DELETE FROM tablename [WHERE expression];

DELETE 문에는 다음과 같은 제한이 있습니다. 쿼리 벡터화는 DELETE 작업에 대해 자동으로 비활성화됩니다. 그러나 삭제 된 데이터가있는 테이블은 여전히 ​​벡터화를 사용하여 쿼리 할 수 ​​있습니다.

다음 예제는이 문의 올바른 사용법을 보여줍니다.

DELETE FROM students WHERE gpa <= 1,0;


CLI는 귀하의 실수가 어디에 있는지 알려줍니다. delete WHAT? from student...

삭제 : Hadoop-Hive에서 테이블을 삭제 / 자르는 방법은 무엇입니까?

업데이트 : Hive의 업데이트, SET 옵션


모든 레코드를 삭제하려면 해결 방법으로 OVERWRITE 모드에서 테이블에 빈 파일을로드합니다.

hive> LOAD DATA LOCAL INPATH '/root/hadoop/textfiles/empty.txt' OVERWRITE INTO TABLE employee;
Loading data to table default.employee
Table default.employee stats: [numFiles=1, numRows=0, totalSize=0, rawDataSize=0]
OK
Time taken: 0.19 seconds

hive> SELECT * FROM employee;
OK
Time taken: 0.052 seconds

다가오는 Hive 버전에서는 한 번에 한 행을 가져 오는 대신 행의 '다발'에 대해 CRUD 작업을 수행하려고 할 때 가장 중요한 SET 기반 업데이트 / 삭제 처리를 허용 할 것입니다.

그동안 http://linkd.in/1Fq3wdb에 문서화 된 동적 파티션 기반 접근 방식을 시도했습니다 .

귀하의 필요에 맞는지 확인하십시오.


Hive를 설치하고 구성했으면 간단한 테이블을 만듭니다.

hive>create table testTable(id int,name string)row format delimited fields terminated by ',';

그런 다음 테스트 테이블에 몇 개의 행을 삽입하십시오.

hive>insert into table testTable values (1,'row1'),(2,'row2');

이제 방금 테이블에 삽입 한 레코드를 삭제하십시오.

hive>delete from testTable where id = 1;

오류! FAILED : SemanticException [오류 10294] : 이러한 작업을 지원하지 않는 트랜잭션 관리자를 사용하여 업데이트 또는 삭제를 시도했습니다.

기본적으로 트랜잭션은 해제되도록 구성됩니다. 변환 관리자에서 사용하는 삭제 작업은 업데이트가 지원되지 않는다고합니다. 업데이트 / 삭제를 지원하려면 다음 구성을 변경해야합니다.

cd  $HIVE_HOME
vi conf/hive-site.xml

파일에 아래 속성 추가

<property>
  <name>hive.support.concurrency</name>
  <value>true</value>
 </property>
 <property>
  <name>hive.enforce.bucketing</name>
  <value>true</value>
 </property>
 <property>
  <name>hive.exec.dynamic.partition.mode</name>
  <value>nonstrict</value>
 </property>
 <property>
  <name>hive.txn.manager</name>
  <value>org.apache.hadoop.hive.ql.lockmgr.DbTxnManager</value>
 </property>
 <property>
  <name>hive.compactor.initiator.on</name>
  <value>true</value>
 </property>
 <property>
  <name>hive.compactor.worker.threads</name>
  <value>2</value>
 </property>

서비스를 다시 시작한 다음 delete 명령을 다시 시도하십시오.

오류!

FAILED : LockException [오류 10280] : 메타 스토어와 통신하는 동안 오류가 발생했습니다.

메타 스토어에 문제가 있습니다. 삽입 / 업데이트 / 삭제 작업을 사용하려면 현재 개발중인 기능이므로 conf / hive-site.xml에서 다음 구성을 변경해야합니다.

<property>
  <name>hive.in.test</name>
  <value>true</value>
 </property>

서비스를 다시 시작한 다음 명령을 다시 삭제하십시오.

hive>delete from testTable where id = 1;

오류!

FAILED: SemanticException [Error 10297]: Attempt to do update or delete on table default.testTable that does not use an AcidOutputFormat or is not bucketed.

Only ORC file format is supported in this first release. The feature has been built such that transactions can be used by any storage format that can determine how updates or deletes apply to base records (basically, that has an explicit or implicit row id), but so far the integration work has only been done for ORC.

Tables must be bucketed to make use of these features. Tables in the same system not using transactions and ACID do not need to be bucketed.

See below built table example with ORCFileformat, bucket enabled and ('transactional'='true').

hive>create table testTableNew(id int ,name string ) clustered by (id) into 2 buckets stored as orc TBLPROPERTIES('transactional'='true');

Insert :

hive>insert into table testTableNew values (1,'row1'),(2,'row2'),(3,'row3');

Update :

hive>update testTableNew set name = 'updateRow2' where id = 2;

Delete :

hive>delete from testTableNew where id = 1;

Test :

hive>select * from testTableNew ;

UPDATE or DELETE a record isn't allowed in Hive, but INSERT INTO is acceptable.
A snippet from Hadoop: The Definitive Guide(3rd edition):

Updates, transactions, and indexes are mainstays of traditional databases. Yet, until recently, these features have not been considered a part of Hive's feature set. This is because Hive was built to operate over HDFS data using MapReduce, where full-table scans are the norm and a table update is achieved by transforming the data into a new table. For a data warehousing application that runs over large portions of the dataset, this works well.

Hive doesn't support updates (or deletes), but it does support INSERT INTO, so it is possible to add new rows to an existing table.


To achieve your current need, you need to fire below query

> insert overwrite table student 
> select *from student 
> where id <> 1;

This will delete current table and create new table with same name with all rows except the rows that you want to exclude/delete

I tried this on Hive 1.2.1


Delete has been recently added in Hive version 0.14 Deletes can only be performed on tables that support ACID Below is the link from Apache .

https://cwiki.apache.org/confluence/display/Hive/LanguageManual+DML#LanguageManualDML-Delete


Good news,Insert updates and deletes are now possible on Hive/Impala using Kudu.

You need to use IMPALA/kudu to maintain the tables and perform insert/update/delete records. Details with examples can be found here: insert-update-delete-on-hadoop

Please share the news if you are excited.

-MIK


Recently I was looking to resolve a similar issue, Apache Hive, Hadoop do not support Update/Delete operations. So ? So you have two ways:

  1. Use a backup table: Save the whole table in a backup_table, then truncate your input table, then re-write only the data you are intrested to mantain.
  2. Use Uber Hudi: It's a framework created by Uber to resolve the HDFS limitations including Deletion and Update. You can give a look in this link: https://eng.uber.com/hoodie/

an example for point 1:

Create table bck_table like input_table;
Insert overwrite table bck_table 
    select * from input_table;
Truncate table input_table;
Insert overwrite table input_table
    select * from bck_table where id <> 1;

NB: If the input_table is an external table you must follow the following link: How to truncate a partitioned external table in hive?

참고URL : https://stackoverflow.com/questions/17810537/how-to-delete-and-update-a-record-in-hive

반응형