python操作Elasticsearch数据

 这篇文章主要记录关于Elasticsearch一些基本查询和聚合的知识。

获取基本信息语法:

1、查询索引:http://xxx/_cat/indices?v

2、获取节点信息:http://xxx/_cat/nodes?v

3、查询集群的健康状态:http://xxx/_cat/health?v

对于Elasticsearch服务器上的记录信息查询,基本语法大致形式如: /索引/类型/id/?q=*&v

 如下图所示,我先创建一个对应的索引再查询:

一般来说,Elasticsearch服务器上的数据都是比较多的,全部查询出来很不现实,于是在这里面有一些基本的过滤筛选,具体语法网上都有很多,也可参见:https://www.elastic.co/guide/en/elasticsearch/reference/current/search.html

那我们回到正题,如何用python操作这些数据呢?可以使用python的 elasticsearch 这个包就行了。具体代码可以如下:

#!/usr/bin/env python
#-*- coding:utf-8 –*-

import time from elasticsearch import Elasticsearch
es = Elasticsearch([{'host': 'xxx', 'port': 9200}])
Index = "xxxx_index_"
body_EWS = {
    "query":{
        "bool":{
            "must":[
                {
                    "range":{
                        "@timestamp":{
                            "from":"now-40m",
                            "to":"now"
                        }
                    }
                },
                {
                    "match_phrase":{
                        "message":{
                            "query":"xxx"
                        }
                    }
                },
                {
                    "match_phrase":{
                        "logtype":{
                            "query":"log"
                        }
                    }
                }
            ]
        }
    },
    "aggs":{
        "multiple_xxx":{
            "terms":{
                "field":"xxx"
            },
            "aggs":{
                "multiple_response":{
                    "terms":{
                        "field":"xx"
                    }
                }
            }
        }
    }
}

if __name__ == '__main__':
    data = time.strftime('%Y.%m.%d', time.localtime(time.time()))
    string = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    Index = Index + data  # index
    logon_res = es.search(
        index=Index,
        body=body_EWS
    )
    for ip_bucket in logon_res["aggregations"]["multiple_clientip"]["buckets"]:
        print ip_bucket["key"] + ":" + str(ip_bucket["doc_count"])
        for response_bucket in ip_bucket["multiple_response"]["buckets"]:
            print '-------->>>> ' + response_bucket['key'] + ' : ' + str(response_bucket['doc_count'])

简单记录下,方便以后查阅。

posted on 2017-07-21 23:37  镱鍚  阅读(306)  评论(0)    收藏  举报

导航