欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 健康 > 养生 > 【Es】python es操作

【Es】python es操作

2024/10/24 18:26:30 来源:https://blog.csdn.net/qq_39057568/article/details/141265594  浏览:    关键词:【Es】python es操作

因为es是集群所以es_hosts是列表

from elasticsearch import Elasticsearch
ES_HOSTS = ["127.0.0.1:9200"]
ES_HTTP_AUTH = "******************"# 连接Es
es = Elasticsearch(hosts=ES_HOSTS ,http_auth=ES_HTTP_AUTH ,maxsize=60,timeout=30,max_retries=3,retry_on_timeout=True
)
index = "assets_distinguish"

创建表

# 检查索引是否存在,如果不存在则创建它
if not es.indices.exists(index=index):# 创建一个索引es.indices.create(index=index)

删除表

# 删除表 index;删完了记得再创建,后边要用到
#res = es.indices.delete(index=index)
#print(res)

增加

import random
item = {"ip_addr": "{}.{}.{}.{}".format(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)),"domain": "{}.cn".format(random.randint(0, 1000)),"geographic_location": ["北京", "上海", "广东", "深圳", "成都", "天津", "西安", ][random.randint(0, 5)],"discovery_time": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),}
res = es.index_name(index=index, body=item)
print("插入结果:", res)

查询


must= []
if discovery_time_start and discovery_time_start:must.append({'range': {'discovery_time': {"gte": discovery_time_start, "lte": discovery_time_end}}})
if ip_addr:must.append({"terms": {"ip_addr.keyword": [ip_addr]}})body = {"query": {"bool": {'must': must}},"sort": {"discovery_time": {"order": "desc"}},'from': (page - 1) * page_size,'size': page_size
}res = es.search(index=index_name, body=body)

删除

 # 根据id删除
delete_by_id = {"query": {"match": {"_id": "srKjS5EBMKmoTl4VO9M8"}}}
result = es.delete_by_query(index=index, body=delete_by_id, )
# // 删除所有
delete_by_all = {"query": {"match_all": {}}}
result = es.delete_by_query(index=index, body=delete_by_id, )

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com