如何在DSL查询中对搜索参数应用过滤器

问题描述

我在弹性搜索中保存了庞大的客户数据

我的查询在下面

{"query": {"query_string": {"query": "Mobile"}}}

  • 问题1

我需要过滤掉{country: Germany}

"filter": [ { "term": { "Country.keyword": "Germany" }}]

  • 问题2

我需要过滤掉

{country: Germany}{continent:Europe}

解决方法

添加包含索引数据,搜索查询和搜索结果的工作示例

{
  "item":"mobile are essential","Country":"India","continent":"Europe"
}
{
  "item":"mobile","Country":"Germany","continent":"asia"
}

对于第一个问题need to filter out {country: Germany},您需要将查询包装在布尔查询中:

{
      "query": {
        "bool": {
          "must": {
            "query_string": {
              "query": "Mobile"
            }
          },"filter": {
            "term": {
              "Country.keyword": "Germany"
            }
          }
        }
      }
    }

搜索结果:

"hits": [
      {
        "_index": "stof_64278091","_type": "_doc","_id": "1","_score": 0.15965708,"_source": {
          "item": "mobile","Country": "Germany","continent": "Europe"
        }
      },{
        "_index": "stof_64278091","_id": "3","continent": "asia"
        }
      }
    ]

对于第二个问题,请尝试以下查询:

{
  "query": {
    "bool": {
      "must": {
        "query_string": {
          "query": "Mobile"
        }
      },"filter": [
        {
          "term": {
            "Country.keyword": "Germany"
          }
        },{
          "term": {
            "continent": "Europe"
          }
        }
      ]
    }
  }
}

搜索结果:

"hits": [
      {
        "_index": "stof_64278091","_score": 0.22920428,"continent": "Europe"
        }
      }
    ]