通过Java API获取Hive Metastore中的元数据信息

简介: 本文以Java API为例,介绍如何获取hive standalone metastore中的catalog、database、table等信息,通过该方式,我们可以方便地对元数据中心进行监控与管理。

在文章hive metastore 3.0介绍中,我们说到Hive 3.0.0版本开始,其单独提供了standalone metastore服务以作为像presto等处理引擎的元数据管理中心。

本文以Java API为例,介绍如何获取hive standalone metastore中的catalog、database、table等信息,通过该方式,我们可以方便地对元数据中心进行监控与管理。

当然,首先要在maven项目中导入如下依赖(以hive 3.1.2为例)

    <dependency>
      <groupId>org.apache.hive</groupId>
      <artifactId>hive-standalone-metastore</artifactId>
      <version>3.1.2</version>
    </dependency>

接着便可以通过如下方式建立客户端IMetaStoreClient与HMS进行连接

    /**
     * 初始化HMS连接
     * @param conf org.apache.hadoop.conf.Configuration HMS连接信息
     * @return IMetaStoreClient
     * @throws MetaException 异常
     */
    public static IMetaStoreClient init(Configuration conf) throws MetaException {
        try {
            return RetryingMetaStoreClient.getProxy(conf, false);
        } catch (MetaException e) {
            LOGGER.error("hms连接失败", e);
            throw e;
        }
    }

而HMS的连接信息有两种方式可以提供,一种是通过配置文件hive-site.xml的形式,另一种则是指定"hive.metastore.uris"参数,具体如下所示:

        Configuration conf = new Configuration();
        // 通过"hive.metastore.uris"参数提供HMS连接信息
        conf.set("hive.metastore.uris", "thrift://192.168.1.3:9083");    
         
        // 通过hive-site.xml方式提供HMS连接信息
        // conf.addResource("hive-site.xml");
        IMetaStoreClient client = HMSClient.init(conf);

通过上述方式建立与HMS连接的客户端之后,便可以通过下述接口获取catalog等信息

        System.out.println("----------------------------获取所有catalogs-------------------------------------");
        client.getCatalogs().forEach(System.out::println);

        System.out.println("------------------------获取catalog为hive的描述信息--------------------------------");
        System.out.println(client.getCatalog("hive").toString());

        System.out.println("--------------------获取catalog为hive的所有database-------------------------------");
        client.getAllDatabases("hive").forEach(System.out::println);

        System.out.println("---------------获取catalog为hive,database为hive的描述信息--------------------------");
        System.out.println(client.getDatabase("hive", "hive_storage"));

        System.out.println("-----------获取catalog为hive,database名为hive_storage下的所有表--------------------");
        client.getTables("hive", "hive_storage", "*").forEach(System.out::println);

        System.out.println("------获取catalog为hive,database名为hive_storage,表名为sample_table_1的描述信息-----");
        System.out.println(client.getTable("hive", "hive_storage", "sample_table_1").toString());

如果要了解更多使用方法,可参考HiveMetaStoreClient.java类

下面为具体代码实现:

maven项目的pom.xml文件

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.zh.ch.bigdata.hms</groupId>
  <artifactId>hms-client</artifactId>
  <version>1.0-SNAPSHOT</version>

  <name>hms-client</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>org.apache.hive</groupId>
      <artifactId>hive-standalone-metastore</artifactId>
      <version>3.1.2</version>
    </dependency>
  </dependencies>

  <build>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <!-- clean lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#clean_Lifecycle -->
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.1.0</version>
        </plugin>
        <!-- default lifecycle, jar packaging: see https://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_jar_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.8.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.22.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-jar-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
        <!-- site lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#site_Lifecycle -->
        <plugin>
          <artifactId>maven-site-plugin</artifactId>
          <version>3.7.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-project-info-reports-plugin</artifactId>
          <version>3.0.0</version>
        </plugin>
      </plugins>
    </pluginManagement>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
          <source>8</source>
          <target>8</target>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>

HMSClient.java测试代码

package com.zh.ch.bigdata.hms;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hive.metastore.IMetaStoreClient;
import org.apache.hadoop.hive.metastore.RetryingMetaStoreClient;
import org.apache.hadoop.hive.metastore.api.MetaException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class HMSClient {

    public static final Logger LOGGER = LoggerFactory.getLogger(HMSClient.class);

    /**
     * 初始化HMS连接
     * @param conf org.apache.hadoop.conf.Configuration
     * @return IMetaStoreClient
     * @throws MetaException 异常
     */
    public static IMetaStoreClient init(Configuration conf) throws MetaException {
        try {
            return RetryingMetaStoreClient.getProxy(conf, false);
        } catch (MetaException e) {
            LOGGER.error("hms连接失败", e);
            throw e;
        }
    }

    public static void main(String[] args) throws Exception {

        Configuration conf = new Configuration();
        conf.set("hive.metastore.uris", "thrift://192.168.1.3:9083");

        // conf.addResource("hive-site.xml");
        IMetaStoreClient client = HMSClient.init(conf);

        System.out.println("----------------------------获取所有catalogs-------------------------------------");
        client.getCatalogs().forEach(System.out::println);

        System.out.println("------------------------获取catalog为hive的描述信息--------------------------------");
        System.out.println(client.getCatalog("hive").toString());

        System.out.println("--------------------获取catalog为hive的所有database-------------------------------");
        client.getAllDatabases("hive").forEach(System.out::println);

        System.out.println("---------------获取catalog为hive,database为hive的描述信息--------------------------");
        System.out.println(client.getDatabase("hive", "hive_storage"));

        System.out.println("-----------获取catalog为hive,database名为hive_storage下的所有表--------------------");
        client.getTables("hive", "hive_storage", "*").forEach(System.out::println);

        System.out.println("------获取catalog为hive,database名为hive_storage,表名为sample_table_1的描述信息-----");
        System.out.println(client.getTable("hive", "hive_storage", "sample_table_1").toString());
    }
}

