【ElasticSearch】精确匹配text字段 用match加.keyword 或 term

【ElasticSearch】精确匹配text字段 用match加.keyword 或 term


1.错误示范

由于记忆混淆,记成了使用match_phrase对text字段精确匹配。

#测试match_phrase
GET /test/external/_search
{
  "query":{
    "bool": {
      "must": [
        {
          "match_phrase": {
            "nodealias": "92新增"
          }
        }
      ]
    }
  }
}

结果

{
  "took" : 0,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 1,
      "relation" : "eq"
    },
    "max_score" : 3.7249355,
    "hits" : [
      {
        "_index" : "test",
        "_type" : "external",
        "_id" : "EcTGtHsBO1AHMH7HW",
        "_score" : 3.7249355,
        "_source" : {
          "key_id" : "url_http_18536276217",
          "nodealias" : "92新增app配置",
          "taskFinishTime" : "1630825478282",
          "result" : {
            "http_request" : {
              "responseTime" : 89.0
            }
          }
        }
      }
    ]
  }
}

2.使用match字段+.keyword

GET /test/external/_search
{
  "query":{
    "bool": {
      "must": [
        {
          "match": {
            "nodealias.keyword": "92新增app配置"
          }
        }
      ]
    }
  }
}

结果

{
  "took" : 0,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 1,
      "relation" : "eq"
    },
    "max_score" : 1.9924302,
    "hits" : [
      {
        "_index" : "test",
        "_type" : "external",
        "_id" : "EcTGtHsBO1AHMH7HW",
        "_score" : 1.9924302,
        "_source" : {
          "key_id" : "url_http_18536276217",
          "nodealias" : "92新增app配置",
          "taskFinishTime" : "1630825478282",
          "result" : {
            "http_request" : {
              "responseTime" : 89.0
            }
          }
        }
      }
    ]
  }
}

3.将字段设为keyword类型后,就可以使用term精确匹配text字段

可以看到key_id是keyword类型的:


GET /test/external/_search
{
  "query":{
    "bool": {
      "must": [
        {
          "term": {
            "key_id": "url_http_18536276217"
          }
        }
      ]
    }
  }
}

结果

{
  "took" : 0,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 1,
      "relation" : "eq"
    },
    "max_score" : 1.9924302,
    "hits" : [
      {
        "_index" : "test",
        "_type" : "external",
        "_id" : "EcTGtHsBO1AHMH7HW",
        "_score" : 1.9924302,
        "_source" : {
          "key_id" : "url_http_18536276217",
          "nodealias" : "92新增app配置",
          "taskFinishTime" : "1630825478282",
          "result" : {
            "http_request" : {
              "responseTime" : 89.0
            }
          }
        }
      }
    ]
  }
}
原文地址:https://www.cnblogs.com/musecho/p/15354576.html