0

I'm trying to write a query to Elasticsearch using the elasticsearch-dsl library in Python 3.7.

I think I managed to write most of it but I'm having an issue with an "exist" clause.

This is the query I want to translate:

            {
                "query": {
                    "constant_score": {
                        "filter": {
                            "bool": {
                                "must": { 
                                    "term": { "locale": "$locale" }
                                },
                                "must_not": {
                                    "term": { "blacklist_country": "$country_code" }
                                },
                                "should": [
                                { "term": { "whitelist_country": "$country_code" } },
                                { "bool": {
                                    "must_not": {
                                        "exists": { "field": "whitelist_country" }
                                    }
                                }}
                                ]
                            }
                        }
                    }
                }
            }

And this is what I have so far:

q = Q('constant_score',
            filter={Q('bool',
                must=[Q('term', locale=locale)],
                must_not=[Q('term', blacklist_country=country_code)],
                should=[Q('term', whitelist_country=country_code),
                        Q('bool',
                            must_not=[Q('exists', field='whitelist_country')]
                        )
                       ]
                    )}
            )

I expect the query to run properly but I am getting currently this error:

...
must_not=[Q('exists', field='whitelist_country')]
TypeError: unhashable type: 'Bool'

1 Answer 1

1

For anyone with the same issue, I solved it like this:

search = Search(using=client_es, index="articles") \
            .query('constant_score', filter=Q('bool',
                must=Q('term', locale=locale),
                must_not=Q('term', blacklist_country=country_code),
                should=[Q('term', whitelist_country=country_code),
                        Q('bool',
                            must_not=Q('exists', field='whitelist_country')
                        )
                       ]
                    ))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.