如何使 urlib return 成为 python 中的数组 - 解析调用 elasticsearch 的结果?

How to make urlib return an array in python - Parse the results of a call to elasticsearch?

例如,我想按州聚合,但下面的returns数据类型是字符串而不是数组。 我如何编写 return 数组的 Elasticsearch 术语聚合?

我的部分代码:

import urllib2 as urllib
import json
query = {
    "size":0,
  "aggs":{
     "states":{
        "terms":{
           "field":"states.raw",
            "size":8
        }
     }
  }

}

query = json.dumps(query )
headers = {'Content-type': 'application/json'}
req = urllib2.Request(url, query , headers)
out = urllib2.urlopen(req)
rs = out.read()

print type(rs )

return :

{
   "took": 1,
   "timed_out": false,
   "_shards": {
      "total": 1,
      "successful": 1,
      "failed": 0
   },
   "hits": {
      "total": 2,
      "max_score": 0,
      "hits": []
   },
   "aggregations": {
      "states": {
         "doc_count_error_upper_bound": 0,
         "sum_other_doc_count": 0,
         "buckets": [
            {
               "key": "New York",
               "doc_count": 200
            },
            {
               "key": "California",
               "doc_count": 10
            },
            {
               "key": "New Jersey",
               "doc_count": 10
            },
            {
               "key": "North Carolina",
               "doc_count": 1802
            },
            {
               "key": "North Dakota",
               "doc_count": 125
            }
         ]
      }
   }
}

我尝试通过 rs[[=​​25=]]['states']['buckets'][0]['key'] 获取 return 数据 但收到错误消息

"TypeError: string indices must be integers, not str"

我发现return数据类型是字符串,如何让return数据是数组?

运行

import json 
... 
rs = json.loads(rs)

那么 rs 将成为您使用 s['aggregations']['states']['buckets'][0]['key']

访问的对象

但是,建议您使用 python 客户端进行 elasticsearch 而不是编写您自己的客户端,因为后者已经处理了您正在寻找的内容等。查看我的回答 以获取有关如何使用 elasticsearch-py 运行 查询的示例。

这里是 elasticsearch-py 文档的link: