2017-10-11 9 views
0

내 쿼리에서 반환되는 탄성 검색 데이터를 CSV 파일로 내보내고 싶습니다. 나는 이것을하기 위해 도처에 찾고 있었다. 그러나 이것에 관해 나의 모든 시도는 그것을하는 방법에 실패하고있다.Elasticsearch 데이터 결과를 CSV 파일로 내보내기

내 검색어는 아래에 있습니다.

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) 

누군가가이 코드를 작동하도록 고칠 수 있었습니까? 작동하려면 시간을 보내고 있습니다.

이 실행할 때 내가 점점 오전 오류는 다음과 같습니다 :

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' 

사전에 감사합니다. 역 추적 (마지막으로 가장 최근 통화) : 파일 "파이썬 3.x를을 사용하고 있기 때문에

답변

0

+0

그 문제를 해결하는, 감사하지만 지금은 서로를 점점 메신저 with open('outputfile.tsv', 'wb')wwb 교체 C : /Users/.PyCharmCE2017.2/config/scratches/trtr.py ", 줄 32, col1 = sample ["some "] ["deeply "] ["nested "] ["field "]. ('utf-8') #이 중첩 키 이름을 자신의 것으로 바꿉니다 TypeError : 목록 색인은 정수 또는 슬라이스 여야하며 str이 아니어야합니다 – Rich