将 Elasticsearch 结果导出到 CSV 文件

2024-04-24

我正在尝试将使用以下查询找到的结果导出到桌面上的 CSV 中。

这是我第一次使用 Elasticsearch 和 cURL,所以我对如何做到这一点感到困惑。

from elasticsearch import Elasticsearch

es = Elasticsearch(["9200"])

# Replace the following Query with your own Elastic Search Query
res = es.search(index="search", body=
                {
                    "_source": ["DTDT", "TRDT", "SPLE", "RPLE"],
                    "query": {
                        "bool": {
                            "should": [
                                {"wildcard": {"CN": "TEST1"}}

                            ]
                        }
                    }
}, size=10)

for doc in res['hits']['hits']:
    print(doc)

现在,当我运行此查询时,它会返回 dave 的姓名、姓氏、地址和性别,我想在运行查询时将结果放入桌面上的 csv 中。

我一直在阅读有关如何执行此操作的链接,但我不确定如何使我的查询执行此操作 - (https://docs.python.org/3/library/csv.html https://docs.python.org/3/library/csv.html)

有人可以帮助我并告诉我如何在导出 csv 时转换我的查询吗?

thanks

我得到的输出是 -

{'_index': 'search', '_type': 'trades', '_id': '179299804977823744', '_score': 1.0, '_source': {'DTDT': '20170928', 'SPLE': '1001', 'RPLE': '1001', 'TRDT': '2017-09-28 17:01:19'}}

您可以使用csv模块来写入数据。

根据您给出的输出,我假设您想从中写入数据_source到 csv 文件。

Code :

from elasticsearch import Elasticsearch
import csv

es = Elasticsearch(["9200"])

# Replace the following Query with your own Elastic Search Query
res = es.search(index="search", body=
                {
                    "_source": ["DTDT", "TRDT", "SPLE", "RPLE"],
                    "query": {
                        "bool": {
                            "should": [
                                {"wildcard": {"CN": "TEST1"}}

                            ]
                        }
                    }
}, size=10)



with open('mycsvfile.csv', 'w') as f:  # Just use 'w' mode in 3.x
    header_present  = False
    for doc in res['hits']['hits']:
        my_dict = doc['_source'] 
        if not header_present:
            w = csv.DictWriter(f, my_dict.keys())
            w.writeheader()
            header_present = True


        w.writerow(my_dict)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将 Elasticsearch 结果导出到 CSV 文件 的相关文章

  • 如何使用Python3将ruamel.yaml转换为dict?

    我想要一个dict or OrderedDict from ruamel yaml 我正在使用 Python 3 8 如果有帮助的话 很乐意切换到 3 9 from ruamel yaml import YAML from collecti
  • Python:合并嵌套列表

    初学者在这里 我有 2 个要合并的嵌套列表 list1 a b c d e f g h list2 p q r s t u v w 我正在寻找的输出是 list3 a p q b c r s d e t f g h u v w 这可以在没有
  • Bokeh 相当于 matplotlib 子图

    我正在寻找一种方法来创建包含多个子图的绘图 例如 fig ax0 ax1 plt subplots nrows 2 sharex True 可以在 matplotlib 中完成 然后可以通过以下方式解决ax0 and ax1 有没有办法在
  • Keras AttributeError:“顺序”对象没有属性“predict_classes”

    我试图按照本指南找到模型性能指标 F1 分数 准确性 召回率 https machinelearningmastery com how to calculate precision recall f1 and more for deep l
  • Python - 重写 print()

    我正在使用 mod wsgi 想知道是否可以覆盖 print 命令 因为它没用 这样做是行不通的 print myPrintFunction 因为这是一个语法错误 Print 不是 Python 2 x 中的函数 因此这不能直接实现 但是
  • 如何从numpy数组中获取两个最小值

    我想从数组中取出两个最小值x 但是当我使用np where A B np where x x min 0 1 我收到此错误 ValueError 需要超过 1 个值才能解压 我该如何修复这个错误 我需要在数组中按升序排列数字吗 您可以使用n
  • 对seaborn图中的分类x轴进行排序

    我正在尝试使用 seaborn 散点图绘制数据框中前 30 的值 如下所示 同一图的可重现代码 import seaborn as sns df sns load dataset iris function to return top 30
  • 读取 JSON 文件并将其漂亮打印到另一个文件

    我有一个复杂 嵌套 的 json 文本文件 它是文本文件中的一长行 有什么方法可以读取文件 在 python 中 并将 json 缩进 漂亮地打印到新的文本文件中吗 使用读取文件json load 并使用json dump 在指定缩进值时将
  • Pandas 无法读取使用 h5py 创建的 hdf5 文件

    当我尝试读取使用 h5py 创建的 HDF5 格式文件时 出现 pandas 错误 我想知道我是否只是做错了什么 import h5py import numpy as np import pandas as pd h5 file h5py
  • 向 list.extend() 传递不可迭代对象

    我正在创建一个公共方法来允许调用者将值写入设备 例如将其称为 write vals 由于这些值将实时输入 因此我希望通过允许用户输入列表或单个值来简化用户的生活 具体取决于他们需要写入的值的数量 例如 write to device 1 2
  • 使用多索引列对多列求和

    我有一个从数据透视表创建的数据框 看起来类似于 import pandas as pd d company1 False Negative April 2012 112 0 April 2013 370 0 April 2014 499 0
  • curl 在命令行中工作正常,但在 php 中不行

    我使用curl 从 PHP 中检索 url 的内容 它适用于大多数 url 但对于某些 url 它只返回一个空字符串 从命令行 卷曲 此类 url 效果很好 这是我运行curl的方式 curl session curl init site
  • 将 csv 写入谷歌云存储

    我试图了解如何将多行 csv 文件写入谷歌云存储 我只是没有遵循文档 https googlecloudplatform github io google cloud python stable storage blobs html hig
  • 是否可以将 SpaCy 安装到 Raspberry Pi 4 Raspbian Buster

    我一整天都在安装 SpaCy sudo pip install U spacy Looking in indexes https pypi org simple https www piwheels org simple Collectin
  • 是否可以使用seaborn 进行“缩放插图”?

    这个例子 https matplotlib org examples pylab examples axes demo html来自 matplotlib 的展示了如何进行插图 不过我正在使用seaborn 特别是kdeplot sns k
  • 在 matplotlib 中添加新的导航模式

    我正在编写一个 wx matplotlib 应用程序 并且在向 matplotlib 导航工具栏添加新工具时遇到相当大的困难 基本上我想添加选择工具 选取框 套索等 以切换受控子图的鼠标模式 到目前为止 我还没有找到任何功能可以让我轻松地做
  • 从 C++ 检索 Python 类型

    这个问题实际上是以下两个问题的延伸 如何在 Python 中实现 C 类 以供 C 调用 https stackoverflow com questions 9040669 how can i implement a c class in
  • Python二进制数据读取

    urllib2 请求接收二进制响应 如下所示 00 00 00 01 00 04 41 4D 54 44 00 00 00 00 02 41 97 33 33 41 99 5C 29 41 90 3D 71 41 91 D7 0A 47 0
  • Python 装饰器只是语法糖? [复制]

    这个问题在这里已经有答案了 可能的重复 了解 Python 装饰器 https stackoverflow com questions 739654 understanding python decorators 我对使用 Python 装
  • Python 调度一个作业,每个工作日开始,每小时运行一次

    我目前有一个示例代码定义为 import schedule import time def job t print I m working t return schedule every day at 01 00 do job It is

随机推荐