入职的新公司,中台使用的elasticsearch给我们提供的数据,已经测了两三个需求了,但不清楚如何查询数据,用例评审时直接说的不校验数据准确性,只做展示校验。然后,上线后发现了一堆bug,虽说没我啥责任吧,但心里总是觉得不是很舒服,于是开始了elasticsearch的简单入门之旅
几个关键概念
- index:类似于sql中的表
- type:类似于SQL中的库,一般查询的时候无需使用(或者也是我没使用)
- hits:返回的数据都在这个key下面
- hits.total:返回数据的数据数量
有这个概念后,根据提供的如何取值需求,就可以直接编写sql语句了:
select 字段 from index where 条件;
在线转换平台:http://www.ischoolbar.com/EsParser/
这样手工测试就可以玩了。
from elasticsearch import Elasticsearch
import pandas
from config.es_config import *
############################################
# 写的很简单,参数严格按要求给,想优化请自行优化 #
############################################
class DataBoard():
def __init__(self):
self.es = Elasticsearch([HOST], http_auth=(USERNAME, PASSWORD), scheme='http', port=PORT, timeout=30)
def create_body(self, fields, hospital_id, st_day="2021-05-01", et_day="2021-06-10"):
body = {"query": {
"bool": {"filter": [{"bool": {"must": [{"match_phrase": {"hospital_id": {"query": str(hospital_id)}}}]}},
{"range": {"st_day": {"gte": st_day, "time_zone": "+08:00",
"lte": et_day}}}]}},
"sort": [{"st_day": {"order": "DESC"}}], "_source": {
"include": fields}}
return body
def search(self, index, body, size=100):
'''
查询
:param index:
:param body:
:param size: 返回的数量
:return:
'''
return self.es.search(index=index, body=body or {'query': {'match_all': {}}}, size=size)
if __name__ == '__main__':
# 查询索引
index = 'dws_hospital_topics_d'
# 查询字段
fields = ["msg_2_user_cnt", "tel_user_call_user_cnt", "business_opp_enquiry_price_user_cnt"]
# 查询的机构(一般都是66)
hospital_id = 66
pandas.set_option('display.width', None) # 设置字符显示宽度
pandas.set_option('display.max_rows', None) # 设置显示最大行
pandas.set_option('display.max_columns', None) # 设置显示最大列
pandas.set_option('max_colwidth', None)
data = DataBoard()
body = data.create_body(fields=fields, hospital_id=hospital_id)
result = data.search(index=index, body=body)
print(result['hits']['hits'])
# 删除掉一些不需要看的字段
for d in result['hits']['hits']:
d.pop('_index')
d.pop('_type')
d.pop('_score')
print(pandas.DataFrame(result['hits']['hits']))
其中用到pandas处理了一下数据,方便控制台可视化展示