python清除es索引

#### 前言

当不需要查看的日志索引占用大量的空间时,需要去清除

 

#### python脚本语言实现清楚指定月份的es日志索引

 

##### python脚本文件

```

cat > /data/python3/delete-es-index.py <<-EOF

#!/usr/bin/env python3

 

import subprocess

import sys

 

def excuteCommand(command, cwd="/root"):

    subp = subprocess.Popen(command,

                            shell=True,

                            stdout=subprocess.PIPE,

                            stderr=subprocess.PIPE,

                            encoding="utf-8",

                            cwd=cwd)

    subp.wait(60)

    if subp.poll() == 0:

        pass

    else:

        return "failure"

 

def curlExcute():

    curlTxt = "curl http://localhost:9200/_cat/indices | grep mb | grep " + sys.argv[1] + " | awk '{print $3}' > /tmp/a.txt"

    excuteCommand(curlTxt)

    with open("/tmp/a.txt", "r") as fr:

        for i in fr.readlines():

            curlXDEL = "curl -XDELETE http://localhost:9200/" + i.strip('\n')

            excuteCommand(curlXDEL)

         

 

if __name__ == "__main__":

    curlExcute()

EOF

```

 

##### 执行python3脚本命令

> python3 /data/python3/delete-es-index.py 201910

### 如何使用Python与Elasticsearch交互 #### 安装Elasticsearch客户端库 为了能够顺利地在Python环境中与Elasticsearch进行通信,首先需要安装官方提供的`elasticsearch-py`客户端库。可以通过pip工具轻松完成这一过程: ```bash pip install elasticsearch ``` 此命令会自动下载并安装最新版本的Elasticsearch Python客户端[^4]。 #### 创建连接对象 建立到Elasticsearch集群的连接是执行任何操作的前提条件之一。下面是一段用于初始化Elasticsearch类实例来代表这种连接关系的基础代码片段: ```python from elasticsearch import Elasticsearch es_client = Elasticsearch( "http://localhost:9200", # 替换成自己的ES服务地址 request_timeout=30 # 设置请求超时时间 ) if not es_client.ping(): raise ValueError("Connection failed") print(&#39;Connected to ES&#39;) ``` 这段脚本不仅实现了基本链接设置还包含了简单的健康状态检测逻辑以确保成功建立了有效的网络通道[^1]。 #### 构建索引结构 定义好目标存储空间即索引之后才能继续后续的数据管理动作。这里给出了一种方式用来声明一个新的索引模式及其映射规则: ```json index_settings = { &#39;settings&#39;: { &#39;number_of_shards&#39;: 1, &#39;number_of_replicas&#39;: 0 }, &#39;mappings&#39;: { &#39;properties&#39;: { &#39;title&#39;: {&#39;type&#39;: &#39;text&#39;}, &#39;content&#39;: {&#39;type&#39;: &#39;text&#39;} } } } response = es_client.indices.create(index=&#39;test-index&#39;, body=index_settings, ignore=[400]) print(response) ``` 上述JSON格式的对象描述了一个名为`test-index`的新索引,并指定了其中两个字段(`title`, `content`)均为文本类型的属性配置信息[^3]。 #### 插入单条记录 当准备好接收新数据后就可以考虑怎样把它们送进去保存起来了。此处展示的是向指定位置写入一条具体消息的方法: ```python doc = { &#39;author&#39;: &#39;John Doe&#39;, &#39;text&#39;: &#39;Interesting content...&#39;, &#39;timestamp&#39;: datetime.now(), } res = es_client.index(index="test-index", id=1, document=doc) print(res[&#39;result&#39;]) ``` 该函数调用将会尝试将给定字典形式的内容作为编号为1的文章存放到之前创建好的测试索引里去[^2]。 #### 执行搜索查询 检索已有的资料无疑是数据库最核心的功能点了。下面的例子说明了如何构建一个简易版全文搜索引擎来进行关键词匹配查找工作: ```python query_body = {"size": 5,"_source": ["title"],"query":{"match_all":{}}} resp = es_client.search(index="test-index", body=query_body) for hit in resp[&#39;hits&#39;][&#39;hits&#39;]: print(hit["_source"]) ``` 这个例子中构造了一个只返回前五个结果并且仅显示标题部分的小规模搜索请求体;当然也可以根据需求调整参数来自定义更复杂的过滤表达式。 #### 更新现有文档 有时候可能需要修改已经存在的某些项的信息而不必重新上传整个文件。这时可以采用如下所示的方式针对特定ID对应的实体做局部改动: ```python update_body = {"doc": {"new_field": "This is a new field"}} res = es_client.update(index="test-index", id=1, body=update_body) print(res[&#39;result&#39;]) ``` 这条语句会在保持其他不变的情况下新增加一个叫作`new_field`的关键值对至id等于1的那个节点上。 #### 删除不再需要的数据 清理过期无用的东西有助于维持系统的整洁有序。如果想要移除某篇帖子的话只需简单几行就能搞定: ```python res = es_client.delete(index="test-index", id=1) print(res[&#39;result&#39;]) ``` 这一步骤彻底清除了关联着数字标识符1的那一份材料。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值