将Elasticsearch数据结果导出到CSV文件 [英] Export Elasticsearch data results into a CSV file

查看:1087
本文介绍了将Elasticsearch数据结果导出到CSV文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将查询返回的弹性搜索数据导出到CSV文件.我一直在到处寻找做到这一点的方法,但是我对此的所有尝试都没有做到.

I would like to export my elastic search data that is being returned from my query to a CSV file. I have been looking everywhere to do this but all my attemps on this is failing on how to do it.

我的查询在下面;

import elasticsearch
import unicodedata
import csv

es = elasticsearch.Elasticsearch(["9200"])
# this returns up to 100 rows, adjust to your needs

res = es.search(index="search", body=
{
    "_source": ["CN", "NCR", "TRDT"],

    "query": {
                        "bool": {
                            "should": [
                                {"wildcard": {
                                        "CN": "TEST*"
                                    }
                                }]
                        }
                    }},size=10)

sample = res['hits']['hits']

# then open a csv file, and loop through the results, writing to the csv
with open('outputfile.tsv', 'wb') as csvfile:

    filewriter = csv.writer(csvfile, delimiter='\t',  # we use TAB delimited, to handle cases where freeform text may have a comma
                        quotechar='|', quoting=csv.QUOTE_MINIMAL)
    # create column header row
    filewriter.writerow(["CN", "NCR", "TRDT"])    #change the column labels here
    # fill columns 1, 2, 3 with your data
    col1 = hit["some"]["deeply"]["nested"]["field"].decode('utf-8')  #replace these nested key names with your own
    col1 = col1.replace('\n', ' ')
    # col2 = , col3 = , etc...
    for hit in sample:
        filewriter.writerow(col1)

有人可以修复此代码以使其正常工作吗,为此花了几个小时才能使其正常工作.

could someone fix this code up for it to work please, been spending hours on this to make it work.

运行此程序时出现的错误如下:

the error i am getting when running this is below:

Traceback (most recent call last):
  File "C:/Users/.PyCharmCE2017.2/config/scratches/trtr.py", line 30, in <module>
    filewriter.writerow(["CN", "NCR", "TRDT"])  # change the column labels here
TypeError: a bytes-like object is required, not 'str'

先谢谢您

推荐答案

with open('outputfile.tsv', 'wb')中用w替换wb,因为您使用的是Python 3.x

Replace wb with w in with open('outputfile.tsv', 'wb') since you are using Python 3.x

这篇关于将Elasticsearch数据结果导出到CSV文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