起因
filebeat采集nginx的日志,以json格式解析後傳入elasticsearch,全部字段都是text格式,我們需要把request_time變成double格式才能使用聚合搜尋request_time的最大值.
但是elasticsearch的index一旦建立好之後,字段隻能新增,不能修改,是以要修改request_time的資料類型,隻能重建索引。
我們的步驟是:1.獲得老索引的mapping資訊,2.用這個mapping資訊建立一個索引 3.用reindex方法,把老索引的資料遷移到新索引 4.确認新索引資料遷移成功,5.删除老索引 6.獲得出新索引的mapping,7.使用新索引的mapping建立老索引。8.把新索引的資料倒回老索引 9.删除老索引
假設老索引:V1
臨時索引:V2
nginx統計接口路徑:path字段
nginx統計響應時間:request_time字段
流程圖與說明

python代碼
根據path,聚合查詢出響應最大時間和平均時間,保留最大響應時間前500個到csv檔案裡
#
# created by zhenwei.Li at 2020/11/3 17:50
#
# filename : example4.py
# description :
import csv
import json
import requests
if __name__ == '__main__':
send_json = {
"query": {
"bool": {
"must": [
{
"range": {
"@timestamp": {
"gte": 1533556800000,
"lte": 1604470685934
}
}
}
]
}
},
"size": 0,
"aggs": {
"Job_gender_stats": {
"terms": {
"field": "path.keyword",
"size": 500,
"order": {
"max_request_time": "desc"
}
},
"aggs": {
"max_request_time": {
"max": {
"field": "request_time"
}
},
"avg_request_time": {
"avg": {
"field": "request_time"
}
}
}
}
}
}
res = requests.post(url="http://192.168.0.174:32164/192.168.0.67-eiop-frontend/_search", json=send_json)
print(json.dumps(res.json()['aggregations']['Job_gender_stats']['buckets'], sort_keys=True, indent=4))
buckets = res.json()['aggregations']['Job_gender_stats']['buckets']
file_handle = open('research.csv', 'w', encoding='utf-8', newline='' "")
# 2. 基于檔案對象建構 csv寫入對象
csv_writer = csv.writer(file_handle)
# 3. 建構清單頭
csv_writer.writerow(["路徑", "出現次數", "平均響應時間(秒)", "最大響應時間(秒)"])
for item in buckets:
csv_writer.writerow(
[item['key'], item['doc_count'], item['avg_request_time']['value'], item['max_request_time']['value']])
# 5. 關閉檔案
file_handle.close()