Below is the code that is grabbing some data from elastic search and exporting that data to a csv file called ‘mycsvfile’.
I want to change the column names so that it is readable by a human.
Below is the 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)
when I run the above query the CSV file data look like below:
DTDT TRDT SPLE SACL RPLE
20170512 12/05/2017 15:39 1001 0 0
20170512 12/05/2017 15:39 1001 0 0
20170908 08/09/2017 02:42 1001 0 0
20170908 08/09/2017 06:30 1001 0 0
As you can see the column names are the same as in the query and I want to give them readable names when the file is being generated.
Could someone show and fix my code up for me to enter column names to the CSV file?
Thank you in advance