将Elasticsearch数据结果导出为CSV文件

时间:2017-10-11 09:10:26

标签: python python-3.x csv elasticsearch export-to-csv

我想将从查询返回的弹性搜索数据导出到CSV文件。我一直在寻找这样做,但我对此的所有尝试都失败了如何做到这一点。

我的查询如下;

{ "path": " /themedesigner",
    "target": {
        "type": "application",
        "name": "themedesigner"
    },
    "description": "Route for theme designer"
}

有人可以修复此代码以使其工作,请花费数小时才能使其正常工作。

运行时出现的错误如下:

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)

提前谢谢。

1 个答案:

答案 0 :(得分:0)

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