Python Elasticsearch API操作ES叢集

來源:互聯網
上載者:User

標籤:cal   cse   網域名稱   clu   utf-8   sea   資料   desc   connect   

環境
  • Centos 7.4
  • Python 2.7
  • Pip 2.7 MySQL-python 1.2.5 Elasticsearc 6.3.1
  • Elasitcsearch6.3.2
知識點
  • 調用Python Elasticsearh API
  • Python Mysqldb使用
  • DSL查詢與彙總
  • Pyehon 列表操作
代碼
#!/usr/bin/env python# -*- coding: utf-8 -*-#minyt 2018.9.1#擷取24小時內出現的模組次數# 該程式通過elasticsearch python client 擷取相關精簡資料,可以計算請求數、逾時數、錯誤數、正確率、錯誤率等等import MySQLdbfrom elasticsearch import Elasticsearchfrom elasticsearch import helpers#定義elasticsearch叢集索引名index_name = "logstash-nginxlog-*"#執行個體化Elasticsearch類,並設定逾時間為180秒,預設是10秒的,如果資料量很大,時間設定更長一些es = Elasticsearch([‘elasticsearch01‘,‘elasticsearch02‘,‘elasticsearch03‘],timeout=180)#DSL(領特定領域語言)查詢文法,查詢top50 sname的排列次數data_sname = {  "aggs": {    "2": {      "terms": {        "field": "apistatus.sname.keyword",        "size": 100,        "order": {          "_count": "desc"        }      }    }  },  "size": 0,  "_source": {    "excludes": []  },  "stored_fields": [    "*"  ],  "script_fields": {},  "docvalue_fields": [    "@timestamp"  ],  "query": {    "bool": {      "must": [        {          "match_all": {}        },        {          "range": {            "@timestamp": {              "gte" : "now-24h/h",              "lt" :  "now/h"            }          }        }      ],      "filter": [],      "should": [],      "must_not": []    }  }}#按照DSL(特定領域語言)文法查詢擷取資料def get_original_data():    try:        #根據上麵條件搜尋資料        res = es.search(            index=index_name,            size=0,            body=data_sname        )        return res    except:        print "get original data failure"#初始化資料庫def init_mysql():    # 開啟資料庫連接    db = MySQLdb.connect("localhost", "myuser", "mypassword", "mydb", charset=‘utf8‘ )    # 使用cursor()方法擷取操作遊標     cursor = db.cursor()    # SQL 更新語句    sql = "update appname set count=0"    try:        # 執行SQL語句        cursor.execute(sql)        # 提交到資料庫執行        db.commit()    except:        # 發生錯誤時復原        db.rollback()    # 關閉資料庫連接    db.close()def updata_mysql(sname_count,sname_list):    # 開啟資料庫連接       db = MySQLdb.connect("localhost", "myuser", "mypassword", "mydb", charset=‘utf8‘ )    # 使用cursor()方法擷取操作遊標     cursor = db.cursor()    # SQL 更新語句    sql = "update appname set count=%d where sname = ‘%s‘" % (sname_count,sname_list)    try:        # 執行SQL語句        cursor.execute(sql)        # 提交到資料庫執行        db.commit()    except:        # 發生錯誤時復原        db.rollback()    # 關閉資料庫連接    db.close()#根據Index資料結構通過Elasticsearch Python Client上傳資料到新的Indexdef import_process_data():    try:        #列表形式顯示結果        res = get_original_data()        #print res        res_list = res.get(‘aggregations‘).get(‘2‘).get(‘buckets‘)        #print res_list        #初始化資料庫        init_mysql()        #擷取24小時內出現的SNAME         for value in res_list:            sname_list = value.get(‘key‘)            sname_count = value.get(‘doc_count‘)            print sname_list,sname_count            #更新sname_status值            updata_mysql(sname_count,sname_list)    except Exception, e:        print repr(e)if __name__ == "__main__":    import_process_data()
總結

關鍵是DSL文法的編寫涉及查詢與彙總可以通過kibana的visualize或者devtool先測試出正確文法,然後結合python對列表、字典、除法、字串等操作即可。下面匯總下各個演算法:

  • 總請求
    http_host.keyword: api.mydomain.com

  • 超長請求
    http_host.keyword: api.mydomain.com AND request_time: [1 TO 600] NOT apistatus.status.keyword:*錯誤

  • 錯誤請求
    apistatus.status.keyword:*錯誤 AND (http_host.keyword: api.mydomain.com OR http_host.keyword: api.yourdomain.com )

  • 請求健康度
    網域名稱與request_time彙總,網域名稱請求時間小於3秒的次數除以總請求次數對應各個網域名稱健康度

  • 請求正確率
    網域名稱與http狀態代碼彙總,網域名稱http狀態代碼為200的次數除以網域名稱總請求數對應各個網域名稱的請求正確率

Python Elasticsearch API操作ES叢集

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.