【Es】python es操作

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

python 复制代码
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"

创建表

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

删除表

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

增加

python 复制代码
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)

查询

python 复制代码
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)

删除

python 复制代码
 # 根据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, )
相关推荐
Xinstall渠道统计平台5 分钟前
开发者怎么平衡变现模式与用户体验
大数据
优秘UMI7 分钟前
大语言模型 (LLM):理解与生成内容的核心技术引擎
python·科技·其他·ai
sherlock_ye410 分钟前
‘jupyter‘ 不是内部或外部命令,也不是可运行的程序或批处理文件,最终解决方案!
ide·python·jupyter·conda
Salt_072822 分钟前
DAY27 pipeline管道
python·机器学习
萧鼎23 分钟前
Python PyWavelets(pywt)库完整技术指南:从小波理论到工程实践
开发语言·python
MediaTea30 分钟前
Python 装饰器:@property_name.deleter
开发语言·python
中等生31 分钟前
Celery 异步任务完全指南:从入门到实战
python·flask
Cherry的跨界思维33 分钟前
5、Python长图拼接终极指南:Pillow/OpenCV/ImageMagick三方案
javascript·python·opencv·webpack·django·pillow·pygame
金叶科技智慧农业1 小时前
科技如何守护每一株幼苗?苗情生态监测系统带来田间新视角
大数据·人工智能
acethanlic1 小时前
使用Ruff进行Python代码Format、lint和fix
python