pythonsearch结果_python 查询Elasticsearch的小例子

#!/usr/bin/env python

# -*- coding: utf-8 -*-

from sfo_common.agent import Agent

from sfo_common.import_common import *

class ElkLog(object):

"""

处理ELK数据类

"""

def __init__(self):

pass

def get_elk_log_json(self):

"""

通过调用elasticsearch接口查询指定索引数据,计算集群的平均响应时间

:return:

"""

try:

day = time.strftime("%Y.%m.%d",time.localtime(time.time()))

clusters = config.elk_index_name.split(',')

if clusters:

for cluster in clusters:

index_name="{}-swift-proxy-{}".format(cluster,day)

req_url = '{}{}/_search?pretty'.format(config.elk_server_url,index_name)

headers = {'content-type': "application/json"}

l_time = datetime.datetime.now() + datetime.timedelta(minutes=-5)

now_time = util.local2utc(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f'))

now_time_5m = util.local2utc(l_time.strftime('%Y-%m-%d %H:%M:%S.%f'))

body = {

"query": {

"bool":{

"must":{

"match_all":{}

},

"filter":{

"range":{

"@timestamp":{

"gte":now_time_5m,

"lte":now_time

}

}

}

}

},

"size": 10000,

"sort": {

"@timestamp": { "order": "asc" }

},

"_source": ["status", "method","client_ip","remote_ip","timestamp","request_time","@timestamp"]

}

#print req_url,body,headers

response = requests.post(req_url,data=json.dumps(body),headers=headers)

total_time=head_total_time=get_total_time=put_total_time=post_total_time=delete_total_time = 0.0

head_count=get_count=put_count=post_count=delete_count = 0

if response.status_code == 200:

tps = SfoClusterTps()

res_data = json.loads(response.text,encoding='UTF-8')

if res_data and res_data.has_key('hits'):

hits = res_data['hits']

total = hits['total']

list = hits['hits']

if list and total > 0:

for obj in list:

if isinstance(obj,dict) and obj.has_key('_source'):

source = obj['_source']

if source.has_key('request_time'):

total_time += float(source['request_time'])

if source.has_key('method') and str(source['method']).strip().upper()=='HEAD':

head_count += 1

if source.has_key('request_time'):

head_total_time += float(source['request_time'])

if source.has_key('method') and str(source['method']).strip().upper()=='GET':

get_count += 1

if source.has_key('request_time'):

get_total_time += float(source['request_time'])

if source.has_key('method') and str(source['method']).strip().upper()=='PUT':

put_count += 1

if source.has_key('request_time'):

put_total_time += float(source['request_time'])

if source.has_key('method') and str(source['method']).strip().upper()=='POST':

post_count += 1

if source.has_key('request_time'):

post_total_time += float(source['request_time'])

if source.has_key('method') and str(source['method']).strip().upper()=='DELETE':

delete_count += 1

if source.has_key('request_time'):

delete_total_time += float(source['request_time'])

tps.guid = str(uuid.uuid1())

tps.cluster_name = cluster

if total > 0:

tps.avg_time = '%.2f'%(total_time/total*1000)

else:

tps.avg_time = 0

if head_count > 0:

tps.head_time = '%.2f'%(head_total_time/head_count*1000)

else:

tps.head_time = 0

if get_count > 0:

tps.get_time = '%.2f'%(get_total_time/get_count*1000)

else:

tps.get_time = 0

if put_count > 0:

tps.put_time = '%.2f'%(put_total_time/put_count*1000)

else:

tps.put_time = 0

if post_count > 0:

tps.post_time = '%.2f'%(post_total_time/post_count*1000)

else:

tps.post_time = 0

if delete_count > 0:

tps.delete_time = '%.2f'%(delete_total_time/delete_count*1000)

else:

tps.delete_time = 0

tps.add_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))

db.session.add(tps)

db.session.commit()

else:

pass

else:

pass

else:

pass

except Exception as ex:

logger.exception("get_elk_log_json function execute exception:" + str(ex))

finally:

db.session.close()

db.session.remove()

#schedule tasks

def get_elklog_json_schl(executor):

"""

起线程执行日志分析

:param executor:

:return:

"""

try:

el = ElkLog()

