python - 弹性搜索条件
问题描述
您好,我对弹性搜索的条件感到困惑。如果参数不为空,代码工作正常如果参数没有提供给方法我如何处理这个布尔查询。
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
解决方案
如果类别为无,您需要使用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
推荐阅读
- javascript - 创建后检索频道 ID
- c# - 尝试使用 C# 中的 HTTPWebRequest 在 Shopify 中创建新产品列表时出错
- c++ - 带有新输入系统的 Unity NullReferenceException 错误
- javascript - 如何使用以前的对象设置文件列表?
- mongodb - 当时间戳在MongoDB中是字符串时在时间戳范围之间选择数据
- angular-cli - Angular 10 - 升级到 Angular 10 后未生成 tsconfig.base.json 文件
- c++ - 如何更改 Visual Studio 中所有项目的默认语言标准。C++
- javascript - history.replaceState() 不起作用,在脚本中
- python - 使用输入文件将字符串转换为浮点数
- c++ - 从函数返回向量