首页 > 解决方案 > 在子字段中进行排除(不得)搜索

问题描述

我想找到街道名称中不包含“大”一词的所有城市。

这是我在索引中的项目:

{
  "name":"the big street",
  "city": "NY",
  "count": 2
},
{
  "name":"not big street",
  "city": "AM",
  "count": 43
},
{
  "name":"st42",
  "city": "NY",
  "count": 1687
},
{
  "name":"Anacostia Drive",
  "city": "WASH",
  "count": 1687
},

我需要找到名称不得包含(排除)“大”一词的所有城市。

当我尝试将术语查询与 must_not 一起使用时

{
  "collapse": {
    "field": "city"
  },
  "query": {
    "bool" : {
"must_not" : {
        "term" : {
          "name" : { "big" }
        }
      },
    }
 }
}

我发现城市包括“NY”,到期项目与“st42” - 与“大街道”项目的正确匹配是错误的。

如何解决?

下面的决定很好,但查询可能更复杂,我需要突出显示:

{
  "aggs": {
    "aggs_by_city": {
      "terms": {
        "field": "city.keyword",
        "size": 20
      },
      "aggs": {

        "filter_exclude_count": {
          "filter": { "match" : { "name" : "big"   }}
        },
        "filter_include_count": {
          "filter": { "match" : { "name" : "Anacostia"   }}
        },
        "selector": {
          "bucket_selector": {
            "buckets_path": {
              "exclude_cnt": "filter_exclude_count._count",
              "include_name": "filter_include_count._count"
            },
            "script": "params.exclude_cnt == 0 && params.include_name > 0"
          }
        }
      }
    }
  },
  "size": 0
}

标签: elasticsearchelasticsearch-query

解决方案


看起来你想“找到所有没有街道名称为“大”的街道的城市?

您可以使用aggregation,此解决方案不使用collapse

{
  "aggs": {
    "aggs_by_city": {
      "terms": {
        "field": "city",
        "size": 10
      },
      "aggs": {
        "filter_exclude_count": {
          "filter": { "match" : { "street" : "big"   }}
        },
        "sellector": {
          "bucket_selector": {
            "buckets_path": {
              "exclude_cnt": "filter_exclude_count._count"
            },
            "script": "params.exclude_cnt == 0"
          }
        }
      }
    }
  },
  "size": 0
}
  1. 分组所有城市
  2. 统计街道名称中包含“大”的所有文件
  3. 如果上述计数 == 0,则使用bucket_selectoraggs_by_city选择此聚合

推荐阅读