Перейти к содержимому

Replace columns hive что делает

  • автор:

Hive — Alter Table

This chapter explains how to alter the attributes of a table such as changing its table name, changing column names, adding columns, and deleting or replacing columns.

Alter Table Statement

It is used to alter a table in Hive.

Syntax

The statement takes any of the following syntaxes based on what attributes we wish to modify in a table.

Rename To… Statement

The following query renames the table from employee to emp.

JDBC Program

The JDBC program to rename a table is as follows.

Save the program in a file named HiveAlterRenameTo.java. Use the following commands to compile and execute this program.

Output:

Change Statement

The following table contains the fields of employee table and it shows the fields to be changed (in bold).

Field Name Convert from Data Type Change Field Name Convert to Data Type
eid int eid int
name String ename String
salary Float salary Double
designation String designation String

The following queries rename the column name and column data type using the above data:

JDBC Program

Given below is the JDBC program to change a column.

Save the program in a file named HiveAlterChangeColumn.java. Use the following commands to compile and execute this program.

Output:

Add Columns Statement

The following query adds a column named dept to the employee table.

JDBC Program

The JDBC program to add a column to a table is given below.

Save the program in a file named HiveAlterAddColumn.java. Use the following commands to compile and execute this program.

Output:

Replace Statement

The following query deletes all the columns from the employee table and replaces it with emp and name columns:

JDBC Program

Given below is the JDBC program to replace eid column with empid and ename column with name.

Hive – Alter Table

Hive - Alter Table - myTechMint

Alter Table Statement

It is used to alter a table in Hive.

Syntax

The statement takes any of the following syntaxes based on what attributes we wish to modify in a table.

Rename To… Statement

The following query renames the table from employee to emp.

JDBC Program

The JDBC program to rename a table is as follows.

Save the program in a file named HiveAlterRenameTo.java. Use the following commands to compile and execute this program.

Output:

Change Statement

The following table contains the fields of employee table and it shows the fields to be changed (in bold).

Field Name Convert from Data Type Change Field Name Convert to Data Type
eid int eid int
name String ename String
salary Float salary Double
designation String designation String

The following queries rename the column name and column data type using the above data:

JDBC Program

Given below is the JDBC program to change a column.

Save the program in a file named HiveAlterChangeColumn.java. Use the following commands to compile and execute this program.

Output:

Add Columns Statement

The following query adds a column named dept to the employee table.

JDBC Program

The JDBC program to add a column to a table is given below.

Save the program in a file named HiveAlterAddColumn.java. Use the following commands to compile and execute this program.

Output:

Replace Statement

The following query deletes all the columns from the employee table and replaces it with emp and name columns:

JDBC Program

Given below is the JDBC program to replace eid column with empid and ename column with name.

Usage of ALTER in Hadoop Hive

Alter is a DDL command which helps in modifying the structure of the database objects. We can change the user provided properties of the database, structure of the tables and name of the objects.

Database Level:

Database Properties:
ALTER (DATABASE|SCHEMA) database_name
SET DBPROPERTIES (property_name = property_value, …);

This helps in modifying the database properties which user has provided at the time of database creation.

Example:
ALTER DATABASE TestDB SET dbProperties(‘Edited’= ‘UserName’, ‘Created’= ’2020-08-01’);

Database Access:
ALTER (DATABASE|SCHEMA) database_name SET OWNER [USER|ROLE] user_or_role;

This command helps in modifying the access level to a different user or a role.

Example:
ALTER DATABASE TestDB SET OWNER USER cloudera;

Database Location:
ALTER (DATABASE|SCHEMA) database_name SET LOCATION hdfs_path;

Though it is documented that the database location can be changed, however it is not allowing to do so in Hive 1.1.0 in CDH 5.10.0

Database Name:
ALTER DATABASE test_db RENAME TO test_db_new;

Though this is also documented but renaming a database is not allowed in Hive 1.1.0 in CDH 5.10.0

Note: As per the link here, there is no functionality to rename the existing database however there is a workaround to rename the database if you have necessary privileges on Hive metastore without changing the database location.

Table Level:

Renaming A Table:
ALTER TABLE [old_db_name.]old_table_name RENAME TO [new_db_name.]new_table_name;

Example:
ALTER TABLE tbOutput RENAME TO tbResults

