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

How to apply filter on search parameter in DSL query

我在elasticsearch中保存了大量的客户数据

我的查询如下

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

我需要过滤掉{country: Germany}

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

我需要过滤掉

{country: Germany}{continent:Europe}

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

{
  "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"
        }
      }
    ]