python连接elasticsearch
from elasticsearch import Elasticsearch
from elasticsearch.helpers import scan
ES_HOSTS = [{'host': '', 'port': 9200, 'scheme': 'http'}]
es = Elasticsearch(hosts=ES_HOSTS, basic_auth=('账号', '密码'))
if es.ping():
print('Yeah Connected!')
else:
print('Oh no :(')
list_a=['','','','']
query_test = {
"query": {
"terms": {
"A": list_a
}
}
}
search_response = es.search(index="索引名", body=query_test )
if search_response['hits']['hits']:
for hit in search_response['hits']['hits']:
source = hit['_source']
print(source)
else:
print("没有匹配的文档")
data = []
if 'aggregations' in search_response and 'A_groups' in search_response['aggregations']:
for bucket in search_response['aggregations']['A_groups']['buckets']:
row = {
'A': bucket['key'],
'B': bucket['b_count']['value']
}
data.append(row)
df= pd.DataFrame(data)
if 'hits' in search_response and 'total' in search_response['hits']:
total_hits = search_response['hits']['total']
if isinstance(total_hits, dict) and 'value' in total_hits:
total_hits = total_hits['value']
else:
pass
print(f"Total hits: {total_hits}")
else:
print("没有搜索响应或hits信息")