将Elasticsearch结果导出到CSV文件 [英] Export Elasticsearch results into a CSV file
问题描述
我正在尝试将使用以下查询找到的结果导出到桌面上的CSV中。
I am trying to export the results that is found using the below query into a CSV on my desktop.
这是我第一次使用Elasticsearch和cURL,因此我
This is my first time using Elasticsearch and cURL so i am confused on how to do this.
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)
现在当我运行此查询时,它返回名称,姓氏,地址和ge nder for dave,我想在运行查询时将结果放入桌面上的csv中。
right now when i run this query it returns the name, lastname, address and gender for dave and i want to put the results into a csv on my desktop when i run the query.
我一直在阅读此链接,了解如何操作不知道如何让我的查询执行此操作-( https://docs.python.org /3/library/csv.html )
i have been reading this link on how to do it but im not sure how to make my query do this - (https://docs.python.org/3/library/csv.html)
有人可以帮助我,向我展示如何在导出CSV请转换我的查询!
could someone help and show me how to convert my query in exporting a csv PLEASE!
谢谢
我得到的输出是-
{'_index': 'search', '_type': 'trades', '_id': '179299804977823744', '_score': 1.0, '_source': {'DTDT': '20170928', 'SPLE': '1001', 'RPLE': '1001', 'TRDT': '2017-09-28 17:01:19'}}
推荐答案
您可以使用csv模块写入数据。
You can use csv module to write data.
从输出您已给出,我假设您想将数据从 _source
写入csv文件。
From the output you have given, I am assuming that you want to write data from _source
to csv file.
代码:
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)
这篇关于将Elasticsearch结果导出到CSV文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!