Анализ запросов в Hive
Перед выполнением каждого запроса оптимизатор Hive (Cost-Based Optimizer, CBO) создает план выполнения — последовательность задач, которые должны быть выполнены, чтобы получить нужные данные наиболее эффективным способом.
Используя команды Hive EXPLAIN и ANALYZE, вы можете просматривать планы выполнения и получать подробную статистику о работе Hive для оптимизации ваших запросов.
Тестовая база данных
Для демонстрации примеров в данной статье используются Hive-таблицы transactions и accounts, структура которых описана ниже.
SELECT * FROM transactions; +----------------------+----------------------+--------------------------+------------------------+ | transactions.txn_id | transactions.acc_id | transactions.txn_amount | transactions.txn_date | +----------------------+----------------------+--------------------------+------------------------+ | 1 | 1002 | 10.00 | 2023-01-01 | | 8 | 1003 | 50.00 | 2023-01-01 | | 3 | 1002 | 30.00 | 2023-01-02 | | 4 | 1001 | 100.50 | 2023-01-02 | | 2 | 1002 | 20.00 | 2023-01-03 | | 6 | 1001 | 200.50 | 2023-01-03 | | 7 | 1003 | 50.00 | 2023-01-03 | | 5 | 1001 | 150.50 | 2023-01-04 | | 9 | 1003 | 75.00 | 2023-01-04 | +----------------------+----------------------+--------------------------+------------------------+ SELECT * FROM accounts; +--------------+---------------------+ | accounts.id | accounts.full_name | +--------------+---------------------+ | 1001 | John Smith | | 1002 | Sarah Connor | | 1003 | Rick Sanchez | +--------------+---------------------+
Для создания и наполнения тестовых таблиц Hive выполните следующий SQL с помощью /bin/beeline.
CREATE DATABASE IF NOT EXISTS explain_demo;
USE explain_demo;
DROP TABLE IF EXISTS transactions;
CREATE TABLE transactions(txn_id int, acc_id int, txn_amount decimal(10,2)) PARTITIONED BY (txn_date date);
INSERT INTO transactions VALUES
(1, 1002, 10.00, '2023-01-01'),
(2, 1002, 20.00, '2023-01-03'),
(3, 1002, 30.00, '2023-01-02'),
(4, 1001, 100.50, '2023-01-02'),
(5, 1001, 150.50, '2023-01-04'),
(6, 1001, 200.50, '2023-01-03'),
(7, 1003, 50.00, '2023-01-03'),
(8, 1003, 50.00, '2023-01-01'),
(9, 1003, 75.00, '2023-01-04');
DROP TABLE IF EXISTS accounts;
CREATE TABLE accounts(id int, full_name string);
INSERT INTO accounts VALUES
(1001, 'John Smith'),
(1002, 'Sarah Connor'),
(1003, 'Rick Sanchez');
EXPLAIN
Команда EXPLAIN выводит план выполнения (execution plan) Hive-запроса.
Вывод включает в себя подробное описание того, какими этапами Hive планирует выполнить запрос.
Синтаксис имеет следующий вид:
EXPLAIN [EXTENDED|DEPENDENCY|AUTHORIZATION|VECTORIZATION|FORMATTED] <query>
Где:
-
EXTENDED— возвращает расширенную информацию о плане выполнения. -
DEPENDENCY— содержит подробную информацию о таблицах и партициях, которые задействованы в запросе. -
AUTHORIZATION— возвращает информацию о всех объектах, требующих авторизации, включая проблемы с правами доступа (если таковые имеются). -
VECTORIZATION— возвращает информацию о тех Map/Reduce-задачах, для которых не применялась векторизация. -
FORMATTED— форматирует вывод в JSON-формате. -
<query>— запрос, который необходимо анализировать.
EXPLAIN
Команда EXPLAIN возвращает общую информацию о плане выполнения запроса.
CREATE TABLE IF NOT EXISTS top_txns_per_acc(acc_id int, max_txn_value decimal(10,2));
EXPLAIN
FROM transactions INSERT OVERWRITE TABLE top_txns_per_acc
SELECT acc_id, MAX(txn_amount) GROUP BY acc_id;
Результат:
+----------------------------------------------------+
| Explain |
+----------------------------------------------------+
| Plan optimized by CBO. |
| |
| Vertex dependency in root stage |
| Reducer 2 <- Map 1 (SIMPLE_EDGE) |
| Reducer 3 <- Reducer 2 (CUSTOM_SIMPLE_EDGE) |
| |
| Stage-3 |
| Stats Work{} |
| Stage-0 |
| Move Operator |
| table:{"name:":"explain_demo.top_txns_per_acc"} |
| Stage-2 |
| Dependency Collection{} |
| Stage-1 |
| Reducer 3 |
| File Output Operator [FS_13] |
| Group By Operator [GBY_11] (rows=1 width=552) |
| Output:["_col0","_col1"],aggregations:["compute_stats(VALUE._col0)","compute_stats(VALUE._col1)"] |
| <-Reducer 2 [CUSTOM_SIMPLE_EDGE] |
| File Output Operator [FS_6] |
| table:{"name:":"explain_demo.top_txns_per_acc"} |
| Group By Operator [GBY_4] (rows=4 width=12) |
| Output:["_col0","_col1"],aggregations:["max(VALUE._col0)"],keys:KEY._col0 |
| <-Map 1 [SIMPLE_EDGE] vectorized |
| SHUFFLE [RS_16] |
| PartitionCols:_col0 |
| Group By Operator [GBY_15] (rows=9 width=12) |
| Output:["_col0","_col1"],aggregations:["max(txn_amount)"],keys:acc_id |
| Select Operator [SEL_14] (rows=9 width=12) |
| Output:["acc_id","txn_amount"] |
| TableScan [TS_0] (rows=9 width=12) |
| explain_demo@transactions,transactions,Tbl:COMPLETE,Col:NONE,Output:["acc_id","txn_amount"] |
| PARTITION_ONLY_SHUFFLE [RS_10] |
| Group By Operator [GBY_9] (rows=1 width=536) |
| Output:["_col0","_col1"],aggregations:["compute_stats(acc_id, 'hll')","compute_stats(max_txn_value, 'hll')"] |
| Select Operator [SEL_8] (rows=4 width=12) |
| Output:["acc_id","max_txn_value"] |
| Please refer to the previous Group By Operator [GBY_4] |
| |
+----------------------------------------------------+
Вывод EXPLAIN может значительно отличаться в зависимости от запроса, но основными информационными блоками являются следующие:
-
Stage dependencies. Содержит список этапов (stages), которые вместе формируют общий план выполнения. Отдельный этап может являться Map/Reduce-задачей, операцией чтения/записи в HDFS, обращением к Hive Metastore и так далее.
-
Stage plans. Каждый блок описывает детали отдельного этапа, включая задействованные операторы, порядок сортировки и так далее.
EXPLAIN EXTENDED
Команда EXPLAIN EXTENDED выводит более подробную информацию о плане выполнения Hive.
Вывод включает в себя дополнительную информацию об операциях ввода-вывода HDFS, форматах данных, бакетах, расширенную статистику и так далее.
EXPLAIN EXTENDED
SELECT * FROM transactions
WHERE txn_amount > 100;
+----------------------------------------------------+
| Explain |
+----------------------------------------------------+
| STAGE DEPENDENCIES: |
| Stage-0 is a root stage |
| |
| STAGE PLANS: |
| Stage: Stage-0 |
| Fetch Operator |
| limit: -1 |
| Partition Description: |
| Partition |
| input format: org.apache.hadoop.mapred.TextInputFormat |
| output format: org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat |
| partition values: |
| txn_date 2023-01-01 |
| properties: |
| COLUMN_STATS_ACCURATE {"BASIC_STATS":"true","COLUMN_STATS":{"acc_id":"true","txn_amount":"true","txn_id":"true"}} |
| bucket_count -1 |
| column.name.delimiter , |
| columns txn_id,acc_id,txn_amount |
| columns.comments |
| columns.types int:int:decimal(10,2) |
| file.inputformat org.apache.hadoop.mapred.TextInputFormat |
| file.outputformat org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat |
| location hdfs://adh/apps/hive/warehouse/explain_demo.db/transactions/txn_date=2023-01-01 |
| name explain_demo.transactions |
| numFiles 1 |
| numRows 2 |
| partition_columns txn_date |
| partition_columns.types date |
| rawDataSize 24 |
| serialization.ddl struct transactions { i32 txn_id, i32 acc_id, decimal(10,2) txn_amount} |
| serialization.format 1 |
| serialization.lib org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe |
| totalSize 26 |
| transient_lastDdlTime 1702847838 |
| serde: org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe |
| |
| input format: org.apache.hadoop.mapred.TextInputFormat |
| output format: org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat |
| properties: |
| bucket_count -1 |
| bucketing_version 2 |
| column.name.delimiter , |
| columns txn_id,acc_id,txn_amount |
| columns.comments |
| columns.types int:int:decimal(10,2) |
| file.inputformat org.apache.hadoop.mapred.TextInputFormat |
| file.outputformat org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat |
| location hdfs://adh/apps/hive/warehouse/explain_demo.db/transactions |
| name explain_demo.transactions |
| partition_columns txn_date |
| partition_columns.types date |
| serialization.ddl struct transactions { i32 txn_id, i32 acc_id, decimal(10,2) txn_amount} |
| serialization.format 1 |
| serialization.lib org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe |
| transient_lastDdlTime 1702846232 |
| serde: org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe |
| name: explain_demo.transactions |
| name: explain_demo.transactions |
| Partition |
| input format: org.apache.hadoop.mapred.TextInputFormat |
| output format: org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat |
| partition values: |
| txn_date 2023-01-02 |
| properties: |
| COLUMN_STATS_ACCURATE {"BASIC_STATS":"true","COLUMN_STATS":{"acc_id":"true","txn_amount":"true","txn_id":"true"}} |
| bucket_count -1 |
| column.name.delimiter , |
| columns txn_id,acc_id,txn_amount |
| columns.comments |
| columns.types int:int:decimal(10,2) |
| file.inputformat org.apache.hadoop.mapred.TextInputFormat |
| file.outputformat org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat |
| location hdfs://adh/apps/hive/warehouse/explain_demo.db/transactions/txn_date=2023-01-02 |
| name explain_demo.transactions |
| numFiles 1 |
| numRows 2 |
| partition_columns txn_date |
| partition_columns.types date |
| rawDataSize 25 |
| serialization.ddl struct transactions { i32 txn_id, i32 acc_id, decimal(10,2) txn_amount} |
| serialization.format 1 |
| serialization.lib org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe |
| totalSize 27 |
| transient_lastDdlTime 1702847838 |
| serde: org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe |
| |
| input format: org.apache.hadoop.mapred.TextInputFormat |
| output format: org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat |
| properties: |
| bucket_count -1 |
| bucketing_version 2 |
| column.name.delimiter , |
| columns txn_id,acc_id,txn_amount |
| columns.comments |
| columns.types int:int:decimal(10,2) |
| file.inputformat org.apache.hadoop.mapred.TextInputFormat |
| file.outputformat org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat |
| location hdfs://adh/apps/hive/warehouse/explain_demo.db/transactions |
| name explain_demo.transactions |
| partition_columns txn_date |
+----------------------------------------------------+
| Explain |
+----------------------------------------------------+
| partition_columns.types date |
| serialization.ddl struct transactions { i32 txn_id, i32 acc_id, decimal(10,2) txn_amount} |
| serialization.format 1 |
| serialization.lib org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe |
| transient_lastDdlTime 1702846232 |
| serde: org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe |
| name: explain_demo.transactions |
| name: explain_demo.transactions |
| Partition |
| input format: org.apache.hadoop.mapred.TextInputFormat |
| output format: org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat |
| partition values: |
| txn_date 2023-01-03 |
| properties: |
| COLUMN_STATS_ACCURATE {"BASIC_STATS":"true","COLUMN_STATS":{"acc_id":"true","txn_amount":"true","txn_id":"true"}} |
| bucket_count -1 |
| column.name.delimiter , |
| columns txn_id,acc_id,txn_amount |
| columns.comments |
| columns.types int:int:decimal(10,2) |
| file.inputformat org.apache.hadoop.mapred.TextInputFormat |
| file.outputformat org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat |
| location hdfs://adh/apps/hive/warehouse/explain_demo.db/transactions/txn_date=2023-01-03 |
| name explain_demo.transactions |
| numFiles 1 |
| numRows 3 |
| partition_columns txn_date |
| partition_columns.types date |
| rawDataSize 37 |
| serialization.ddl struct transactions { i32 txn_id, i32 acc_id, decimal(10,2) txn_amount} |
| serialization.format 1 |
| serialization.lib org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe |
| totalSize 40 |
| transient_lastDdlTime 1702847838 |
| serde: org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe |
| |
| input format: org.apache.hadoop.mapred.TextInputFormat |
| output format: org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat |
| properties: |
| bucket_count -1 |
| bucketing_version 2 |
| column.name.delimiter , |
| columns txn_id,acc_id,txn_amount |
| columns.comments |
| columns.types int:int:decimal(10,2) |
| file.inputformat org.apache.hadoop.mapred.TextInputFormat |
| file.outputformat org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat |
| location hdfs://adh/apps/hive/warehouse/explain_demo.db/transactions |
| name explain_demo.transactions |
| partition_columns txn_date |
| partition_columns.types date |
| serialization.ddl struct transactions { i32 txn_id, i32 acc_id, decimal(10,2) txn_amount} |
| serialization.format 1 |
| serialization.lib org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe |
| transient_lastDdlTime 1702846232 |
| serde: org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe |
| name: explain_demo.transactions |
| name: explain_demo.transactions |
| Partition |
| input format: org.apache.hadoop.mapred.TextInputFormat |
| output format: org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat |
| partition values: |
| txn_date 2023-01-04 |
| properties: |
| COLUMN_STATS_ACCURATE {"BASIC_STATS":"true","COLUMN_STATS":{"acc_id":"true","txn_amount":"true","txn_id":"true"}} |
| bucket_count -1 |
| column.name.delimiter , |
| columns txn_id,acc_id,txn_amount |
| columns.comments |
| columns.types int:int:decimal(10,2) |
| file.inputformat org.apache.hadoop.mapred.TextInputFormat |
| file.outputformat org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat |
| location hdfs://adh/apps/hive/warehouse/explain_demo.db/transactions/txn_date=2023-01-04 |
| name explain_demo.transactions |
| numFiles 1 |
| numRows 2 |
| partition_columns txn_date |
| partition_columns.types date |
| rawDataSize 25 |
| serialization.ddl struct transactions { i32 txn_id, i32 acc_id, decimal(10,2) txn_amount} |
| serialization.format 1 |
| serialization.lib org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe |
| totalSize 27 |
| transient_lastDdlTime 1702847838 |
| serde: org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe |
| |
| input format: org.apache.hadoop.mapred.TextInputFormat |
| output format: org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat |
| properties: |
| bucket_count -1 |
| bucketing_version 2 |
| column.name.delimiter , |
| columns txn_id,acc_id,txn_amount |
| columns.comments |
| columns.types int:int:decimal(10,2) |
| file.inputformat org.apache.hadoop.mapred.TextInputFormat |
| file.outputformat org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat |
| location hdfs://adh/apps/hive/warehouse/explain_demo.db/transactions |
| name explain_demo.transactions |
| partition_columns txn_date |
+----------------------------------------------------+
| Explain |
+----------------------------------------------------+
| partition_columns.types date |
| serialization.ddl struct transactions { i32 txn_id, i32 acc_id, decimal(10,2) txn_amount} |
| serialization.format 1 |
| serialization.lib org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe |
| transient_lastDdlTime 1702846232 |
| serde: org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe |
| name: explain_demo.transactions |
| name: explain_demo.transactions |
| Processor Tree: |
| TableScan |
| alias: transactions |
| GatherStats: false |
| Filter Operator |
| isSamplingPred: false |
| predicate: (txn_amount > 100) (type: boolean) |
| Select Operator |
| expressions: txn_id (type: int), acc_id (type: int), txn_amount (type: decimal(10,2)), txn_date (type: date) |
| outputColumnNames: _col0, _col1, _col2, _col3 |
| ListSink |
| |
+----------------------------------------------------+
EXPLAIN DEPENDENCY
Команда EXPLAIN DEPENDENCY возвращает дополнительную информацию о всех источниках входных данных (таблицы Hive, партиции, HDFS-файлы), к которым осуществляется доступ при выполнении запроса.
EXPLAIN DEPENDENCY
SELECT t.txn_id, a.full_name
FROM transactions t
JOIN accounts a ON (t.acc_id=a.id)
Результат:
+----------------------------------------------------+
| Explain |
+----------------------------------------------------+
| {"input_tables":[{"tablename":"explain_demo@transactions","tabletype":"MANAGED_TABLE"},{"tablename":"explain_demo@accounts","tabletype":"MANAGED_TABLE"}],"input_partitions":[{"partitionName":"explain_demo@transactions@txn_date=2023-01-01"},{"partitionName":"explain_demo@transactions@txn_date=2023-01-02"},{"partitionName":"explain_demo@transactions@txn_date=2023-01-03"},{"partitionName":"explain_demo@transactions@txn_date=2023-01-04"}]} |
+----------------------------------------------------+
EXPLAIN AUTHORIZATION
Используя EXPLAIN AUTHORIZATION, можно получить информацию о всех ошибках авторизации, включая проблемы с правами доступа (если таковые имеются).
Например:
EXPLAIN AUTHORIZATION
SELECT a.full_name, t.txn_date, t.txn_id from accounts a
JOIN transactions t ON (a.id=t.acc_id);
Результат:
+----------------------------------------------------+ | Explain | +----------------------------------------------------+ | INPUTS: | | explain_demo@accounts | | explain_demo@transactions | | explain_demo@transactions@txn_date=2023-01-01 | | explain_demo@transactions@txn_date=2023-01-02 | | explain_demo@transactions@txn_date=2023-01-03 | | explain_demo@transactions@txn_date=2023-01-04 | | OUTPUTS: | | hdfs://adh/tmp/hive/hive/de6b68f3-0c62-40e9-84ac-8e34916558c9/hive_2023-12-18_09-26-13_342_1170854594803480484-104/-mr-10001 | | CURRENT_USER: | | hive | | OPERATION: | | QUERY | +----------------------------------------------------+
EXPLAIN VECTORIZATION
Ключевое слово VECTORIZATION добавляет в вывод EXPLAIN информацию, указывающую, почему для определенных Map/Reduce-задач не использовалась векторизация (если таковые задачи имеются).
Синтаксис имеет следующий вид:
EXPLAIN VECTORIZATION [ONLY] [SUMMARY|OPERATOR|EXPRESSION|DETAIL]
Где:
-
ONLY— скрывает большинство элементов, не связанных с векторизацией. -
SUMMARY— отображает, включена ли векторизация, а также добавляет краткую информацию о работе Map/Reduce-задач. -
OPERATOR— показывает информацию о векторизации для операторов. -
EXPRESSION— показывает информацию о векторизации для выражений. -
DETAIL— наиболее подробный уровень информации. Включает в себя все вышеперечисленное.
Сбор статистики с помощью ANALYZE
При обработке запросов оптимизатор CBO активно использует статистику Hive для выбора оптимального плана выполнения запроса с точки зрения системных ресурсов.
Эта статистика (количество строк, количество файлов, размер сырых данных) хранится в Hive Metastore и по умолчанию генерируется автоматически при добавлении новых данных в таблицы Hive (hive.stats.autogather=true).
Сбор статистики
Для сбора статистики определенной таблицы или партиции в любой момент времени используйте команду ANALYZE.
Эта команда вычисляет статистику по запросу и записывает ее в Hive Metastore.
Hive поддерживает статистику на уровне таблиц, партиций и столбцов.
Синтаксис выглядит следующим образом:
ANALYZE TABLE <tbl_name> [PARTITION(<partition>)] COMPUTE STATISTICS
[FOR COLUMNS c1, c2, ...]
[NOSCAN];
Где:
-
FOR COLUMNS— вычисляет статистику либо для всех столбцов таблицы (если имена столбцов не указаны), либо только для указанных столбцов. -
NOSCAN— если параметр указан, команда не сканирует все файлы. Вместо этого в статистике будет содержаться информация о количестве байт и физическом размере в байтах.
|
ПРИМЕЧАНИЕ
По умолчанию сбор статистики включен для вновь созданных таблиц/партиций, поэтому нет необходимости вычислять статистику вручную, если только не было изменено дефолтное значение свойства hive.stats.autogather=true.
|
После сохранения статистики в Hive Metastore вы можете просмотреть статистику, выполнив команду DESCRIBE.
Синтаксис команды следующий:
DESCRIBE [EXTENDED|FORMATTED] <tbl_name> [PARTITION(<partition>)]
В следующем примере показан сбор и вывод статистики Hive для всей таблицы:
ANALYZE TABLE transactions COMPUTE STATISTICS;
DESCRIBE EXTENDED transactions;
Вывод:
+-----------------------------+----------------------------------------------------+----------+
| col_name | data_type | comment |
+-----------------------------+----------------------------------------------------+----------+
| txn_id | int | |
| acc_id | int | |
| txn_amount | decimal(10,2) | |
| txn_date | date | |
| | NULL | NULL |
| # Partition Information | NULL | NULL |
| # col_name | data_type | comment |
| txn_date | date | |
| | NULL | NULL |
| Detailed Table Information | Table(tableName:transactions, explain_demo, owner:hive, createTime:1702839122, lastAccessTime:0, retention:0, sd:StorageDescriptor(cols:[FieldSchema(name:txn_id, type:int, comment:null), FieldSchema(name:acc_id, type:int, comment:null), FieldSchema(name:txn_amount, type:decimal(10,2), comment:null), FieldSchema(name:txn_date, type:date, comment:null)], location:hdfs://adh/apps/hive/warehouse/transactions, inputFormat:org.apache.hadoop.mapred.TextInputFormat, outputFormat:org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat, compressed:false, numBuckets:-1, serdeInfo:SerDeInfo(name:null, serializationLib:org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe, parameters:{serialization.format=1}), bucketCols:[], sortCols:[], parameters:{}, skewedInfo:SkewedInfo(skewedColNames:[], skewedColValues:[], skewedColValueLocationMaps:{}), storedAsSubDirectories:false), partitionKeys:[FieldSchema(name:txn_date, type:date, comment:null)], parameters:{totalSize=120, numRows=9, rawDataSize=111, COLUMN_STATS_ACCURATE={\"BASIC_STATS\":\"true\"}, numFiles=4, numPartitions=4, transient_lastDdlTime=1702839122, bucketing_version=2}, viewOriginalText:null, viewExpandedText:null, tableType:MANAGED_TABLE, rewriteEnabled:false, catName:hive, ownerType:USER) | |
+-----------------------------+----------------------------------------------------+----------+
Для отображения статистики определенной партиции в Hive-таблице используйте следующий пример:
ANALYZE TABLE transactions PARTITION(txn_date='2023-01-03') COMPUTE STATISTICS;
DESCRIBE EXTENDED transactions PARTITION(txn_date='2023-01-03');
Подробная статистика партиции содержится в блоке Detailed Partition Information.
+---------------------------------+----------------------------------------------------+----------+
| col_name | data_type | comment |
+---------------------------------+----------------------------------------------------+----------+
| txn_id | int | |
| acc_id | int | |
| txn_amount | decimal(10,2) | |
| txn_date | date | |
| | NULL | NULL |
| # Partition Information | NULL | NULL |
| # col_name | data_type | comment |
| txn_date | date | |
| | NULL | NULL |
| Detailed Partition Information | Partition(values:[2023-01-03], dbName:explain_demo, tableName:transactions, createTime:0, lastAccessTime:0, sd:StorageDescriptor(cols:[FieldSchema(name:txn_id, type:int, comment:null), FieldSchema(name:acc_id, type:int, comment:null), FieldSchema(name:txn_amount, type:decimal(10,2), comment:null), FieldSchema(name:txn_date, type:date, comment:null)], location:hdfs://adh/apps/hive/warehouse/transactions/txn_date=2023-01-03, inputFormat:org.apache.hadoop.mapred.TextInputFormat, outputFormat:org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat, compressed:false, numBuckets:-1, serdeInfo:SerDeInfo(name:null, serializationLib:org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe, parameters:{serialization.format=1}), bucketCols:[], sortCols:[], parameters:{}, skewedInfo:SkewedInfo(skewedColNames:[], skewedColValues:[], skewedColValueLocationMaps:{}), storedAsSubDirectories:false), parameters:{totalSize=40, numRows=3, rawDataSize=37, COLUMN_STATS_ACCURATE={"BASIC_STATS":"true","COLUMN_STATS":{"acc_id":"true","txn_amount":"true","txn_id":"true"}}, numFiles=1, transient_lastDdlTime=1702844180}, catName:hive) | |
+---------------------------------+----------------------------------------------------+----------+