2017-01-30 5 views
0

ich den Code unten bin mit Daten aus Elasticsearch zu bekommen, und ich bin nicht in der Lage, es zu formatieren, wie pro meine AnforderungPython Elasticsearch Formatdaten

from datetime import datetime 
from elasticsearch import Elasticsearch 
import json 

es = Elasticsearch(hosts=[{'host': "localhost", 'port': "9200"}]) 

res = es.search(index="myindice",size=2, body={"query": {"match_all":{}}}) 
for hit in res['hits']['hits']: 
    v = hit["_source"] 
    q = json.dumps({'name': v['name'],'timestamp': v['@timestamp']}) 
    print(q) 

Und der Ausgang ist

{"timestamp": "2016-09-22T00:28:44.000Z", "name": "1456772324.47092"} 
{"timestamp": "2016-09-22T00:32:16.000Z", "name": "1456772536.57587"} 
{"timestamp": "2016-09-22T00:39:19.000Z", "name": "1456772836.57587"} 

Aber ich Willst du den Ausgang so:

{"mydata":[{"timestamp": "2016-09-22T00:28:44.000Z", "name":"1456772324.47092"}, 
{"timestamp": "2016-09-22T00:32:16.000Z", "name": "1456772536.57587"}, 
{"timestamp": "2016-09-22T00:39:19.000Z", "name": "1456772836.57587"}]} 

Könntest du mir bitte helfen, wie ich das erreichen kann.

Antwort

1

Wie wäre das?

mydata = [] 
for hit in res['hits']['hits']: 
    v = hit["_source"] 
    mydata.append({'name': v['name'],'timestamp': v['@timestamp']}) 
result = {"mydata": mydata} 
q = json.dumps(result) 
print(q) 
+1

Ossom funktioniert erstaunlich – Dython