Es基礎數據類型

string 字符串類型,es中最常用的類型,官方文檔 比較重要的參數: index分析 analyzed(默認) not_analyzed no store存儲 true 獨立存儲 false(默認)不存儲,從_source中解析 Numeric 數值類型,注意numeric並不是一個類型,它包括多種類型,比如:long,integer,short,byte,double,float,每種的存儲空間都是不一樣的,一般默認推薦integer和float。官方文檔參考 重要的參數: index分析 not_analyzed(默認) ,設置為該值可以保證該字段能通過檢索查詢到 no store存儲 true 獨立存儲 false(默認)不存儲,從_source中解析 date 日期類型,該類型可以接受一些常見的日期表達方式,官方文檔參考。 重要的參數: index分析 not_analyzed(默認) ,設置為該值可以保證該字段能通過檢索查詢到 no store存儲 true 獨立存儲 false(默認)不存儲,從_source中解析 format格式化 strict_date_optional_time||epoch_millis(默認) 你也可以自定義格式化內容,比如 "date": { "type": "date", "format": "yyy-MM-dd HH:mm:ss||yyyy-MM-dd||epoch_millis" } 更多的時間表達式可以參考這里 IP 這個類型可以用來標識IPV4的地址,參考官方文檔 常用參數: index分析 not_analyzed(默認) ,設置為該值可以保證該字段能通過檢索查詢到 no store存儲 true 獨立存儲 false(默認)不存儲,從_source中解析 boolean 布爾類型,所有的類型都可以標識布爾類型,參考官方文檔 False: 表示該值的有:false, "false", "off", "no", "0", "" (empty string), 0, 0.0 True: 所有非False的都是true 重要的參數: index分析 not_analyzed(默認) ,設置為該值可以保證該字段能通過檢索查詢到 no store存儲 true 獨立存儲 false(默認)不存儲,從_source中解析
Es的head插件使用
1.查看集群中的索引信息和查看索引中定義的列的類型
2.查看es是如何對某個字符串進行切分的
Es對Date類型的處理
es如何存儲Date類型,它最終的輸出方式都是以字符串輸出,只是默認的格式是:1970-01-01T00:00:00Z
,也就是默認的 UTC
格式
所以我們在查詢和添加時間類型數據的時候需要把格式手動轉換成UTC格式 否則會出現時間格式轉換異常
異常查詢示例:
正常查詢示例:
Es查詢條件設置

