【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 分钟前
不同规模企业如何选 OPM?参考局域网管理软件与 cpu 温度监控适配指南
大数据·运维·服务器·网络·数据库·postgresql·snmp
superman超哥11 分钟前
仓颉性能瓶颈定位方法深度解析
c语言·开发语言·c++·python·仓颉
岁岁的O泡奶18 分钟前
NSSCTF_crypto_[SWPU 2020]happy
经验分享·python·算法·密码学
武汉唯众智创20 分钟前
“物联网 Python 开发教程”课程教学解决方案
开发语言·python·物联网·物联网技术·物联网 python 开发·python 开发
是阿威啊23 分钟前
【第六站】测试本地项目连接虚拟机上的大数据集群
大数据·linux·hive·hadoop·spark·yarn
老徐电商数据笔记23 分钟前
技术复盘第八篇:从“数据烟囱”到“能力引擎”:中型电商数仓重构实战手册
大数据·数据仓库·重构·数据中台·用户画像·技术面试
时光Autistic24 分钟前
【搭建教程】腾讯混元3D模型部署
开发语言·python·3d·github
前端程序猿之路25 分钟前
AI大模型应用之-RAG 全流程
人工智能·python·gpt·语言模型·aigc·mybatis·ai编程
程序员miki26 分钟前
Dramatiq安装及应用(一)
python·dramatiq
数据皮皮侠AI31 分钟前
数字经济政策工具变量数据(2008-2023)
大数据·数据库·人工智能·笔记·1024程序员节