注意:elasticsearch 的版本不能太高,建议安装7.13.0
pip install elasticsearch ==7.13.0
from elasticsearch import Elasticsearch
import logging
logger = logging.getLogger("inquiry_es")
logging.basicConfig(filename="logs/logging.txt",
level=logging.INFO,
format='{"time":"%(asctime)s","script":"%(name)s","thread":"%(thread)d",'
'"threadName":"%(threadName)s","loglevel":"%(levelname)s"} - %(message)s')
class search_es:
def __init__(self,host,port="9200",user=None,passwd=None):
self.host = host
self.user = user
self.passwd = passwd
self.port = port
self.es = Elasticsearch([f"{self.host}:{self.port}"]) if user is None else \
Elasticsearch([f"{self.host}:{self.port}"],http_auth=(self.user, self.passwd))
# 获取所有的index
def get_indices(self):
# for index in self.es.indices.get('*'):
# print(index)
# indices = self.es.indices.get('*')
indices = self.es.indices.get_alias().keys()
indices = sorted(indices)
# print(indices)
return indices
# 查询index
def get_es(self,index,body={"size":10000,"query": {"match_all":{}}}):
"""
提交查询参数,返回结果
:return: es_data
"""
try:
logger.info(f"开始查询:{index}")
# print(self.es.index)
es_data = self.es.search(index=index, body=body)
logger.info(es_data)
return es_data
except Exception as e:
logger.error(f"error:{e}", exc_info=True, stack_info=True)
return {}