在Hive中,如何添加不存在的列?



我想在表中添加一个新列,但仅在该列不存在的情况下。

如果列不存在,则此操作有效:

ALTER TABLE MyTable ADD COLUMNS (mycolumn string);

但是当我第二次执行它时,我得到一个错误。

Column 'mycolumn' exists

当我尝试使用CREATE TABLE和ADD PARTITION支持的"IF NOT EXISTS"语法时,我得到一个语法错误:

ALTER TABLE MyTable ADD IF NOT EXISTS COLUMNS (mycolumn string);
FAILED: ParseException line 3:42 required (...)+ loop did not match anything at input 'COLUMNS' in add partition statement

我需要的是一些可以执行itempotently的东西,这样我就可以运行我的查询,无论这列是否存在

您可以通过设置hive.cli.errors.ignore标志部分地解决这个问题。在这种情况下,即使查询失败,hive CLI也会强制执行进一步的查询。

在这个例子中:

SET hive.cli.errors.ignore=true;
ALTER TABLE MyTable ADD COLUMNS (mycolumn string);
ALTER TABLE MyTable ADD COLUMNS (mycolumn string);
ALTER TABLE MyTable ADD COLUMNS (mycolumn2 string);

hive将执行所有的查询,即使在第二个查询中会出现错误。

没有直接的方法。我的意思是通过一个查询。还有另外两种方法:

1)。使用JDBC:

1.1) Do describe on the table name.
1.2) You will get a list of columns in result set.
1.3) Check if your columns exists or not by iterating through the result set.

2)。使用hive Metastore client:

2.1) Create a object of HiveMetastoreClient
2.2) HiveMetastoreClient.getFields(<>db_name, <table_name>).get(index).getName() will give you the column name.
2.3) Check if your column exists of not by comparing the list.

希望有帮助…!!

最新更新