【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, )
相关推荐
上海锝秉工控6 分钟前
超声波风向传感器:以科技之翼,捕捉风的每一次呼吸
大数据·人工智能·科技
海天一色y1 小时前
Pycharm(二十一)递归删除文件夹
ide·python·pycharm
在未来等你3 小时前
Elasticsearch面试精讲 Day 13:索引生命周期管理ILM
大数据·分布式·elasticsearch·搜索引擎·面试
Elastic 中国社区官方博客5 小时前
Elasticsearch:智能搜索的 MCP
大数据·人工智能·elasticsearch·搜索引擎·全文检索
乔巴先生246 小时前
LLMCompiler:基于LangGraph的并行化Agent架构高效实现
人工智能·python·langchain·人机交互
未来之窗软件服务7 小时前
浏览器开发CEFSharp+X86 (十六)网页读取电子秤数据——仙盟创梦IDE
大数据·智能硬件·浏览器开发·仙盟创梦ide·东方仙盟·东方仙盟网页调用sdk
张子夜 iiii7 小时前
实战项目-----Python+OpenCV 实现对视频的椒盐噪声注入与实时平滑还原”
开发语言·python·opencv·计算机视觉
困鲲鲲8 小时前
Flask 核心基础:从 路由装饰器 到 __name__ 变量 的底层逻辑解析
python·flask
njxiejing9 小时前
Python NumPy安装、导入与入门
开发语言·python·numpy
阿豪39 小时前
2025 年职场转行突围:除实习外,这些硬核证书让你的简历脱颖而出(纯经验分享)
大数据·人工智能·经验分享·科技·信息可视化·产品经理