【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, )
相关推荐
Hello.Reader8 分钟前
Flink CDC 从 Definition 到可落地 YAML
大数据·adb·flink
2401_841495648 分钟前
【数据结构】基于BF算法的树种病毒检测
java·数据结构·c++·python·算法·字符串·模式匹配
图灵信徒27 分钟前
R语言绘图与可视化第六章总结
python·数据挖掘·数据分析·r语言
Lansonli28 分钟前
大数据Spark(七十二):Transformation转换算子repartition和coalesce使用案例
大数据·分布式·spark
chde2Wang29 分钟前
hbase启动报错-keeperErrorCode
大数据·数据库·hbase
清平乐的技术专栏32 分钟前
HBase Shell常用命令
大数据·数据库·hbase
封奚泽优35 分钟前
使用Labelme进行图像标注
开发语言·python·labelme
檐下翻书17342 分钟前
智能医疗大模型在医生培训中的应用案例
python
数字冰雹1 小时前
重塑城市公共安全管理的“智慧之眼”
java·大数据·数据库
码界筑梦坊1 小时前
243-基于Django与VUE的笔记本电脑数据可视化分析系统
vue.js·python·信息可视化·数据分析·django·毕业设计·echarts