首页 > 解决方案 > 如何过滤掉复杂查询中的文本字段?

问题描述

我的 UI 上有很多文档过滤器(日期范围、复选框、输入字段),因此查询是动态生成的——这就是我决定创建一个布尔查询并将所有内容推送到must数组的原因。这是我的请求示例:

const {
    body: {
      hits
    }
  } = await esclient.search({
    from: filterQuery.page || 0,
    size: filterQuery.limit || 1000,
    index,
    body: query
  });

复选框(我使用了额外bool.should的内部must数组)和日期范围完美地工作,但术语/匹配过滤根本不起作用:

{
  "query": {
    "bool": {
      "must": [
          {"match": { "issueNumber": "TEST-10" }}
        ]
    }  
  }
} 

上面的查询为我提供了索引中包含“TEST”(及其分数)的所有文档,如果我更改matchterm- 它返回一个空数组。

由于我的字段属于“文本”类型,我也尝试过filter查询 - ES 仍然提供所有带有“测试”字样的文档:

{
  "query": {
    "bool": {
      "must": [
        {
          "bool": {
            "filter": {
              "match": {"issueNumber": "TEST-10"}
            }
          }
        }
      ]
    }
  }
} 

这就是我的命中的样子:

       {
        "_index" : "test_elastic",
        "_type" : "_doc",
        "_id" : "bj213hj2gghg213",
        "_score" : 0.0,
        "_source" : {
          "date" : "2019-11-26T13:27:01.586Z",
          "country" : "US",
          "issueNumber" : "TEST-10",
        }

有人可以给我关于如何在复杂查询中正确过滤文档的输入吗?

这是我的索引的结构:

{
  "test_elasticsearch" : {
    "aliases" : { },
    "mappings" : {
      "properties" : {
        "country" : {
          "type" : "text"
        },
        "date" : {
          "type" : "date"
        },
        "issueNumber" : {
          "type" : "text"
        }
      }
    },
    "settings" : {
      "index" : {
        "creation_date" : "1574759226800",
        "number_of_shards" : "1",
        "number_of_replicas" : "1",
        "uuid" : "PTDsdadasd-ERERER",
        "version" : {
          "created" : "7040299"
        },
        "provided_name" : "logs"
      }
    }
  }
}

标签: javascriptnode.jselasticsearch

解决方案


好的,问题是您的issueNumber字段类型不正确,如果您的目标是对其进行精确搜索,则应该这样keywordtext。对于country. 像这样修改你的映射:

  "properties" : {
    "country" : {
      "type" : "keyword"
    },
    "date" : {
      "type" : "date"
    },
    "issueNumber" : {
      "type" : "keyword"
    }
  }

然后重新索引您的数据,您的查询将起作用。


推荐阅读