body = { "query": { "filtered": { "filter": { "bool":{ "must": [ //must數組中的三個條件必須同時滿足 {"term":{"jylsh": jylsh}}, { "range": { "@timestamp": { "gte": tools.strtime_to_timestamp(startTime), "lte": tools.strtime_to_timestamp(endTime) } } }, { "bool": { "should": [ //should數組中的條件至少需要滿足一個 {"match": {"message": "SERVICE_LOG"}}, {"match": {"message": "ENTRANCE_LOG"}} ] } } ] } } } }, "sort": sort_dict }
Es查詢代碼示例
1.需要把時間轉換成unix格式的13位數的時間戳字符 精確到毫秒級

#格式化日期字符串 def formatDate(self,timestr): timeStruct = time.strptime(timestr, "%Y-%m-%d %H:%M:%S.%f") strTime = time.strftime("%Y-%m-%d %H:%M:%S", timeStruct) return strTime import time t = "2017-11-24 17:30:00" #將其轉換為時間數組 timeStruct = time.strptime(t, "%Y-%m-%d %H:%M:%S") #轉換為時間戳: timeStamp = int(time.mktime(timeStruct)) print(timeStamp)

#!/usr/bin/env python # -*- coding: utf-8 -*- from elasticsearch import Elasticsearch import time,datetime ####動態修改配置項目############ es = Elasticsearch("http://127.0.0.1:9200") appname="dzgzpt-wsys" userChoiceTime_start="2019-04-05 09:27:27.820" userChoiceTime_end="2019-06-27 09:27:41.986" #東八區時間 nowtime=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3] #計算15分鍾前的時間 fifteenminAgo=(datetime.datetime.now()+datetime.timedelta(minutes=-15)).strftime("%Y-%m-%d %H:%M:%S.%f")[:-3] #計算1個小時前的時間 hourAgo=(datetime.datetime.now()+datetime.timedelta(hours=-1)).strftime("%Y-%m-%d %H:%M:%S.%f")[:-3] #計算1天前的時間 dayAgo=(datetime.datetime.now()+datetime.timedelta(days=-1)).strftime("%Y-%m-%d %H:%M:%S.%f")[:-3] def strtime_to_datetime(timestr): """將字符串格式的時間 (含毫秒) 轉為 datetime 格式 :param timestr: {str}'2016-02-25 20:21:04.242' :return: {datetime}2016-02-25 20:21:04.242000 """ local_datetime = datetime.datetime.strptime(timestr, "%Y-%m-%d %H:%M:%S.%f") return local_datetime def datetime_to_timestamp(datetime_obj): """將本地(local) datetime 格式的時間 (含毫秒) 轉為毫秒時間戳 :param datetime_obj: {datetime}2016-02-25 20:21:04.242000 :return: 13 位的毫秒時間戳 1456402864242 """ local_timestamp = int(time.mktime(datetime_obj.timetuple()) * 1000.0 + datetime_obj.microsecond / 1000.0) return local_timestamp def strtime_to_timestamp(local_timestr): """將本地時間 (字符串格式,含毫秒) 轉為 13 位整數的毫秒時間戳 :param local_timestr: {str}'2016-02-25 20:21:04.242' :return: 1456402864242 """ local_datetime = strtime_to_datetime(local_timestr) timestamp = datetime_to_timestamp(local_datetime) return timestamp def set_interval(startTime,endTime): d1 = datetime.datetime.strptime(startTime, "%Y-%m-%d %H:%M:%S.%f") d2 = datetime.datetime.strptime(endTime, "%Y-%m-%d %H:%M:%S.%f") n_days = d2 - d1 days = n_days.days year = days // 365 month = days % 365 // 30 seconds = n_days.seconds mins = seconds // 60 hours = mins // 60 if year >=1: return "1M" elif month == 1: return "12h" elif month > 1: return "1d" elif days == 1: return "30m" elif days >=2 and days <=4: return "1h" elif days >= 5 and days <=12: return "3h" elif days >=13 and days <= 30: return "12h" elif hours == 1 or hours ==2: return "1m" elif hours >=3 and hours<5: return "3m" elif hours >=5 and hours<10: return "5m" elif hours >=10 and hours<=60: return "10m" elif mins>=1 and mins<=30: return "30s" elif mins>30 and mins <=60: return "1m" def search_qps(startTime,endTime): interval=set_interval(startTime,endTime) print("interval設置為 %s" %(interval)) print("開始qps時間%s" %(startTime)) print("結束qps時間%s " %(endTime)) body={ "size": 0, "query": { "filtered": { "query": { "query_string": { "analyze_wildcard": True, "query": "appname:"+appname } }, "filter": { "bool": { "must": [ { "range": { "@timestamp": { "gte": strtime_to_timestamp(startTime), "lte": strtime_to_timestamp(endTime) } } } ] } } } }, "aggs": { "res": { "date_histogram": { "field": "@timestamp", "interval": "%s" %(interval), "time_zone": "Asia/Shanghai", "min_doc_count": 0, "extended_bounds": { "min": strtime_to_timestamp(startTime), "max": strtime_to_timestamp(endTime) } } } } } res=es.search(body=body) print(res) print("查詢到qps總條數: %s" %(len(res["aggregations"]["res"]["buckets"]))) def search_wastetime(startTime,endTime): print("開始延遲時間%s" % (startTime)) print("結束延遲時間%s " % (endTime)) body = { "size": 0, "query": { "filtered": { "query": { "query_string": { "analyze_wildcard": True, "query": "appname:" + appname } }, "filter": { "bool": { "must": [ { "range": { "@timestamp": { "gte": strtime_to_timestamp(startTime), "lte": strtime_to_timestamp(endTime) } } } ] } } } }, "aggs": { "avg_wastetime": { "avg": { "field": "waste_time" } } } } res=es.search(body=body) print(res) def search_abnormal(startTime,endTime): print("開始異常統計時間%s" % (startTime)) print("結束異常統計時間%s " % (endTime)) body = { "size": 0, "query": { "filtered": { "query": { "query_string": { "analyze_wildcard": True, "query": "appname:" + appname } }, "filter": { "bool": { "must": [ { "range": { "@timestamp": { "gte": strtime_to_timestamp(startTime), "lte": strtime_to_timestamp(endTime) } } } ] } } } }, "aggs": { "res": { "terms": { "field": "success" } } } } res=es.search(body=body) reslist=res["aggregations"]["res"]["buckets"] for re in reslist: if re["key"] == "false": print("統計到的異常數 %s" %(re["doc_count"])) print("---------------------15分鍾內的qps總數-------------------") search_qps(fifteenminAgo,nowtime) print("-------------------用戶設置時間段的qps總數------------------------") search_qps(userChoiceTime_start,userChoiceTime_end) print("*******************************************************************") print("---------------------15分鍾內的延遲平均值-------------------") search_wastetime(fifteenminAgo,nowtime) print("-------------------用戶設置時間段的延遲平均值------------------------") search_wastetime(userChoiceTime_start,userChoiceTime_end) print("*******************************************************************") print("---------------------15分鍾內的異常數-------------------") search_abnormal(fifteenminAgo,nowtime) print("-------------------用戶設置時間段的異常數------------------------") search_abnormal(userChoiceTime_start,userChoiceTime_end)

def search_test(): body={ "query" : { "constant_score" : { "filter" : { "range" : { "@timestamp":{ "gt": "now-3m" } } } } } } res=es.search(body=body) print(res) import time, datetime def timeToZtime(time): myTime = datetime.datetime.strptime(time, "%Y-%m-%d %H:%M:%S") return myTime.strftime("%Y-%m-%dT%H:%M:%S.%fZ") def search_test2(): body={ "query" : { "constant_score" : { "filter" : { "range" : { "@timestamp":{ "gt": timeToZtime("2019-01-13 12:10:30"), "lt": timeToZtime("2019-01-13 12:10:30")+"||+1M" } } } } } } res=es.search(body=body) print(res) search_test2()

import time, datetime def strtime_to_datetime(timestr): """將字符串格式的時間 (含毫秒) 轉為 datetime 格式 :param timestr: {str}'2016-02-25 20:21:04.242' :return: {datetime}2016-02-25 20:21:04.242000 """ local_datetime = datetime.datetime.strptime(timestr, "%Y-%m-%d %H:%M:%S.%f") return local_datetime def datetime_to_timestamp(datetime_obj): """將本地(local) datetime 格式的時間 (含毫秒) 轉為毫秒時間戳 :param datetime_obj: {datetime}2016-02-25 20:21:04.242000 :return: 13 位的毫秒時間戳 1456402864242 """ local_timestamp = int(time.mktime(datetime_obj.timetuple()) * 1000.0 + datetime_obj.microsecond / 1000.0) return local_timestamp def strtime_to_timestamp(local_timestr): """將本地時間 (字符串格式,含毫秒) 轉為 13 位整數的毫秒時間戳 :param local_timestr: {str}'2016-02-25 20:21:04.242' :return: 1456402864242 """ local_datetime = strtime_to_datetime(local_timestr) timestamp = datetime_to_timestamp(local_datetime) return timestamp #調用api處理時間 def search_qps_avg(): body2={ "size": 0, "query": { "filtered": { "query": { "query_string": { "analyze_wildcard": True, "query": "appname:dzgzpt-wsys" } }, "filter": { "bool": { "must": [ { "range": { "@timestamp": { "gte": strtime_to_timestamp("2019-04-05 09:27:27.820"), "lte": strtime_to_timestamp("2019-04-18 09:34:41.986") } } } ] } } } }, "aggs": { "2": { "date_histogram": { "field": "@timestamp", "interval": "12h", "time_zone": "Asia/Shanghai", "min_doc_count": 1, "extended_bounds": { "min": strtime_to_timestamp("2019-04-05 09:27:27.820"), "max": strtime_to_timestamp("2019-04-18 09:34:41.986") } } } } } body1 = { "size": 0, "query": { "filtered": { "query": { "query_string": { "analyze_wildcard": 'true', "query": "appname:dzgzpt-wsys" } }, "filter": { "bool": { "must": [ { "range": { "@timestamp": { "gte": 1554427647820, "lte": 1555551281986, "format": "epoch_millis" } } } ], "must_not": [] } } } }, "aggs": { "2": { "date_histogram": { "field": "@timestamp", "interval": "12h", "time_zone": "Asia/Shanghai", "min_doc_count": 1, "extended_bounds": { "min": 1554427647820, "max": 1555551281986 } } } } } res=es.search(body=body2) print(res) search_qps_avg()

#unix的utc標准時間 print(datetime.datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]) #東八區時間 print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]) #計算15分鍾后的時間 print((datetime.datetime.now()+datetime.timedelta(minutes=15)).strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]) #計算15分鍾前的時間 print((datetime.datetime.now()+datetime.timedelta(minutes=-15)).strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]) #計算一天后的時間 print((datetime.datetime.now()+datetime.timedelta(days=1)).strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]) #計算1個小時后的時間 print((datetime.datetime.now()+datetime.timedelta(hours=1)).strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]) 2019-06-04 05:37:41.564 2019-06-04 13:37:41.564 2019-06-04 13:52:41.564 2019-06-04 13:22:41.564 2019-06-05 13:37:41.564 2019-06-04 14:37:41.564

import datetime d1 = datetime.datetime.strptime("2019-06-27 09:27:27.820", "%Y-%m-%d %H:%M:%S.%f") d2 = datetime.datetime.strptime("2021-07-29 15:43:41.986", "%Y-%m-%d %H:%M:%S.%f") n_days = d2 - d1 print("------------計算時分秒-----------------") seconds = n_days.seconds print("相差秒數: %s" %(seconds)) mins = seconds // 60 print("相差分鍾數: %s" %(mins)) hours = mins // 60 print("相差小時數: %s" %(hours)) print("-------------計算年月日---------------------") days=n_days.days print("相差天數: %s" %(days)) month= days%365//30 print("相差月數: %s" %(month)) year = days // 365 print("相差年數: %s" %(year))