【问题标题】:How to ignore query constraints when the parameter is empty or null in elastic search弹性搜索中参数为空或null时如何忽略查询约束
【发布时间】:2019-11-09 20:27:04
【问题描述】:

这里是弹性菜鸟,我对弹性搜索索引有以下查询。我尝试根据产品记录的标题过滤记录。

"query" => [
    "bool" => [
        "should" => [
            [
                "nested" => [
                    "path"  => "name",
                    "query" => [
                        "multi_match" => [
                            "query"  => (string) $query, // here the $query can be empty string
                            "fields" => ['name.en', 'name.ar'],
                        ],
                    ],
                ],
            ],
        ],
    ],
];

现在参数$query(请参阅示例代码中的注释部分)可以是空字符串。在那种情况下,现在我得到的结果为零,显然是因为我没有任何标题为空的记录。

我想得到什么

本质上是忽略查询,因为参数为空并返回默认结果集。

我有更多的查询,如类别、标签、评论等......所以即使名称/标题查询为空,我也应该能够根据其他查询进行过滤。但现在如果 name 部分为空,我将得到一个空结果集。

如果需要更多信息,请发表评论

弹性搜索 7

【问题讨论】:

  • 在 PHP 中简单地使用if/else 逻辑怎么样?
  • 我可以,但我正在寻找更多弹性搜索解决方案。
  • 查询 DSL 不是命令式语言,而是声明式语言,因此无法指定任何控制流。
  • Hmm.. 所以从这个意义上说,如果没有匹配到 match_all 的回退,就没有办法这么说?
  • 在 PHP 中使用 if/else 逻辑 :-)

标签: php elasticsearch


【解决方案1】:

matchmulti_match 查询中,如果使用zero_terms_query 选项,则会输入一个空字符串,如下所示:

{
  "query": {
    "bool": {
      "must": [
        {
          "multi_match": {
            "query": "",
            "zero_terms_query": "all",
            "fields": ["name.en", "name.ar"]
          }
        }
      ]
    }
  }
}

match版本:

{
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "name": {
              "query": "",
              "zero_terms_query": "all"
            }
          }
        }
      ]
    }
  }
}

zero terms query

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-11
    • 1970-01-01
    • 2021-07-10
    • 2021-06-29
    • 1970-01-01
    • 2021-09-18
    • 1970-01-01
    • 2019-06-09
    相关资源
    最近更新 更多