【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, )
相关推荐
极小狐9 分钟前
极狐GitLab 安全文件管理功能介绍
linux·运维·数据库·安全·elasticsearch·gitlab
da-peng-song9 分钟前
python学习—详解word邮件合并
python·学习·word
明明跟你说过24 分钟前
深入浅出 NVIDIA CUDA 架构与并行计算技术
人工智能·pytorch·python·chatgpt·架构·tensorflow
恒拓高科WorkPlus35 分钟前
内部聊天软件,BeeWorks-安全的企业内部通讯软件
大数据·网络·安全
科技小E1 小时前
视频设备轨迹回放平台EasyCVR打造水库大坝智慧安防视频监控智能分析方案
大数据·网络·人工智能·音视频·安防监控
get lend gua1 小时前
游戏数据分析,力扣(游戏玩法分析 I~V)mysql+pandas
python·mysql·leetcode·游戏·数据分析
唐叔在学习1 小时前
【Python入门】文件读取全攻略:5种常用格式(csv/excel/word/ppt/pdf)一键搞定 | 附完整代码示例
python·数据分析·办公自动化·文件处理
zxsz_com_cn1 小时前
医疗设备预测性维护的合规性挑战与标准化路径研究
大数据·数据库·人工智能
心软且酷丶1 小时前
leetcode:2899. 上一个遍历的整数(python3解法)
python·算法·leetcode