简体   繁体   中英

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

I have to delete a field from search results in Elasticsearch. I want to remove the detail property if display_detail is False.

the documents example:

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

this is the query looks like:

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"])

what I expect:

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

I can get the results above after get the search results like this:

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

is this a good way to deal with it? or is there any chance I can get the faster/cleanest way by using elastic query?

It is not possible to select/hide fields on a condition based.

However you can select/hide fields using fields options or source options from all the documents

It's always recommended to handle such micro operations on the client end the same way you handled.

If you have a list of dicts then you can remove items from the dicts with pop.

Here is how to do it:


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)

And here is the result:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM