前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python Elasticsearch API操作ES集群

Python Elasticsearch API操作ES集群

作者头像
三杯水Plus
发布2018-11-14 17:00:28
1.6K0
发布2018-11-14 17:00:28
举报
文章被收录于专栏:运维运维运维

环境

  • 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查询与聚合
  • Python 列表操作

代码

#!/usr/bin/env python
# -*- coding: utf-8 -*-
#minyt 2018.9.1
#获取24小时内出现的模块次数
# 该程序通过elasticsearch python client 获取相关精简数据,可以计算请求数、超时数、错误数、正确率、错误率等等
import MySQLdb
from elasticsearch import Elasticsearch
from 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上传数据到新的Index
def 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的次数除以域名总请求数对应各个域名的请求正确率
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018-09-02 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 环境
  • 知识点
  • 代码
  • 总结
相关产品与服务
Elasticsearch Service
腾讯云 Elasticsearch Service(ES)是云端全托管海量数据检索分析服务,拥有高性能自研内核,集成X-Pack。ES 支持通过自治索引、存算分离、集群巡检等特性轻松管理集群,也支持免运维、自动弹性、按需使用的 Serverless 模式。使用 ES 您可以高效构建信息检索、日志分析、运维监控等服务,它独特的向量检索还可助您构建基于语义、图像的AI深度应用。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档