首页 > 解决方案 > 弹性搜索条件

问题描述

您好,我对弹性搜索的条件感到困惑。如果参数不为空,代码工作正常如果参数没有提供给方法我如何处理这个布尔查询。

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

标签: pythondjangoelasticsearch

解决方案


如果类别为无,您需要使用match_all...只需根据类别的值有条件地构建您的查询。

这样的事情应该做

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

推荐阅读