executor.submit(el.get_elk_log_json)

#threading.Thread(target=el.get_elk_log_json).start()

except Exception as ex:

logger.exception("get_elklog_json_schl function execute exception:" + str(ex))

class ElklogUnitAgnet(Agent):

def __init__(self, pidfile):

Agent.__init__(self, pidfile)

def run(self):

try:

sys.stdout.flush()

hostname = socket.getfqdn()

hostip = socket.gethostbyname(hostname)

logger.info("hostname is {}, ip is {}".format(hostname, hostip))

#use schedule

with ThreadPoolExecutor(config.thread_workers) as executor:

schedule.every(config.upload_refresh).seconds.do(get_elklog_json_schl,executor)

schedule.run_all(0)

while True:

schedule.run_pending()

time.sleep(0.1)

except Exception as ex:

logger.exception("elk log agent run exception:" + str(ex))

def main():

agent = ElklogUnitAgnet(config.elklog_agnet_pfile)

try:

if len(sys.argv) == 3:

if 'elklog' == sys.argv[1]:

if 'start' == sys.argv[2]:

agent.start()

if 'stop' == sys.argv[2]:

agent.stop()

else:

print("Unknown command")

sys.exit(2)

else:

print("usage: %s" % (sys.argv[0],))

sys.exit(2)

except Exception as ex:

logger.exception("elk log process run exception:" + str(ex))

if __name__ == '__main__':

main()

###########################################################################################

更多查询方式接口:

查询一条记录

curl -H "Content-Type: application/json" -X POST 'http://192.168.1.1:9200/swift-nginx-2018.08.31/_search?pretty' -d '{"query": { "match_all": {} },"size": 1}'

查询offset为20的记录

curl -H "Content-Type: application/json" -X POST 'http://192.168.1.1:9200/swift-nginx-2018.08.31/_search?pretty' -d '{"query": { "match": { "offset": 20 } }}'

查询结果只返回指定的字段

curl -H "Content-Type: application/json" -X POST 'http://192.168.1.1:9200/swift-nginx-2018.08.31/_search?pretty' -d '{"query": { "match_all": {} },"_source": ["host", "message"]}'

查询结果排序

curl -H "Content-Type: application/json" -X POST 'http://192.168.1.1:9200/swift-nginx-2018.08.31/_search?pretty' -d '{"query": { "match_all": {} },"_source": ["offset","host", "message"]},"sort": { "offset": { "order": "desc" } }'

返回从10开始的10条记录

curl -H "Content-Type: application/json" -X POST 'http://192.168.1.1:9200/swift-nginx-2018.08.31/_search?pretty' -d '{"query": { "match_all": {} },"from": 10,"size": 10,"_source": ["offset","host", "message"]},"sort": { "offset": { "order": "desc" } }'

集群健康状态查询:

curl '192.168.1.1:9200/_cat/health?v'

查询索引列表:

curl '192.168.1.1:9200/_cat/indices?v'

查询集群节点列表:

curl '192.168.1.1:9200/_cat/nodes?v'

创建索引:

curl -XPUT '192.168.1.1:9200/test-index?pretty'

注意:索引名中不能使用大写,否则会报错:

Could not index event to Elasticsearch.     "reason"=>"Invalid index name [iTech-swift-proxy-2018.11.08], must be lowercase",

删除索引:

curl -XDELETE '192.168.1.1:9200/test-index?pretty'

向索引中插入数据:

curl -XPUT '192.168.1.1:9200/test-index/<_type>/<_id>?pretty' -d '{"name": "test name"}'

获取插入的数据:

curl -XGET '192.168.1.1:9200/test-index/<_type>/<_id>?pretty'

(<_type>和<_id>用实际需要插入的属性名和id值替换)

更新数据:

curl -XPOST '192.168.1.1:9200/test-index/<_type>/<_id>/_update?pretty' -d '{"doc": { "name": "test2 Name" }}'

删除数据:

curl -XDELETE '192.168.1.1:9200/test-index/<_type>/<_id>?pretty'

查询数据:

curl -XPOST '192.168.1.1:9200/test-index/_search?pretty' -d '{"query": { "match_all": {} }}'