Adding Columns of an Existing Table:
ALTER TABLE name ADD COLUMNS (col_spec[, col_spec …]);

Example:
ALTER TABLE test ADD COLUMNS (Col2 string, Col3 int)

Change Column Type
ALTER TABLE name CHANGE column_name new_name new_type;

Example:
ALTER TABLE test CHANGE col2 col2 int;

Change Column Type and Name
ALTER TABLE name CHANGE column_name new_name new_type;

Example:
ALTER TABLE test CHANGE col2 col4 string;

Replace Columns in the Table:
ALTER TABLE name REPLACE COLUMNS (col_spec[, col_spec …]);

The above command used to remove all existing columns and adds the new set of columns. REPLACE is used when you want to have an altogether different columns to your table.

Example:
ALTER TABLE test REPLACE COLUMNS (id int, col2 int, col3 string)

Change Table’s Location:
ALTER TABLE [TABLENAME] SET LOCATION [NewLocation]

Example:
ALTER TABLE tblTest SET LOCATION “hdfs:/DB/dbTest”;

LanguageManual DDL

HiveQL DDL statements are documented here, including:

  • CREATE DATABASE/SCHEMA, TABLE, VIEW, FUNCTION, INDEX
  • DROP DATABASE/SCHEMA, TABLE, VIEW, INDEX
  • TRUNCATE TABLE
  • ALTER DATABASE/SCHEMA, TABLE, VIEW
  • MSCK REPAIR TABLE (or ALTER TABLE RECOVER PARTITIONS)
  • SHOW DATABASES/SCHEMAS, TABLES, TBLPROPERTIES, VIEWS, PARTITIONS, FUNCTIONS, INDEX[ES], COLUMNS, CREATE TABLE
  • DESCRIBE DATABASE/SCHEMA, table_name, view_name, materialized_view_name

PARTITION statements are usually options of TABLE statements, except for SHOW PARTITIONS.

Keywords, Non-reserved Keywords and Reserved Keywords

All Keywords

Non-reserved Keywords

Reserved Keywords

ADD, ADMIN, AFTER, ANALYZE, ARCHIVE, ASC, BEFORE, BUCKET, BUCKETS, CASCADE, CHANGE, CLUSTER, CLUSTERED, CLUSTERSTATUS, COLLECTION, COLUMNS, COMMENT, COMPACT, COMPACTIONS, COMPUTE, CONCATENATE, CONTINUE, DATA, DATABASES, DATETIME, DAY, DBPROPERTIES, DEFERRED, DEFINED, DELIMITED, DEPENDENCY, DESC, DIRECTORIES, DIRECTORY, DISABLE, DISTRIBUTE, ELEM_TYPE, ENABLE, ESCAPED, EXCLUSIVE, EXPLAIN, EXPORT, FIELDS, FILE, FILEFORMAT, FIRST, FORMAT, FORMATTED, FUNCTIONS, HOLD_DDLTIME, HOUR, IDXPROPERTIES, IGNORE, INDEX, INDEXES, INPATH, INPUTDRIVER, INPUTFORMAT, ITEMS, JAR, KEYS, KEY_TYPE, LIMIT, LINES, LOAD, LOCATION, LOCK, LOCKS, LOGICAL, LONG, MAPJOIN, MATERIALIZED, METADATA, MINUS, MINUTE, MONTH, MSCK, NOSCAN, NO_DROP, OFFLINE, OPTION, OUTPUTDRIVER, OUTPUTFORMAT, OVERWRITE, OWNER, PARTITIONED, PARTITIONS, PLUS, PRETTY, PRINCIPALS, PROTECTION, PURGE, READ, READONLY, REBUILD, RECORDREADER, RECORDWRITER, REGEXP, RELOAD, RENAME, REPAIR, REPLACE, REPLICATION, RESTRICT, REWRITE, RLIKE, ROLE, ROLES, SCHEMA, SCHEMAS, SECOND, SEMI, SERDE, SERDEPROPERTIES, SERVER, SETS, SHARED, SHOW, SHOW_DATABASE, SKEWED, SORT, SORTED, SSL, STATISTICS, STORED, STREAMTABLE, STRING, STRUCT, TABLES, TBLPROPERTIES, TEMPORARY, TERMINATED, TINYINT, TOUCH, TRANSACTIONS, UNARCHIVE, UNDO, UNIONTYPE, UNLOCK, UNSET, UNSIGNED, URI, USE, UTC, UTCTIMESTAMP, VALUE_TYPE, VIEW, WHILE, YEAR

