2015-09-21 242 views
0

我有一個ElasticSearch產值是在這種形式從詞典獲取數據列表裏面裏面字典

u'hits': 
     { 
      u'hits': 
       [ 
        { 
         u'_score': 1.0, u'_type': u'timer_data', 
         u'_id': u'AU_uJ1dk4uyHlwrlFlQv', 
         u'_source': { 
          u'std': u'0', u'upper': u'62.688', 
          u'lower': u'62.688', u'count_90': u'1', 
          u'tgt': u'duration', u'grp': u'request', 
          u'sum_90': u'62.688', u'sum': u'62.688', 
          u'median': u'62.688', u'count': u'1', 
          u'mean_90': u'62.688', u'sum_squares': u'3929.7853440000004', 
          u'ns': u'gunicorn', u'act': u'', 
          u'upper_90': u'62.688', u'sum_squares_90': u'3929.7853440000004', 
          u'count_ps': u'0.1', u'@timestamp': u'1442809600000', 
          u'mean': u'62.688' 
         }, 
         u'_index': u'statsd-2015.09.21' 
        } 
       ], 
       u'total': 1, u'max_score': 1.0 
      }, 
      u'_shards': { 
       u'successful': 5, u'failed': 0, u'total': 5 
      }, 
      u'took': 2, u'timed_out': False 
     } 

我想訪問字典裏面u'_source」數據,但不能找到比下列其他任何適當的方式。

anoval = output[u'hits'][u'hits'] 
print type(anoval) 
# print output[u'hits'][u'hits'] 
anoval = anoval[0] 
print type(anoval) 

我想知道是否有任何其他與elasticsearch輸出來作爲字典在Python

回答

1

試試下面的遞歸通過您遍歷數據結構,並返回搜索的價值要做到這一點更有效的方式。

def search_multiDS(search_DS, searchfor): 
    if isinstance(search_DS, dict): 
     if searchfor in search_DS: 
      return search_DS['_source'] 
     else: 
      for key, value in search_DS.items(): 
       return search_multiDS(value, searchfor) 
    if isinstance(search_DS, list): 
     for item in search_DS: 
      return search_multiDS(item, searchfor) 
    else: 
     return None 

print search_multiDS(s, '_source') 
1

您的'_source'字典是在列表中。因此,您必須訪問該列表的第一項以訪問'_source'
so try:

['hits']['hits'][0]['_source']