运行结果

----------------------------获取所有catalogs-------------------------------------
hive
------------------------获取catalog为hive的描述信息--------------------------------
Catalog(name:hive, description:Default catalog for Hive, locationUri:file:/user/hive/warehouse)
--------------------获取catalog为hive的所有database-------------------------------
default
hive
hive_storage
---------------获取catalog为hive,database为hive的描述信息--------------------------
Database(name:hive_storage, description:null, locationUri:s3a://hive-storage/, parameters:{}, ownerName:root, ownerType:USER, catalogName:hive)
-----------获取catalog为hive,database名为hive_storage下的所有表--------------------
sample_table_1
------获取catalog为hive,database名为hive_storage,表名为sample_table_1的描述信息-----
Table(tableName:sample_table_1, dbName:hive_storage, owner:root, createTime:1641540923, lastAccessTime:0, retention:0, sd:StorageDescriptor(cols:[FieldSchema(name:col1, type:string, comment:null), FieldSchema(name:col2, type:string, comment:null)], location:s3a://hive-storage/sample_table_1, inputFormat:org.apache.hadoop.hive.ql.io.orc.OrcInputFormat, outputFormat:org.apache.hadoop.hive.ql.io.orc.OrcOutputFormat, compressed:false, numBuckets:0, serdeInfo:SerDeInfo(name:sample_table_1, serializationLib:org.apache.hadoop.hive.ql.io.orc.OrcSerde, parameters:{}), bucketCols:[], sortCols:[], parameters:{}, skewedInfo:SkewedInfo(skewedColNames:[], skewedColValues:[], skewedColValueLocationMaps:{}), storedAsSubDirectories:false), partitionKeys:[], parameters:{presto_query_id=20220107_073521_00018_favj9, totalSize=366, numRows=1, rawDataSize=22, COLUMN_STATS_ACCURATE={"COLUMN_STATS":{"col1":"true","col2":"true"}}, numFiles=1, transient_lastDdlTime=1641540923, auto.purge=false, STATS_GENERATED_VIA_STATS_TASK=workaround for potential lack of HIVE-12730, presto_version=366}, viewOriginalText:null, viewExpandedText:null, tableType:MANAGED_TABLE, rewriteEnabled:false, catName:hive, ownerType:USER)  
相关文章
|
4月前
|
Java API 数据处理
Java新特性:使用Stream API重构你的数据处理
Java新特性:使用Stream API重构你的数据处理
|
4月前
|
Java 大数据 API
Java Stream API:现代集合处理与函数式编程
Java Stream API:现代集合处理与函数式编程
286 100
|
4月前
|
Java API 数据处理
Java Stream API:现代集合处理新方式
Java Stream API:现代集合处理新方式
318 101
|
4月前
|
并行计算 Java 大数据
Java Stream API:现代数据处理之道
Java Stream API:现代数据处理之道
270 101
|
5月前
|
存储 Java API
Java Stream API:现代数据处理之道
Java Stream API:现代数据处理之道
387 188
|
5月前
|
存储 Java API
Java Stream API:现代数据处理之道
Java Stream API:现代数据处理之道
306 92
|
4月前
|
安全 Java API
使用 Java 构建强大的 REST API 的四个基本技巧
本文结合探险领域案例,分享Java构建REST API的四大核心策略:统一资源命名、版本控制与自动化文档、安全防护及标准化异常处理,助力开发者打造易用、可维护、安全可靠的稳健API服务。
249 2
|
4月前
|
存储 数据可视化 Java
Java Stream API 的强大功能
Java Stream API 是 Java 8 引入的重要特性,它改变了集合数据的处理方式。通过声明式语法,开发者可以更简洁地进行过滤、映射、聚合等操作。Stream API 支持惰性求值和并行处理,提升了代码效率和可读性,是现代 Java 开发不可或缺的工具。
104 0
Java Stream API 的强大功能
|
5月前
|
安全 Java API
Java日期时间API:从Date到Java.time
本文深入解析了Java 8中引入的全新日期时间API,涵盖LocalDate、LocalTime、LocalDateTime、ZonedDateTime等核心类的使用,以及时间调整、格式化、时区处理和与旧API的互操作。通过实例对比,展示了新API在可变性、线程安全与易用性方面的显著优势,并提供迁移方案与实战技巧,助你掌握现代Java时间处理的最佳实践。
|
5月前
|
存储 NoSQL Java
Java Stream API:集合操作与并行处理
Stream API 是 Java 8 提供的集合处理工具,通过声明式编程简化数据操作。它支持链式调用、延迟执行和并行处理,能够高效实现过滤、转换、聚合等操作,提升代码可读性和性能。