python 如何将 Elasticsearch 查询写入 elasticsearch-dsl

How to write Elasticsearch query into elasticsearch-dsl in python

我正在尝试使用 Python 3.7 中的 elasticsearch-dsl 库向 Elasticsearch 编写查询。

我想我已经写完了其中的大部分内容,但我对 "exist" 子句有疑问。

这是我要翻译的查询:

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

这是我目前所拥有的:

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

我希望查询 运行 正确,但我目前收到此错误:

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

对于有同样问题的人,我是这样解决的:

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