python elasearch-dsl 查询
pip install elasticsearch-dsl
pip install elasticsearch
from elasticsearch import Elasticsearch
client = Elasticsearch('127.0.0.1:9021')
def esSearch():
from elasticsearch_dsl.search import Search, Q, A
index = 'test_base_service_test_case'
search = Search(using=client, index=index).params(size=10000)
# 1.匹配条件
q1= Q("match", project_id=581) & Q("match", is_delete=0) # 等于
q2 = Q("terms", id=[1, 3, 5, 7, 9]) # in
search = search.query(q1).query(q2)
# 2.范围查询(range)
search = search.filter("range", create_time={"gte": '2020-02-26T20:17:04.000Z', "lte": '2020-03-27T20:53:24.000Z'})
# 3.排序
search = search.sort({'creation_date': {"order": "desc"}})
# 4.返回结果过滤
search = search.source(include=["id", "creation_date"], exclude=[])
# 5.求和 (无返回值)
search.aggs.metric("sum_age", "stats", field="age") # 对age求和; stats为固定字段名,可改为extended_stats
# 6.分组求和 (无返回值)
search.aggs.bucket("groupDate", "date_histogram", field="creation_time", interval="day", format="yyyy-MM-dd") # 按照creation_date分天统计记录条数,相当于count(id) group by day
# 7.执行
search_result = search.execute()
# 8.结果转化为dict
search_result = search_result.to_dict()
return search_result