描述:ElasticSearch是一个基于Lucene的搜索服务器。它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口。下面介绍了利用Python API接口进行数据查询,方便其他系统的调用。安装API1pip install elasticsearch建立es连接12from elasticsearch import Elasticsearches = Elasticsearch([{'host':'10.10.13.12','port':9200}]) # 如果索引不存在,则创建索引if _es.indices.exists(index='blog_index') is not True: _es.indices.create(index='blog_index', body=_index_mappings) # 将refresh设为true,使得添加的文档可以立即搜索到; # 默认为false,可能会导致下面的search没有结果 _es.index(index='blog_index', doc_type='user', refresh=True, body=_doc)# 查询所有记录结果print('Search all...', flush=True)_query_all = { 'query': { 'match_all': {} }}_searched = _es.search(index='blog_index', doc_type='user', body=_query_all)print(_searched, flush=True)# 输出查询到的结果for hit in _searched['hits']['hits']: print(hit['_source'], flush=True)数据检索功能1es.search(index='logstash-2015.08.20', q='http_status_code:5* AND server_name:"web1"', from_='124119')常用参数index - 索引名q - 查询指定匹配 使用Lucene查询语法from_ - 查询起始点 默认0doc_type - 文档类型size - 指定查询条数 默认10field - 指定字段 逗号分隔sort - 排序 字段:asc/descbody - 使用Query DSLscroll - 滚动查询统计查询功能# 语法同search大致一样,但只输出统计值12In[52]: es.count(index='logstash-2015.08.21', q='http_status_code:500')Out[52]:{u'_shards':{u'failed':0, u'successful':5, u'total':5}, u'count':17042} 知识扩展滚动demo123456789101112131415161718192021222324# Initialize the scrollpage = es.search( index ='yourIndex', doc_type ='yourType', scroll ='2m', search_type ='scan', size =1000, body ={ # Your query's body})sid = page['_scroll_id']scroll_size = page['hits']['total']# Start scrollingwhile(scroll_size >0): print "Scrolling..." page = es.scroll(scroll_id = sid, scroll ='2m') # Update the scroll ID sid = page['_scroll_id'] # Get the number of results that we returned in the last scroll scroll_size = len(page['hits']['hits']) print "scroll size: "+ str(scroll_size) # Do something with the obtained page以上demo实现了一次取若干数据,数据取完之后结束,不会获取到最新更新的数据。我们滚动完之后想获取最新数据怎么办?滚动的时候会有一个统计值,如total: 5。跳出循环之后,我们可以用_from参数定位到5开始滚动之后的数据。Query DSLrange过滤器查询范围gt: > 大于lt: < 小于gte: >= 大于或等于lte: <= 小于或等于123456"range":{ "money":{ "gt":20, "lt":40 }} bool组合过滤器must:所有分句都必须匹配,与 AND 相同。must_not:所有分句都必须不匹配,与 NOT 相同。should:至少有一个分句匹配,与 OR 相同。1234567{ "bool":{ "must":[], "should":[], "must_not":[], }}term过滤器term单过滤12345{ "terms":{ "money":20 }} terms复数版本,允许多个匹配条件12345{ "terms":{ "money": [20,30] }}正则查询 12345{ "regexp": { "http_status_code": "5.*" }}match查询match 精确匹配12345{ "match":{ "email":"123456@qq.com" }}multi_match 多字段搜索123456{ "multi_match":{ "query":"11", "fields":["Tr","Tq"] }}demo获取最近一小时的数据123456789{'query': {'filtered': {'filter': {'range': {'@timestamp':{'gt':'now-1h'}} } } }} 条件过滤查询12345678{ "query":{ "filtered":{ "query":{"match":{"http_status_code":500}}, "filter":{"term":{"server_name":"vip03"}} } }}Terms Facet 单字段统计12345678910{'facets': {'stat': {'terms': {'field':'http_status_code', 'order':'count', 'size':50} } }, 'size':0} 一次统计多个字段12345678910{'facets': {'cip': {'terms': {'fields':['client_ip']}}, 'status_facets':{'terms':{'fields':['http_status_code'], 'order':'term', 'size':50}}}, 'query':{'query_string':{'query':'*'}}, 'size':0} 多个字段一起统计123456789101112{'facets': {'tag': {'terms': {'fields':['http_status_code','client_ip'], 'size':10 } } }, 'query': {'match_all':{}}, 'size':0} 数据组装以下是kibana首页的demo,用来统计一段时间内的日志数量1234567891011121314151617181920212223242526272829303132333435363738394041424344{ "facets": { "0": { "date_histogram": { "field": "@timestamp", "interval": "5m" }, "facet_filter": { "fquery": { "query": { "filtered": { "query": { "query_string": { "query": "*" } }, "filter": { "bool": { "must": [ { "range": { "@timestamp": { 'gt': 'now-1h' } } }, { "exists": { "field": "http_status_code.raw" } }, # --------------- ------- # 此处加匹配条件 ] } } } } } } } }, "size": 0} 如果想添加匹配条件,在以上代码标识部分加上过滤条件,按照以下代码格式即可12345{"query": { "query_string": {"query": "backend_name:baidu.com"} }},