从elasticsearch的另一个字段的搜索结果中排除一个字段?

Exclude a field from search results by another field on elasticsearch?

我必须从 Elasticsearch 的搜索结果中删除一个字段。如果 display_detail 为假,我想删除 detail 属性。

文档示例:

{
    "last_name" : "anna",
    "first_name" : "bella",
    "detail" : "descript their hobby",
    "display_detail" : true
},
{
    "last_name" : "anna",
    "first_name" : "michelle",
    "detail" : "another hobby",
    "display_detail" : false
}

查询如下:

indexname=indexname
query = {
         "query_string" : {
              "query" : anna,
              "fields: : ["first_name","last_name"]
          }

}
results = es.search(index=indexname, query=query , source = ["first_name","last_name","detail"])

我的期望:

{
    "last_name" : "anna",
    "first_name" : "bella",
    "detail" : "descript their hobby",
},
{
    "last_name" : "anna",
    "first_name" : "michelle",
}

我得到这样的搜索结果后可以得到上面的结果:

for element in results['hits']['hits']: 
    if element["display_detail"] == "true":
        del element['detail'] 
    json.append(element)

这样处理好吗?或者我有没有机会通过使用弹性查询获得 faster/cleanest 方式?

如果你有一个字典列表,那么你可以使用 pop 从字典中删除项目。

操作方法如下:


ld = [
    {
    "last_name" : "anna",
    "first_name" : "bella",
    "detail" : "descript their hobby",
    "display_detail" : True
    },
    {
    "last_name" : "anna",
    "first_name" : "michelle",
    "detail" : "another hobby",
    "display_detail" : False
    }
]

print('before removing:')
print(ld)


for i in ld:
    if i['display_detail']==False:
        i.pop('detail')

print('after removing:')
print(ld)

结果如下:

before removing:
[{'last_name': 'anna', 'first_name': 'bella', 'detail': 'descript their hobby', 'display_detail': True}, {'last_name': 'anna', 'first_name': 'michelle', 'detail': 'another hobby', 'display_detail': False}]
after removing:
[{'last_name': 'anna', 'first_name': 'bella', 'detail': 'descript their hobby', 'display_detail': True}, {'last_name': 'anna', 'first_name': 'michelle', 'display_detail': False}]

不可能 select/hide 基于条件的字段。

但是您可以 select/hide 使用所有文档中的 fields options or source options 字段

始终建议在客户端以与处理相同的方式处理此类微操作。