1. 程式人生 > >es-hadoop-hive 時間格式問題記錄

es-hadoop-hive 時間格式問題記錄

使用 es-hive 同步資料,插入 hive 表即插入 es,讀取 hive 表資料即讀取 es 資料 建立 es-hive 測試表
drop TABLE IF EXISTS `es_dim_s.es_test_time`;
CREATE TABLE IF NOT EXISTS `es_dim_s.es_test_time` (
  `service_date` STRING comment 'yyyy-MM-dd',
  `service_date_time` STRING comment 'yyyy-MM-ddTHH:mm:ss'
)
comment '時間測試'
STORED BY 'org.elasticsearch.hadoop.hive.EsStorageHandler'
TBLPROPERTIES(
'es.nodes' = 'es1:9201,es2:9202,es2:9203',
'es.index.auto.create' = 'true',
'es.resource' = 'bi_m_sbkcq_test-{service_date:YYYY.MM}/es_test_time',
'es.index.read.missing.as.empty' = 'true',
'es.batch.size.bytes' = '10mb',
'es.batch.size.entries' = '3000',
'es.mapping.names' = '');
如果 hive 中時間型別指定為 date ,對於 yyyy-MM-dd 型別的資料會預設新增時區 例如自動變為 2017-05-04+08:00

插入測試資料
>hive
insert into table es_dim_s.es_test_time  select '2016-10-01','2016-10-01 10:00:00’;


執行後報錯 hive 客戶端報錯
找到 es-hadoop 原始碼中報錯位置line:105

報錯原因分析 es-hadoop jar 預設使用 ISO 進行時間格式化,2016-10-01 10:00:00 不屬於 ISO標準,預設改寫為 2016-10-01T10:00:00 格式進行 datetime 型別資料插入
修改匯入Hive測試語句的 date-time 格式為 ISO 標準格式即可正確匯入 hive-es 重新執行匯入操作即可成功
>hive
insert into table es_dim_s.es_test_time  select '2016-10-01','2016-10-01T10:00:00’;


es 時間欄位動態 mapping-template 如下
"dynamic_templates": [
        {
          "date_fields": {
            "match": "*_date",
            "mapping": {
              "type": "date"
            }
          }
        },
        {
          "time_fields": {
            "match": "*_time",
            "mapping": {
              "type": "date"
            }
          }
        },


date 不指定 format,指定具體 format 後es 客戶端會丟擲錯誤 Caused by: java.lang.IllegalArgumentException: Invalid format: [yyyy-MM-ddTHH:mm:ss]: Illegal pattern component: T hive 時間格式轉換
select from_unixtime(unix_timestamp("2014-11-10 08:00:00","yyyy-MM-dd HH:mm:ss"),"yyyy-MM-dd'T'HH:mm:ss") as a from es_dim_sbkcq.es_third_relation;


2014-11-10 和 20141110相互轉化的辦法:
#from_unixtime && unix_timestamp
-- 20141110
select from_unixtime(unix_timestamp('2014-11-10','yyyy-mm-dd'),'yyyymmdd') from default.dual;
-- 2014-11-10
select from_unixtime(unix_timestamp('20141110','yyyymmdd'),'yyyy-mm-dd') from default.dual;
#substr + concat
-- 20141110
select concat(substr('2014-11-10',1,4),substr('2014-11-10',6,2),substr('2014-11-10',9,2)) from default.dual;
-- 2014-11-10
select concat(substr('20141110',1,4),'-',substr('20141110',5,2),'-',substr('20141110',7,2)) from default.dual;

hive 獲取當前時間
select from_unixtime(unix_timestamp(),"yyyy-MM-dd'T'HH:mm:ss") from es_dim_sbkcq.es_third_relation;



ISO時間格式探索 - 相關乾貨