首页 > 解决方案 > 如何在 DSL 查询中对搜索参数应用过滤器

问题描述

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

我的查询如下

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

我需要过滤掉{country: Germany}

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

我需要过滤掉

{country: Germany}{continent:Europe}

标签: elasticsearchdsl

解决方案


添加带有索引数据、搜索查询和搜索结果的工作示例

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

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

{
      "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",
        "_type": "_doc",
        "_id": "3",
        "_score": 0.15965708,
        "_source": {
          "item": "mobile",
          "Country": "Germany",
          "continent": "asia"
        }
      }
    ]

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

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

搜索结果:

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

推荐阅读