简体   繁体   English

如何在弹性搜索中参数为空或空时忽略查询约束

[英]How to ignore query constraints when the parameter is empty or null in elastic search

Elastic Noob here, I have the following query for the elastic search index. Elastic Noob 在这里,我对弹性搜索索引有以下查询。 in which I try to filter the records based on the title of the product record.其中我尝试根据产品记录的标题过滤记录。

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

Now the parameter $query (please see the commented section in the sample code) can be an empty string.现在参数$query (请参阅示例代码中的注释部分)可以是一个空字符串。 In that case, now I am getting zero results, Obviously because I don't have any records with an empty title.在这种情况下,现在我得到的结果为零,显然是因为我没有任何标题为空的记录。

What I would like to get我想得到什么

is to essentially ignore the query since the parameter is empty and to get a default result set back.本质上是忽略查询,因为参数为空,并获取默认结果集。

I have more queries like category, tags, reviews etc... so even when the name/title query is empty, I should be able to filter based on the other queries.我有更多查询,如类别、标签、评论等...所以即使名称/标题查询为空,我也应该能够根据其他查询进行过滤。 But now if the name part is empty I am getting an empty result set.但是现在如果name部分为空,我会得到一个空的结果集。

Please post a comment if more info is needed如果需要更多信息,请发表评论

Elasticsearch 7弹性搜索 7

是的,有Elasticsearch解决方案: 零项查询

In a match or multi_match query an empty string will be ingored if one uses zero_terms_query option, like this:matchmulti_match查询中,如果使用zero_terms_query选项,将使用空字符串,如下所示:

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

or match version:match版本:

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

See zero terms query查看零项查询

Try to change the name.en and name.ar to keyword type. 尝试将name.enname.ar更改为keyword类型。 In ES, only keyword type field is valid for empty string. 在ES中,只有keyword类型字段对空字符串有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM