引言
工作中常常是将数据库的数据推送到es用作快速搜索查询,但是在某些特定情况下,可能需要将es上的数据获取下来,存储到数据库以备使用。本篇是记录自己对于此需求的学习和python方法实现。
获取es连接
先引用elasticsearch包
from elasticsearch import Elasticsearch
获取连接
es = Elasticsearch(
hosts=['127.0.0.1'],
http_auth=('*','*'),
port=9200,
sniff_on_start=True,
sniff_on_connection_fail=True,
sniff_timeout=60,
ignore=[400, 405, 502]
)
查询数据
先构造es条件查询语句
import time
starttime = 20200825000000
endtime= int(time.strftime('%Y%m%d%H%M%S', time.localtime()))
query = {
"query": {
"bool": {
"filter": {
"range": {
"gxsj": {
"gte": starttime,
"lte": endtime
}
}
}
}
}
}
根据条件查询数据
index_name = "xxx"
type_name = "xxx"
size = 100
es_result = es.search(index=index_name, doc_type=type_name, body=query, scroll='5m', size=size)
result_items = es_result['hits']['hits']
es_total = es_result['hits']['total']
scroll_id = es_result['_scroll_id']
for i in range(0, int(es_total / size) +