首页 > 解决方案 > 过滤 elasticsearch 字段(如果存在),否则忽略过滤器

问题描述

我正在尝试过滤两个不同的索引,但在同一个弹性查询中,

我想过滤两个索引上不存在的字段:

第一指数:

label: string,
value: string,
isShowable: boolean

第二个指数:

label: string,
value: string

我想从第二个索引中检索所有项目,并且只从第一个索引中获取可显示的项目。

我在 php 中使用 Elasticsearch DSL。

这是我尝试过的:

Item::search($formattedRequest, function (Client $client, Search $body) {
            $dispensationQuery = new TermQuery("isShowable", true);

            $bool = new BoolQuery();
            $bool->add($dispensationQuery, BoolQuery::SHOULD);

            $body->addQuery($bool);

            return $client->search(
                ['index' => firstIndex . "," . secondIndex, 'body' => $body->toArray()],
            );
        })->get();

但它会过滤我的所有项目,并且不会从第二个指数中检索值。

如何管理?

标签: elasticsearchelasticsearch-dsllaravel-scout

解决方案


您可以使用 should 子句来组合存在和布尔检查。如果任一字段存在或其值为 true,则类似于返回文档

GET index1,index2/_search
{
  "query": {
    "bool": {
      "should": [
        {
          "bool": {
            "must_not": [
              {
                "exists": {
                  "field": "isShowable"
                }
              }
            ]
          }
        },
        {
          "term": {
            "isShowable": {
              "value": true
            }
          }
        }
      ]
    }
  }
}

推荐阅读