elasticsearch 如果字段不存在,则返回null

wmvff8tz  于 2022-11-02  发布在  ElasticSearch
关注(0)|答案(1)|浏览(294)

我正在尝试使用python从elasticsearch API获取所有需要的数据。
但是,每个对象中的数据是不同的。我的意思是:
例如:

hits: [
 "_source": {
   "info": {
      "id": 1234,
      "name": "xyz apt"
      "address": "adsfv"
}},
"_source": {
   "info": {
      "id": 3579,
      "name": "abc apt"
}}, ...

如图所示,在第二个示例中,“address”数据不存在,因此当我通过for循环获取每个数据时,会得到一个错误。

for i in hits: 
   address.append(i['_source']['info']['address'])

那么,当数据不存在时,如何将这样的值置为空呢?

taor4pac

taor4pac1#

无论何时处理一个可能存在也可能不存在的键,都可以使用.get

>>> d = {'a': 1}
>>> d['b']
KeyError
>>> str(d.get('b'))
'None'

.get也接受默认值:

>>> d.get('b', 'something that will be returned if the key is not present')
'something that will be returned if the key is not present'

相关问题