ALL, ALTER, AND, ARRAY, AS, AUTHORIZATION, BETWEEN, BIGINT, BINARY, BOOLEAN, BOTH, BY, CASE, CAST, CHAR, COLUMN, CONF, CREATE, CROSS, CUBE, CURRENT, CURRENT_DATE, CURRENT_TIMESTAMP, CURSOR, DATABASE, DATE, DECIMAL, DELETE, DESCRIBE, DISTINCT, DOUBLE, DROP, ELSE, END, EXCHANGE, EXISTS, EXTENDED, EXTERNAL, FALSE, FETCH, FLOAT, FOLLOWING, FOR, FROM, FULL, FUNCTION, GRANT, GROUP, GROUPING, HAVING, IF, IMPORT, IN, INNER, INSERT, INT, INTERSECT, INTERVAL, INTO, IS, JOIN, LATERAL, LEFT, LESS, LIKE, LOCAL, MACRO, MAP, MORE, NONE, NOT, NULL, OF, ON, OR, ORDER, OUT, OUTER, OVER, PARTIALSCAN, PARTITION, PERCENT, PRECEDING, PRESERVE, PROCEDURE, RANGE, READS, REDUCE, REVOKE, RIGHT, ROLLUP, ROW, ROWS, SELECT, SET, SMALLINT, TABLE, TABLESAMPLE, THEN, TIMESTAMP, TO, TRANSFORM, TRIGGER, TRUE, TRUNCATE, UNBOUNDED, UNION, UNIQUEJOIN, UPDATE, USER, USING, UTC_TMESTAMP, VALUES, VARCHAR, WHEN, WHERE, WINDOW, WITH

removed: REGEXP, RLIKE

added: AUTOCOMMIT, ISOLATION, LEVEL, OFFSET, SNAPSHOT, TRANSACTION, WORK, WRITE

added: COMMIT, ONLY, REGEXP, RLIKE, ROLLBACK, START

added: ABORT, KEY, LAST, NORELY, NOVALIDATE, NULLS, RELY, VALIDATE

added: CACHE, CONSTRAINT, FOREIGN, PRIMARY, REFERENCES

added: DETAIL, DOW, EXPRESSION, OPERATOR, QUARTER, SUMMARY, VECTORIZATION, WEEK, YEARS, MONTHS, WEEKS, DAYS, HOURS, MINUTES, SECONDS

added: DAYOFWEEK, EXTRACT, FLOOR, INTEGER, PRECISION, VIEWS

REGEXP and RLIKE are non-reserved keywords prior to Hive 2.0.0 and reserved keywords starting in Hive 2.0.0 (HIVE-11703).

Reserved keywords are permitted as identifiers if you quote them as described in Supporting Quoted Identifiers in Column Names ( version 0.13.0 and later, see HIVE-6013). Most of the keywords are reserved through HIVE-6617 in order to reduce the ambiguity in grammar (version 1.2.0 and later). There are two ways if the user still would like to use those reserved keywords as identifiers: (1) use quoted identifiers, (2) set hive.support.sql11.reserved.keywords=false. (version 2.1.0 and earlier)

Create/Drop/Alter/Use Database

Create Database

The uses of SCHEMA and DATABASE are interchangeable – they mean the same thing. CREATE DATABASE was added in Hive 0.6 (HIVE-675). The WITH DBPROPERTIES clause was added in Hive 0.7 (HIVE-1836).

MANAGEDLOCATION was added to database in Hive 4.0.0 (HIVE-22995). LOCATION now refers to the default directory for external tables and MANAGEDLOCATION refers to the default directory for managed tables. Its recommended that MANAGEDLOCATION be within metastore.warehouse.dir so all managed tables have a common root where common governance policies. It can be used with metastore.warehouse.tenant.colocation to have it point to a directory outside the warehouse root directory to have a tenant based common root where quotas and other policies can be set.

REMOTE databases were added in Hive 4.0.0 (HIVE-24396) for support for Data connectors. See documentation for Data connectors.

Drop Database

The uses of SCHEMA and DATABASE are interchangeable – they mean the same thing. DROP DATABASE was added in Hive 0.6 (HIVE-675). The default behavior is RESTRICT, where DROP DATABASE will fail if the database is not empty. To drop the tables in the database as well, use DROP DATABASE . CASCADE. Support for RESTRICT and CASCADE was added in Hive 0.8 (HIVE-2090).

Alter Database

The uses of SCHEMA and DATABASE are interchangeable – they mean the same thing. ALTER SCHEMA was added in Hive 0.14 (HIVE-6601).

The ALTER DATABASE . SET LOCATION statement does not move the contents of the database’s current directory to the newly specified location. It does not change the locations associated with any tables/partitions under the specified database. It only changes the default parent-directory where new tables will be added for this database. This behaviour is analogous to how changing a table-directory does not move existing partitions to a different location.

The ALTER DATABASE . SET MANAGEDLOCATION statement does not move the contents of the database’s managed tables directories to the newly specified location. It does not change the locations associated with any tables/partitions under the specified database. It only changes the default parent-directory where new tables will be added for this database. This behaviour is analogous to how changing a table-directory does not move existing partitions to a different location.

No other metadata about a database can be changed.

Use Database

USE sets the current database for all subsequent HiveQL statements. To revert to the default database, use the keyword " default " instead of a database name. To check which database is currently being used: SELECT current_database() (as of Hive 0.13.0).

USE database_name was added in Hive 0.6 (HIVE-675).

Create/Drop/Alter Connector

Create Connector

Since Hive 4.0.0 via HIVE-24396 Support for Data connectors was added in hive 4.0.0. Initial commit includes connector implementations for JDBC based datasource like MYSQL, POSTGRES, DERBY. Additional connector implementations will be added via followup commits.

TYPE — Type of the remote datasource this connector connects to. for example MYSQL. The type determines the Driver class and any other params specific to this datasource.

URL — URL of the remote datasource. In case of JDBC datasource, it would be the JDBC connection URL. For hive types, it would be the thrift URL.

COMMENT — A short description for this connector.

DCPROPERTIES: Contains a set of name/value pairs that are set for the connector. The credentials for the remote datasource are specified as part of the DCPROPERTIES as documented in the JDBC Storage Handler docs. All properties that start with a prefix of "hive.sql" are added to the tables mapped by this connector.

Drop Connector

Since Hive 4.0.0 via HIVE-24396. If there are databases that are mapped by this connector, drop still succeeds. Users will see errors when running DDLs like "show tables" in the mapped databases.

Alter Connector

Since Hive 4.0.0 via HIVE-24396

The ALTER CONNECTOR . SET DCPROPERTIES replaces the existing properties with the new set of properties specified in the ALTER DDL.

The ALTER CONNECTOR . SET URL replaces the existing URL with a new URL for the remote datasource. Any REMOTE databases that were created using the connector will continue to work as they are associated by name.

The ALTER CONNECTOR . SET OWNER changes the ownership of the connector object in hive.

Create/Drop/Truncate Table

Create Table

