【问题标题】:Create table in HIVE using column names from file使用文件中的列名在 HIVE 中创建表
【发布时间】:2020-06-12 19:38:08
【问题描述】:

我目前有一些 HIVE 代码可以创建一个表,我在其中声明所有列名和类型。然后我使用“加载数据路径”将 CSV 加载到该表中,这样我就可以加入我的数据库表。问题在于有时 CSV 列的顺序可能不同。我无法控制它,因为它是从不同的来源发送给我的。我想知道是否有一种方法可以创建我每天所做的临时表而不声明列名,只允许它从 CSV 中读取。这样我就不必每天早上手动查看文件以检查列的顺序是否正确?

【问题讨论】:

    标签: csv hive


    【解决方案1】:

    由于列顺序不断变化,作为第一步,您可以使用 shell 脚本读取标题列并为临时表生成 create table 脚本。此后,执行生成的创建表字符串和load 文件到临时表中。从临时表中,您可以将其加载到目标表中。

    一个示例 bash 脚本,为您提供一个想法。

    #!/bin/bash
    
    #File check
    if [ -s "$1" ]
    then echo "File $1 exists and is non-empty"
    else
    echo "File $1 does not exist or is empty"
    fi
    
    create_tbl_cmd="create table tblname ("    
    #Get fields from file header
    fields=`head -1 $1`    
    #add string as the datatype for each field
    fields="${fields//,/ string,} string)"
    create_table_cmd="$create_tbl_cmd$fields"
    #echo $create_table_cmd
    
    #Execute the $create_table_cmd using Beeline or Hive command line invoking the necessary command
    
    #Execute the Load into temp table
    
    #Execute the Insert from temp table to target table 
    

    使用 csv 文件参数执行上面的 bash 脚本

    bash scriptname.sh filename.csv
    

    【讨论】:

    • 目前,我们有一个用于访问和运行查询的终端,它类似于 microsoft SQL 或 TD SQL。所以我不使用任何命令行或类似的东西来运行查询。像这样的东西可以在这些结构中工作还是只在 putty 中运行的 shell 脚本(我在需要时用来访问服务器的接口)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-30
    • 2017-09-24
    • 1970-01-01
    • 2022-10-02
    相关资源
    最近更新 更多