日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪(fǎng)問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程语言 > python >内容正文

python

pythonsearch结果_python 查询Elasticsearch的小例子

發(fā)布時(shí)間:2024/8/23 python 26 豆豆
生活随笔 收集整理的這篇文章主要介紹了 pythonsearch结果_python 查询Elasticsearch的小例子 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

#!/usr/bin/env python

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

from sfo_common.agent import Agent

from sfo_common.import_common import *

class ElkLog(object):

"""

處理ELK數(shù)據(jù)類(lèi)

"""

def __init__(self):

pass

def get_elk_log_json(self):

"""

通過(guò)調(diào)用elasticsearch接口查詢(xún)指定索引數(shù)據(jù),計(jì)算集群的平均響應(yīng)時(shí)間

: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):

"""

起線(xiàn)程執(zhí)行日志分析

: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()

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

更多查詢(xún)方式接口:

查詢(xún)一條記錄

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}'

查詢(xún)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 } }}'

查詢(xún)結(jié)果只返回指定的字段

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"]}'

查詢(xún)結(jié)果排序

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開(kāi)始的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" } }'

集群健康狀態(tài)查詢(xún):

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

查詢(xún)索引列表:

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

查詢(xún)集群節(jié)點(diǎn)列表:

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

創(chuàng)建索引:

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

注意:索引名中不能使用大寫(xiě),否則會(huì)報(bào)錯(cuò):

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'

向索引中插入數(shù)據(jù):

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

獲取插入的數(shù)據(jù):

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

(<_type>和<_id>用實(shí)際需要插入的屬性名和id值替換)

更新數(shù)據(jù):

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

刪除數(shù)據(jù):

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

查詢(xún)數(shù)據(jù):

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

如果有一臺(tái)elasticsearch磁盤(pán)空間不足,將會(huì)導(dǎo)致index變成readonly狀態(tài),此時(shí)擴(kuò)容后需要用以下命令修改其狀態(tài),恢復(fù)正常:

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

全部查詢(xún)接口實(shí)例請(qǐng)參考:

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

創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎(jiǎng)勵(lì)來(lái)咯,堅(jiān)持創(chuàng)作打卡瓜分現(xiàn)金大獎(jiǎng)

總結(jié)

以上是生活随笔為你收集整理的pythonsearch结果_python 查询Elasticsearch的小例子的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。

主站蜘蛛池模板: 中文字幕一区三区 | 麻豆蜜桃av | 91丨九色丨蝌蚪丨对白 | 亚洲欧美成人综合 | 99无码熟妇丰满人妻啪啪 | 村姑电影在线播放免费观看 | 亚洲一级一级 | 欧美熟妇精品一区二区 | 日韩三级视频在线观看 | 波多野结衣中文字幕一区二区三区 | 九九人人 | 亚洲国产激情 | 都市乱淫 | 亚洲成人高清在线观看 | 国产91精品久久久久久久 | 爱爱爱爱网| 欧美中字 | 人妻奶水人妻系列 | 成人久久影院 | 在线无遮挡| 有机z中国电影免费观看 | 3d欧美精品动漫xxxx无尽 | 欧美一区二区在线 | 国产h片在线观看 | 日本无遮挡边做边爱边摸 | 欧美精品v国产精品v日韩精品 | 在线播放色| 影音先锋成人资源网 | 大战熟女丰满人妻av | 国产精品视频合集 | 在线一区二区三区视频 | 玖玖精品在线视频 | 91精品观看 | 人人干人人草 | 窝窝午夜视频 | 国产日韩欧美一二三区 | 国产第三区 | 亚洲国产日韩一区无码精品久久久 | 在线成人| 福利精品 | 亚洲视频99 | 色哟哟精品一区 | 一级视频毛片 | 中国在线观看片免费 | 人妻内射一区二区在线视频 | 粉嫩av蜜桃av蜜臀av | 亚洲第一在线 | 成人做爰的视频 | 91天天色| 日韩专区中文字幕 | 婷婷麻豆 | 免费国产一区 | 在线步兵区 | 亚洲黄色第一页 | 污黄网站在线观看 | 精品亚洲一区二区三区四区五区 | 国产成人8x视频一区二区 | 日本高清视频在线播放 | 香蕉视频黄在线观看 | 久久黑人 | 成人免费在线看片 | 上海毛片 | 成年人视频在线免费观看 | 日美av | 亚洲gay视频 | 欧美疯狂做受xxxxx高潮 | 日本少妇videos高潮 | 亚洲一区二区网站 | 999xxxx| 海角社区id:1220.7126,10. | 韩国伦理在线视频 | 男女午夜爽爽爽 | 丁香花电影免费播放在线观看 | 大肉大捧一进一出好爽 | www.一区二区 | 国产精品suv一区二区88 | 久久高清一区 | 亚洲天堂国产精品 | 91精彩视频在线观看 | 国产美女网站视频 | 精品久久久久久久久久久国产字幕 | 天天插夜夜爽 | 亚洲福利午夜 | 国产欧美在线观看 | 婷婷五月在线视频 | 国内视频自拍 | 九一国产在线观看 | 99极品视频 | 好吊色青青草 | 第一章豪妇荡乳黄淑珍 | 亚洲最大福利网站 | 男人天堂va | 999资源站 | 国产精品69久久久久 | a毛片 | 九九视频精品在线 | 丁香一区二区三区 | 逼逼av网站 | 就是色 |