El contenido no se encuentra disponible en el idioma seleccionado. Estamos trabajando continuamente para agregar más idiomas. Gracias por su apoyo.

Compute
Elastic Cloud Server
Huawei Cloud Flexus
Bare Metal Server
Auto Scaling
Image Management Service
Dedicated Host
FunctionGraph
Cloud Phone Host
Huawei Cloud EulerOS
Networking
Virtual Private Cloud
Elastic IP
Elastic Load Balance
NAT Gateway
Direct Connect
Virtual Private Network
VPC Endpoint
Cloud Connect
Enterprise Router
Enterprise Switch
Global Accelerator
Management & Governance
Cloud Eye
Identity and Access Management
Cloud Trace Service
Resource Formation Service
Tag Management Service
Log Tank Service
Config
OneAccess
Resource Access Manager
Simple Message Notification
Application Performance Management
Application Operations Management
Organizations
Optimization Advisor
IAM Identity Center
Cloud Operations Center
Resource Governance Center
Migration
Server Migration Service
Object Storage Migration Service
Cloud Data Migration
Migration Center
Cloud Ecosystem
KooGallery
Partner Center
User Support
My Account
Billing Center
Cost Center
Resource Center
Enterprise Management
Service Tickets
HUAWEI CLOUD (International) FAQs
ICP Filing
Support Plans
My Credentials
Customer Operation Capabilities
Partner Support Plans
Professional Services
Analytics
MapReduce Service
Data Lake Insight
CloudTable Service
Cloud Search Service
Data Lake Visualization
Data Ingestion Service
GaussDB(DWS)
DataArts Studio
Data Lake Factory
DataArts Lake Formation
IoT
IoT Device Access
Others
Product Pricing Details
System Permissions
Console Quick Start
Common FAQs
Instructions for Associating with a HUAWEI CLOUD Partner
Message Center
Security & Compliance
Security Technologies and Applications
Web Application Firewall
Host Security Service
Cloud Firewall
SecMaster
Anti-DDoS Service
Data Encryption Workshop
Database Security Service
Cloud Bastion Host
Data Security Center
Cloud Certificate Manager
Edge Security
Managed Threat Detection
Blockchain
Blockchain Service
Web3 Node Engine Service
Media Services
Media Processing Center
Video On Demand
Live
SparkRTC
MetaStudio
Storage
Object Storage Service
Elastic Volume Service
Cloud Backup and Recovery
Storage Disaster Recovery Service
Scalable File Service Turbo
Scalable File Service
Volume Backup Service
Cloud Server Backup Service
Data Express Service
Dedicated Distributed Storage Service
Containers
Cloud Container Engine
SoftWare Repository for Container
Application Service Mesh
Ubiquitous Cloud Native Service
Cloud Container Instance
Databases
Relational Database Service
Document Database Service
Data Admin Service
Data Replication Service
GeminiDB
GaussDB
Distributed Database Middleware
Database and Application Migration UGO
TaurusDB
Middleware
Distributed Cache Service
API Gateway
Distributed Message Service for Kafka
Distributed Message Service for RabbitMQ
Distributed Message Service for RocketMQ
Cloud Service Engine
Multi-Site High Availability Service
EventGrid
Dedicated Cloud
Dedicated Computing Cluster
Business Applications
Workspace
ROMA Connect
Message & SMS
Domain Name Service
Edge Data Center Management
Meeting
AI
Face Recognition Service
Graph Engine Service
Content Moderation
Image Recognition
Optical Character Recognition
ModelArts
ImageSearch
Conversational Bot Service
Speech Interaction Service
Huawei HiLens
Video Intelligent Analysis Service
Developer Tools
SDK Developer Guide
API Request Signing Guide
Terraform
Koo Command Line Interface
Content Delivery & Edge Computing
Content Delivery Network
Intelligent EdgeFabric
CloudPond
Intelligent EdgeCloud
Solutions
SAP Cloud
High Performance Computing
Developer Services
ServiceStage
CodeArts
CodeArts PerfTest
CodeArts Req
CodeArts Pipeline
CodeArts Build
CodeArts Deploy
CodeArts Artifact
CodeArts TestPlan
CodeArts Check
CodeArts Repo
Cloud Application Engine
MacroVerse aPaaS
KooMessage
KooPhone
KooDrive
On this page

Analyzing Hive Data

Updated on 2024-08-16 GMT+08:00

Function Description

This section describes how to use a sample program to complete an analysis task. The sample program provides the following methods:

  • Submitting a data analysis task by using JDBC APIs
  • Submitting a data analysis task by using HCatalog APIs

Sample Code

  • If you submit a data analysis task using Hive JDBC APIs, refer to JDBCExample.java in the sample program.
    1. Define HiveQL. HiveQL must be a single statement and cannot contain ";".
         // Define HiveQL, which cannot contain the semicolon (;).
         String[] sqls = {"CREATE TABLE IF NOT EXISTS employees_info(id INT,name STRING)", 
                  "SELECT COUNT(*) FROM employees_info", "DROP TABLE employees_info"}; 
    2. Build JDBC URL.
      // Build JDBC URL.
      StringBuilder sBuilder = new StringBuilder(
        "jdbc:hive2://").append(clientInfo.getZkQuorum()).append("/");
      
      if (isSecurityMode) {
          // Security mode
          // ZooKeeper login authentication
          sBuilder.append(";serviceDiscoveryMode=")
                  .append(clientInfo.getServiceDiscoveryMode())
                  .append(";zooKeeperNamespace=")
                  .append(clientInfo.getZooKeeperNamespace())
                  .append(";sasl.qop=")
                  .append(clientInfo.getSaslQop())
                  .append(";auth=")
                  .append(clientInfo.getAuth())
                  .append(";principal=")
                  .append(clientInfo.getPrincipal())
                  .append(";");
      } else {
          // Normal mode
          sBuilder.append(";serviceDiscoveryMode=")
                  .append(clientInfo.getServiceDiscoveryMode())
                  .append(";zooKeeperNamespace=")
                  .append(clientInfo.getZooKeeperNamespace())
                  .append(";auth=none");
      }
      String url = sBuilder.toString();

      The preceding operations are performed to access Hive through ZooKeeper. If you want to access Hive by directly connecting to HiveServer, perform the following operations to combine the JDBC URL and change the port of zk.quorum in the hiveclient.properties file to 10000.

      // Build JDBC URL.
      StringBuilder sBuilder = new StringBuilder(
        "jdbc:hive2://").append(clientInfo.getZkQuorum()).append("/");
      
      if (isSecurityMode) {
          // Security mode
          // ZooKeeper login authentication
          sBuilder.append(";sasl.qop=")
                  .append(clientInfo.getSaslQop())
                  .append(";auth=")
                  .append(clientInfo.getAuth())
                  .append(";principal=")
                  .append(clientInfo.getPrincipal())
                  .append(";");
      } else {
          // Normal mode
          sBuilder.append(";auth=none");
      }
      String url = sBuilder.toString();

      Note: When the HiveServer is directly connected, if the connected HiveServer is faulty, Hive access fails. If the ZooKeeper is used to access Hive, any available HiveServer instance can provide services properly. Therefore, you are advised to use ZooKeeper to access Hive when using JDBC.

    3. Load the Hive JDBC driver.
         // Load the Hive JDBC driver.
         Class.forName(HIVE_DRIVER);
    4. Enter a correct username, obtain the JDBC connection, confirm the HiveQL type (DDL/DML), call APIs to run HiveQL, return the queried column name and result to the console, and close the JDBC connection.
       
         Connection connection = null; 
           try { 
             // Obtain the JDBC connection.
             // If you set the second parameter to an incorrect username, the anonymous user will be used for login.
             connection = DriverManager.getConnection(url, "userName", ""); 
                
             // Create a table.
             // To import data to a table after the table is created, you can use the LOAD statement. For example, import data from HDFS to the table. 
             //load data inpath '/tmp/employees.txt' overwrite into table employees_info; 
             execDDL(connection,sqls[0]); 
             System.out.println("Create table success!"); 
               
             // Query
             execDML(connection,sqls[1]); 
                
             // Delete the table.
             execDDL(connection,sqls[2]); 
             System.out.println("Delete table success!"); 
           } 
           finally { 
             // Close the JDBC connection.
             if (null != connection) { 
               connection.close(); 
             } 
        
       public static void execDDL(Connection connection, String sql) 
         throws SQLException { 
           PreparedStatement statement = null; 
           try { 
             statement = connection.prepareStatement(sql); 
             statement.execute(); 
           } 
           finally { 
             if (null != statement) { 
               statement.close(); 
             } 
           } 
         } 
        
        
         public static void execDML(Connection connection, String sql) throws SQLException { 
           PreparedStatement statement = null; 
           ResultSet resultSet = null; 
           ResultSetMetaData resultMetaData = null; 
            
           try { 
             // Execute HiveQL.
             statement = connection.prepareStatement(sql); 
             resultSet = statement.executeQuery(); 
              
             // Output the queried column name to the console.
             resultMetaData = resultSet.getMetaData(); 
             int columnCount = resultMetaData.getColumnCount(); 
             for (int i = 1; i <= columnCount; i++) { 
               System.out.print(resultMetaData.getColumnLabel(i) + '\t'); 
             } 
             System.out.println(); 
              
             // Output the query result to the console.
             while (resultSet.next()) { 
               for (int i = 1; i <= columnCount; i++) { 
                 System.out.print(resultSet.getString(i) + '\t'); 
               } 
               System.out.println(); 
             } 
           } 
           finally { 
             if (null != resultSet) { 
               resultSet.close(); 
             } 
              
             if (null != statement) { 
               statement.close(); 
             } 
           } 
         }     
  • If you submit a data analysis task using HCatalog APIs, refer to HCatalogExample.java in the sample program.
    1. Compile the Map class to obtain data from a Hive table.
         public static class Map extends
                  Mapper<LongWritable, HCatRecord, IntWritable, IntWritable> {
              int age;
              @Override
              protected void map(
                      LongWritable key,
                      HCatRecord value,
                      Context context)
                      throws IOException, InterruptedException {
                  age = (Integer) value.get(0);
                  context.write(new IntWritable(age), new IntWritable(1));
              }
          }     
    2. Compile the Reduce class to collect statistics on data read from the Hive table.
          public static class Reduce extends Reducer<IntWritable, IntWritable,
          IntWritable, HCatRecord> {
            @Override
            protected void reduce(
                    IntWritable key,
                    Iterable<IntWritable> values,
                    Context context)
                    throws IOException, InterruptedException {
                int sum = 0;
                Iterator<IntWritable> iter = values.iterator();
                while (iter.hasNext()) {
                    sum++;
                    iter.next();
                }
                HCatRecord record = new DefaultHCatRecord(2);
                record.set(0, key.get());
                record.set(1, sum);
      
                context.write(null, record);
              }
          } 
    3. After configuring the job in the run() method, execute the main() method to submit a task.
          public int run(String[] args) throws Exception {
            
              HiveConf.setLoadMetastoreConfig(true);
              Configuration conf = getConf();
              String[] otherArgs = args;
              
              String inputTableName = otherArgs[0];
              String outputTableName = otherArgs[1];
              String dbName = "default";
      
              @SuppressWarnings("deprecation")
              Job job = new Job(conf, "GroupByDemo");
              
              HCatInputFormat.setInput(job, dbName, inputTableName);
              job.setInputFormatClass(HCatInputFormat.class);
              job.setJarByClass(HCatalogExample.class);
              job.setMapperClass(Map.class);
              job.setReducerClass(Reduce.class);
              job.setMapOutputKeyClass(IntWritable.class);
              job.setMapOutputValueClass(IntWritable.class);
              job.setOutputKeyClass(WritableComparable.class);
              job.setOutputValueClass(DefaultHCatRecord.class);
              
              OutputJobInfo outputjobInfo = OutputJobInfo.create(dbName,outputTableName, null);
              HCatOutputFormat.setOutput(job, outputjobInfo);
              HCatSchema schema = outputjobInfo.getOutputSchema();
              HCatOutputFormat.setSchema(job, schema);
              job.setOutputFormatClass(HCatOutputFormat.class);
              
              return (job.waitForCompletion(true) ? 0 : 1);
          }
          public static void main(String[] args) throws Exception {
              int exitCode = ToolRunner.run(new HCatalogExample(), args);
              System.exit(exitCode);
          }

Utilizamos cookies para mejorar nuestro sitio y tu experiencia. Al continuar navegando en nuestro sitio, tú aceptas nuestra política de cookies. Descubre más

Feedback

Feedback

Feedback

0/500

Selected Content

Submit selected content with the feedback