Home > database >  Exclude a field from search results by another field on elasticsearch?
Exclude a field from search results by another field on elasticsearch?

Time:03-23

I want to remove 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"])

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?

CodePudding user response:

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" : True
    }
]

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


for i in ld:
    i.pop('display_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': True}]
after removing:
[{'last_name': 'anna', 'first_name': 'bella', 'detail': 'descript their hobby'}, {'last_name': 'anna', 'first_name': 'michelle', 'detail': 'another hobby'}]

CodePudding user response:

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.

  • Related