【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, )
相关推荐
步辞1 小时前
Go语言怎么用channel做信号通知_Go语言channel信号模式教程【完整】
jvm·数据库·python
Ulyanov1 小时前
《PySide6 GUI开发指南:QML核心与实践》 第一篇:GUI新纪元——QML与PySide6生态系统全景
开发语言·python·qt·qml·雷达电子对抗
曲幽1 小时前
FastAPI + SQLAlchemy 2.0 通用CRUD操作手册 —— 从同步到异步,一次讲透
python·fastapi·web·async·sqlalchemy·session·crud·sync·with
Dxy12393102161 小时前
Python 如何使用 XPath 定位元素:从入门到实战
python
用户8356290780511 小时前
Python 设置 PowerPoint 文档属性与页面参数
后端·python
weixin_424999361 小时前
mysql行级锁失效的原因排查_检查查询条件与执行计划
jvm·数据库·python
yaoxin5211231 小时前
389. Java IO API - 获取文件名
java·开发语言·python
Polar__Star1 小时前
uni-app怎么实现App端一键换肤 uni-app全局样式动态切换【实战】
jvm·数据库·python
用户8356290780512 小时前
使用 Python 自动管理 PowerPoint 幻灯片分节的方法
后端·python
LinuxGeek10242 小时前
Kylin-Server-V11、openEuler-22.03和openEuler-24.03的MySQL 9.7.0版本正式发布
大数据·mysql·kylin