python elasticsearch格式数据

时间:2017-01-30 10:31:24

标签: python json elasticsearch formatting

我使用以下代码从弹性搜索中获取数据,我无法根据我的要求对其进行格式化

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)

输出

{"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"}

但我希望输出像这样:

{"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"}]}

你能帮我解决一下如何做到这一点。

1 个答案:

答案 0 :(得分:2)

这个怎么样?

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)