python - Elasticsearch 条件

标签 python django elasticsearch

您好,我在 Elasticsearch 中感到困惑。如果未将参数赋给方法,那么如果参数不为空,则代码可以正常工作,我该如何处理该 bool(boolean) 查询。

def elastic_search(category=None):
    client = Elasticsearch(host="localhost", port=9200)
    query_all = {
        'size': 10000,
        'query': {
            "bool": {
                "filter": [
                    {
                        "match": {
                            "category": category
                        }
                    }]
               },
        }
    }
    resp = client.search(
        index="my-index",
        body=query_all
        )
    return resp

最佳答案

如果category为None,则需要使用match_all。只需根据category的值有条件地构建查询即可。
这样的事情应该做

def elastic_search(category=None):
    client = Elasticsearch(host="localhost", port=9200)

    query_all = {
        'size': 10000,
        'query': {}
    }

    if category is None:
        query_all['query']['match_all'] = {}
    else:
        query_all['query']['bool'] = {
             "filter": [
               {
                 "match": {
                   "category": category
                 }
               }
             ]
        }

    resp = client.search(
        index="my-index",
        body=query_all
        )
    return resp

关于python - Elasticsearch 条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63290916/

相关文章:

python - Django 1.8 无法加载 css 模板

php - 如何将数据从 Python 发送到 Android 应用程序

python - Django 模型自动填充外键

elasticsearch - 让 elasticsearch 和 bigquery 协同工作

java - Elasticsearch java批量更新插入异常

python - 从数据采集单元读取数据(测量计算)

python - Linux 错误 : sh: qsub: command not found

python - ImportError: 仅当在 heroku 上部署 django 应用程序时才出现 win32

python - Django DeleteView 不会从数据中删除对象

elasticsearch - Kibana,过滤计数大于或等于 X