如果有一台elasticsearch磁盘空间不足,将会导致index变成readonly状态,此时扩容后需要用以下命令修改其状态,恢复正常:

curl -XPUT -H "Content-Type: application/json" http://10.202.233.78:9200/_all/_settings -d '{"index.blocks.read_only_allow_delete": null}'

全部查询接口实例请参考:

https://www.cnblogs.com/pilihaotian/p/5830754.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/507171.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

matlab程序svm四等级分类,支持向量机(SVM)多分类matlab程序代码

%模型训练及数据整理model_12svmtrain(class_12_label,class_12_value);model_13svmtrain(class_13_label,class_13_value);model_14svmtrain(class_14_label,class_14_value);model_23svmtrain(class_23_label,class_23_value);model_24svmtrain(class_24_label,class_24_valu…

python requests form data_python使用requests发送multipart/form-data请求数据

def client_post_mutipart_formdata_requests(request_url,requestdict):#功能说明&#xff1a;发送以多部分表单数据格式(它要求post的消息体分多个部分(fields)发送&#xff0c;每个fields之间用自定义的且唯一的随机字符串boundary进行分割。)请求到远程服务器&#xff0c;并…

oracle 几个字段中某个字段大于0其他字段不再进行统计?_如何深入理解MySQL 8.0直方图?...

MySQL8.0 新功能直方图&#xff0c;继承于Oracle &#xff0c;MairaDB的实现方式。 那下面从mysql角度认识下&#xff0c;直方图是什么。先看下官方直方图的实现方式。 从上图上可以看到原来是ANALYZE命令。先了解一下MySQL里 ANALYZE命令到底有什么用。ANALYZE在MySQL里提交一…

Apache java文件比对,Java Apache Commons的字符串比较

1&#xff64;使用Apache Commons的equals()实现字符串比较StringUtils类的equals()方法是String类方法equals()的增强版&#xff0c;它会处理null值:assertThat(StringUtils.equals(null, null)).isTrue();assertThat(StringUtils.equals(null, "equals method")).i…

godaddy修改php版本,Godaddy美国主机Plesk面板修改PHP版本教程

由于不同的需求&#xff0c;我们站长朋友们建站所用的网站程序也不尽相同&#xff0c;有PHP、ASP和ASP.NET等。Godaddy美国主机作为全球最大域名主机商&#xff0c;当之无愧成为站长使用最多的主机。不少朋友应该都知道不同的网站程序对于PHP和ASP的版本要求又不一样&#xff0…

mysql数据结构_mysql的底层数据结构

一&#xff0e;数据结构1. 二叉树特点&#xff1a;左侧子节点比父节点小&#xff0c;右侧子节点比父节点大(对于同一个父节点下的两个子节点)缺点&#xff1a;对于一直递增得数据不能存在该数据结构中&#xff0c;会变成链表&#xff0c;不能降低树的高度图 1-1图1-22. 红黑树特…

python 隐含波动率_【BSM模型】用实际市场数据计算隐含波动率并验证波动率微笑...

在Black-Scholes期权定价模型中&#xff0c;不能直接观察到的参数只有股票价格的波动率。波动率可以由历史数据进行估计&#xff0c;这是历史波动率。隐含波动率也是交易员非常关心的&#xff0c;隐含波动率是期权的市场价格中所包含的波动率&#xff0c;即由期权价格和期权定价…

php获得指定目录文件,PHP遍历指定文件夹获取路径及大小(包含子文件夹)

PHP获取指定文件夹下(包含子文件夹)所有文件路径 及 大小代码如下&#xff1a;// 获取指定文件夹 所有文件及大小 (包含子文件夹) By 【简爱】function JA_files2arr($dirpath){if($dirpath[strlen($dirpath)-1]!"/"){$dirpath."/";} //static $result_arr…

winform判断线程有没有完成_并发编程系列1:线程池的架构实现、大小配置、及四种线程池使用...

△ 公众号回复关键词“架构” 即可领取《1500BAT架构及面试专题合集》本篇为线程池系列文章之一&#xff0c;不经常使用线程池的童鞋&#xff0c;还有对几种线程的使用不甚了解的童鞋&#xff0c;可以读一下此文&#xff0c;并关注后续线程池相关文章连载。 本篇内容大纲&#…

python枚举是什么意思,什么是枚举python

枚举类型可以看作是一种标签或是一系列常量的集合&#xff0c;通常用于表示某些特定的有限集合&#xff0c;例如星期、月份、状态等。Python 的原生类型(Built-in types)里并没有专门的枚举类型&#xff0c;但是我们可以通过很多方法来实现它&#xff0c;例如字典、类等&#x…

php 10060,远程连接mysql 10060错误

远程连接mysql 10060错误Could not connect: Cant connect to MySQL server on ***.***.***.*** (10060)代码是$con mysql_connect("***.***.***.***","user","Password");if (!$con){die(Could not connect: . mysql_error());}用户名和密码正…

python包含多个元组的元组_Python数据结构(元组,列表,字典)

Python内置了 几种数据结构,元组,列表 字典1.元组元组可以由不同的元素组成,所有元素通过圆括号( )包含起来,并通过逗号","隔开.如变量名 (元素1,元素2,...),如果a 1,3,56,abc,aoe,也默认a是元组每个元素也可以是不同的数据类型,字符串,数字,元组,列表,字典元组的元…

vscode 导入python库_vscode 如何导入python库

vscode 如何导入python库首先&#xff0c;我们要知道&#xff0c;VScode和本地运行的并不是同一个python&#xff0c;反正我的是这样&#xff0c;所以导致了在本地下载好库后&#xff0c;在VScode运行时还是报错。那么如何在VScode中导入python库呢&#xff1f;1.已经在vscode中…

docker部署php站点,docker部署php

## **Docker部署php**操作系统&#xff1a;Ubuntu16.04 / Ubuntu18.04~~~//查看可用的php版本$ docker search php//这里安装php7.1版$ docker pull php:7.1-fpm//启动挂载$ docker run -p 9000:9000 -d --name myphp-fpm -v /docker/www:/usr/share/nginx/www php:7.1-fpm//这…

python怎么退出调试模式_python – 在验尸调试时如何退出ipdb?

我喜欢使用以下方式检查Python脚本中的错误&#xff1a;$python3 -m pdb my_script.py这会让我进入一个pdb提示,从那里我可以继续执行,当它遇到错误,我可以检查变量,然后q退出脚本执行以回到我的shell.我尝试与iPython调试器模块相同,因为它更加丰富多彩&#xff1a;$python3 -…

oracle捕捉所有异常,如何捕获和处理特定的Oracle异常?

你有两个选择&#xff1a;直接通过编号参考例外&#xff1a;BEGINEXECUTE IMMEDIATE CREATE SEQUENCE S_TEST START WITH 1 INCREMENT BY 1;EXCEPTIONWHEN OTHERS THENIF SQLCODE -955 THENNULL; -- suppresses ORA-00955 exceptionELSERAISE;END IF;END;其他选项是使用EXCEPT…

拖拽批量上传图片如何保证 顺序_图片压缩神器和图片分割工具,美工设计和运营终于得救了...

想要快速互联网干货技巧&#xff1f;请&#xff08;置顶&#xff09;星标我们好不容易写好文案&#xff0c;设计好长图海报&#xff0c;上传到微信公众号&#xff0c;竟然提示上传图片体积不得超过5M,怎么办&#xff1f;怎么办&#xff1f;不得已&#xff0c;只好又返回Ps里降低…

php将word转txt,PHP如何将将word文件转为pdf

PHP将word文件转为pdf的方法&#xff1a;首先修改【php.ini】&#xff0c;并重启环境&#xff1b;然后安装微软office套件&#xff1b;最后配置office组件服务即可。PHP将word文件转为pdf的方法&#xff1a;1、修改php.ini添加&#xff1a;extensionphp_com_dotnet.dll去除注释…

redis一般缓存什么样数据_SpringBoot+Redis轻松实现数据缓存

1.为什么需要缓存为什么需要缓存&#xff0c;我相信搞开发的都能回答出来&#xff0c;无非就是为了降低数据库压力&#xff0c;节约资源&#xff0c;提升系统性能。而事实上也确实是&#xff0c;归根结底就是降压&#xff0c;高并发&#xff0c;高性能。不过&#xff0c;大厂里…