Elasticsearch数据导出Excel Python实现

本文介绍了一种将Elasticsearch中的数据导出至Excel的方法,通过Python编程实现,涉及Elasticsearch数据检索、字段映射解析及Excel文件写入等关键技术。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

依赖环境: 

pip install elasticsearch openpyxl

代码如下:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Author  : QC
# @Date    : 2018/12/15 11:08
# @desc    : 导出es指定index, type的数据到excel
from elasticsearch import Elasticsearch
from elasticsearch import helpers
import openpyxl


class EsToExcel(object):
    def __init__(self, es_host, index, type, file_name):
        """
        :param es_host: es连接地址 例: 127.0.0.1:9200
        :param index: 索引名
        :param type: type名
        :param file_name: 导出文件名
        """
        self.es = Elasticsearch([es_host])
        self.index = index
        self.type = type
        self.file_name = file_name
        self.item_list = []

    def get_field(self):
        """
        获取字段信息
        :return: 字段信息
        """
        field_list = list(self.es.indices.get_mapping(index=self.index, doc_type=self.type)
                          [self.index]['mappings'][self.type]['properties'])
        return field_list

    def get_data(self):
        """
        获取索引下所有数据
        :return: 数据纪录
        """
        query = {
            "query": {
                "match_all": {

                }
            }
        }
        scanResp = helpers.scan(client=self.es, query=query, scroll="5m", index=self.index, doc_type=self.type,
                                request_timeout=100)
        for resp in scanResp:
            item = resp['_source']
            yield item

    def deal_data(self, item, field_list):
        """
        :param item: es查询出的数据纪录
        :param field_list: 对应的字段信息
        :return: 处理好的数据纪录
        """
        new_item = [str(item.get(field, '')) for field in field_list]
        return new_item

    def write_excel(self, item_list, style):
        """
        写入Excel
        :param item_list: 数据集
        :param style: 表头信息
        :return:
        """
        f = openpyxl.Workbook()
        sheet1 = f.active
        for index, i in enumerate(style):
            # openpyxl生成xlsx文件,行列从1开始
            sheet1.cell(row=1, column=index + 1, value=i)
        for row, item in enumerate(item_list):
            try:
                for index, i in enumerate(item):
                    # openpyxl生成xlsx文件,行列从1开始
                    sheet1.cell(row=row + 2, column=index + 1, value=i)
            except Exception as e:
                print(e)

        f.save('{}.xlsx'.format(self.file_name))
        print('{}数据导出完成'.format(self.file_name))

    def start(self):
        """运行主函数"""
        field_list = self.get_field()
        for item in self.get_data():
            new_item = self.deal_data(item, field_list)
            self.item_list.append(new_item)
        self.write_excel(self.item_list, field_list)


if __name__ == '__main__':
    export = EsToExcel(es_host='127.0.0.1', index='**', type='**', file_name='**')
    export.start()

 

### es_data_export 的使用方法与下载 es_data_export 是一个用于从 Elasticsearch 导出数据的开源工具,支持多种导出格式,如 CSV、Excel 和 PDF,旨在简化数据导出流程[^1]。以下是关于 es_data_export 的使用方法和下载信息: #### 下载与安装 1. **获取项目** 可以通过访问该项目的开源平台(如 GitHub 或 GitLab)获取源码并进行安装。通常,使用 `git clone` 命令下载项目: ```bash git clone https://github.com/xxx/es_data_export.git ``` 2. **安装依赖** 项目通常基于 Python 开发,因此需要安装必要的依赖库。使用 `pip` 安装依赖: ```bash pip install -r requirements.txt ``` 3. **配置 Elasticsearch 连接** 在配置文件中设置 Elasticsearch 的连接信息,例如主机地址、端口、认证信息等。 #### 使用方法 1. **导出数据** 运行主程序并指定导出格式(如 CSV、Excel 或 PDF): ```bash python es_data_export.py --format=csv --index=index_name --output=output_file.csv ``` 其中,`--format` 指定导出格式,`--index` 指定 Elasticsearch 索引,`--output` 指定输出文件路径。 2. **支持的导出格式** - **CSV**:适用于表格数据,便于在 Excel数据分析工具中打开。 - **Excel**:支持多表导出,适合复杂的数据结构。 - **PDF**:适用于需要生成报告的场景。 3. **高级功能** - **数据过滤**:通过查询语句指定导出数据的范围。 - **定时任务**:可结合系统定时任务工具(如 cron)实现定期导出数据。 #### 其他相关工具 除了 es_data_export,还可以使用其他工具实现 Elasticsearch 数据导出- **elasticsearch-dump**:适用于导出为 JSON、NDJSON 或原始数据格式。命令如下: ```bash elasticdump --input=http://localhost:9200/index_name --output=data.json --type=data ``` #### 优势 es_data_export 的优势在于其支持多种导出格式,简化了数据导出流程,适合需要将数据用于进一步分析和处理的场景。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值