用于ElasticSearch Watcher的Python客户端

elasticsearch-watcher的Python项目详细描述


这是官方elasticsearch python客户端的一个插件,它添加了 Watcher插件的功能。

安装

您可以使用pip

pip install elasticsearch-watcher

用法

您可以单独使用此客户端:

fromelasticsearchimportElasticsearchfromelasticsearch_watcherimportWatcherClientclient=Elasticsearch()watcher=WatcherClient(client)watcher.get_watch(id=42)

或者,您可以将watcher命名空间添加到正式客户端,以模拟 其他命名空间的行为:

WatcherClient.infect_client(client)client.watcher.get_watch(id=42)

复杂示例

fromtimeimportsleepfromdatetimeimportdatetimefromrandomimportrandintfromelasticsearchimportElasticsearchfromelasticsearch_watcherimportWatcherClient# initialize the standard client as usuales=Elasticsearch()# add the .watcher namespace to itWatcherClient.infect_client(es)# clear the index fiorstes.indices.delete(index=['alerts','test','.watches','.watch_history*'],ignore=404)# get the watcher plugin versionprint('Using watcher',es.watcher.info()['version']['number'])# Register a new watches.watcher.put_watch(id='error_500',body={# label the watch'metadata':{'tags':['errors']},# Run the watch every 10 seconds'trigger':{'schedule':{'interval':'10s'}},# Search for at least 3 documents matching the condition'condition':{'script':{'inline':'ctx.payload.hits.total > 3'}},# Throttle the watch execution for 30 seconds'throttle_period':'30s',# The search request to execute'input':{'search':{'request':{'indices':['test'],'body':{'query':{'filtered':{'query':{'match':{'status':500}},'filter':{'range':{'timestamp':{'from':'{{ctx.trigger.scheduled_time}}||-5m','to':'{{ctx.trigger.triggered_time}}'}}}}},# Return statistics about different hosts'aggregations':{'hosts':{'terms':{'field':'host'}}}}}}},# The actions to perform'actions':{'send_email':{'transform':{# Transform the data for the template'script':'''return [
                            total: ctx.payload.hits.total,
                            hosts: ctx.payload.aggregations.hosts.buckets.collect { [ host: it.key, errors: it.doc_count ] },
                            errors: ctx.payload.hits.hits.collect { it._source }
                        ];'''},'email':{'to':'you@example.com','subject':'[ALERT] {{ctx.watch_id}}','attach_data':True,'body':'''
                        Received {{ctx.payload.total}} error documents in the last 5 minutes.

                        Hosts:

                        {{#ctx.payload.hosts}}* {{host}} ({{errors}})
                        {{/ctx.payload.hosts}}'''.replace('\n'+' '*24,'\n').strip(),}},'index_payload':{# Transform the data to be stored'transform':{'script':'return [ watch_id: ctx.watch_id, payload: ctx.payload ]'},'index':{'index':'alerts','doc_type':'alert'}},'ping_webhook':{'webhook':{'method':'POST','host':'localhost','port':8000,'path':'/','body':'{"watch_id" : "{{ctx.watch_id}}", "payload" : "{{ctx.payload}}"}'}}}})# index documents to trigger the watchfor_inrange(5):es.index(index='test',doc_type='d',body={'timestamp':datetime.utcnow(),'status':500,'host':'10.0.0.%d'%randint(1,3)})# wait a bit...for_inrange(30):sleep(1)print('.',sep='',end='',flush=True)print()# display information about watch executionprint('='*80)s=es.search(index='.watch_history*',q='watch_id:error_500',sort='trigger_event.schedule.triggered_time:asc')forhitins['hits']['hits']:print('%s: %s'%(hit['_id'],hit['_source']['state']))# delete the watches.watcher.delete_watch(id='error_500',force=True)

许可证

2015 ElasticSearch版权所有

根据apache许可证2.0版(以下简称“许可证”)授权; 除非符合许可证,否则您不能使用此文件。 您可以在

http://www.apache.org/licenses/LICENSE-2.0

除非适用法律要求或书面同意,否则软件 根据许可证分发是按“原样”分发的, 无任何明示或默示的保证或条件。 有关管理权限的特定语言和 许可下的限制。

欢迎加入QQ群-->: 979659372 Python中文网_新手群

推荐PyPI第三方库


热门话题
Split方法在Java数组中创建空元素   多线程java多线程读取。。请帮助我,我对java非常陌生:(   调整大小时,java jpanel与jdesktop窗格不匹配   java JDBC/MYSQL通信链路故障(ECLIPSE/ANDROID)   java Android应用程序登录和注册错误   同一行上多次字符串之间的Java正则表达式   java为什么Spring在混淆之后看不到我的@Resource注释对象?   java Javafx:解析命名空间中不存在的onAction//eventHandler时出错   Java中的“原始接口方法”是什么?   apache如何在使用httpClent java上传时取得进展   java如何设计我的setter方法?   java可以在使用Iterable迭代元素时更改元素。forEach(消费者)?   java组织。openqa。硒。ElementNotVisibleException   使用JAXRS和OData的java REST服务?