CREATE TABLE creates a table with the given name. An error is thrown if a table or view with the same name already exists. You can use IF NOT EXISTS to skip the error.

  • Table names and column names are case insensitive but SerDe and property names are case sensitive.
    • In Hive 0.12 and earlier, only alphanumeric and underscore characters are allowed in table and column names.
    • In Hive 0.13 and later, column names can contain any Unicode character (see HIVE-6013), however, dot (.) and colon (:) yield errors on querying, so they are disallowed in Hive 1.2.0 (see HIVE-10120). Any column name that is specified within backticks ( ` ) is treated literally. Within a backtick string, use double backticks ( « ) to represent a backtick character. Backtick quotation also enables the use of reserved keywords for table and column identifiers.
    • To revert to pre-0.13.0 behavior and restrict column names to alphanumeric and underscore characters, set the configuration property hive.support.quoted.identifiers to none . In this configuration, backticked names are interpreted as regular expressions. For details, see Supporting Quoted Identifiers in Column Names.
    • TBLPROPERTIES ("comment"="table_comment")
    • TBLPROPERTIES ("hbase.table.name"="table_name") – see HBase Integration.
    • TBLPROPERTIES ("immutable"="true") or ("immutable"="false") in release 0.13.0+ (HIVE-6406) – see Inserting Data into Hive Tables from Queries.
    • TBLPROPERTIES ("orc.compress"="ZLIB") or ("orc.compress"="SNAPPY") or ("orc.compress"="NONE") and other ORC properties – see ORC Files.
    • TBLPROPERTIES ("transactional"="true") or ("transactional"="false") in release 0.14.0+, the default is "false" – see Hive Transactions.
    • TBLPROPERTIES ("NO_AUTO_COMPACTION"="true") or ("NO_AUTO_COMPACTION"="false"), the default is "false" – see Hive Transactions.
    • TBLPROPERTIES ("compactor.mapreduce.map.memory.mb"="mapper_memory") – see Hive Transactions .
    • TBLPROPERTIES ("compactorthreshold.hive.compactor.delta.num.threshold"="threshold_num") – see Hive Transactions .
    • TBLPROPERTIES ("compactorthreshold.hive.compactor.delta.pct.threshold"="threshold_pct") – see Hive Transactions .
    • TBLPROPERTIES ( "auto.purge"="true") or ( "auto.purge"="false" ) in release 1.2.0+ (HIVE-9118) – see Drop Table, Drop Partitions, Truncate Table, and Insert Overwrite.
    • TBLPROPERTIES ("EXTERNAL"="TRUE") in release 0.6.0+ (HIVE-1329) – Change a managed table to an external table and vice versa for "FALSE".
      • As of Hive 2.4.0 (HIVE-16324) the value of the property ‘EXTERNAL’ is parsed as a boolean (case insensitive true or false) instead of a case sensitive string comparison.

      See Alter Table below for more information about table comments, table properties, and SerDe properties.

      See Type System and Hive Data Types for details about the primitive and complex data types.

      Managed and External Tables

      By default Hive creates managed tables, where files, metadata and statistics are managed by internal Hive processes. For details on the differences between managed and external table see Managed vs. External Tables.

      Storage Formats

      Hive supports built-in and custom-developed file formats. See CompressedStorage for details on compressed table storage .
      The following are some of the formats built-in to Hive:

      Storage Format Description
      STORED AS TEXTFILE Stored as plain text files. TEXTFILE is the default file format, unless the configuration parameter hive.default.fileformat has a different setting.

      Use the DELIMITED clause to read delimited files.

      Enable escaping for the delimiter characters by using the ‘ESCAPED BY’ clause (such as ESCAPED BY ‘\’)
      Escaping is needed if you want to work with data that can contain these delimiter characters.

      A custom NULL format can also be specified using the ‘NULL DEFINED AS’ clause (default is ‘\N’).

      (Hive 4.0) All BINARY columns in the table are assumed to be base64 encoded. To read the data as raw bytes:

      For example, ‘org.apache.hadoop.hive.contrib.fileformat.base64.Base64TextInputFormat’.

      For LZO compression, the values to use are
      ‘INPUTFORMAT "com.hadoop.mapred.DeprecatedLzoTextInputFormat"
      OUTPUTFORMAT "org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat"’

      Row Formats & SerDe

      You can create tables with a custom SerDe or using a native SerDe. A native SerDe is used if ROW FORMAT is not specified or ROW FORMAT DELIMITED is specified.
      Use the SERDE clause to create a table with a custom SerDe. For more information on SerDes see:

      You must specify a list of columns for tables that use a native SerDe. Refer to the Types part of the User Guide for the allowable column types.
      A list of columns for tables that use a custom SerDe may be specified but Hive will query the SerDe to determine the actual list of columns for this table.

      For general information about SerDes, see Hive SerDe in the Developer Guide. Also see SerDe for details about input and output processing.

      To change a table’s SerDe or SERDEPROPERTIES, use the ALTER TABLE statement as described below in Add SerDe Properties .

      RegEx

      ROW FORMAT SERDE
      ‘org.apache.hadoop.hive.serde2.RegexSerDe’
      WITH SERDEPROPERTIES
      (
      "input.regex" = "<regex>"
      )
      STORED AS TEXTFILE;

      Stored as plain text file, translated by Regular Expression.

      The following example defines a table in the default Apache Weblog format.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *