elasticsearch 7.4 term查询keyword字段和text字段的区别

1. 创建index mapping

PUT my_index
{
  "mappings": {
      "properties": {
        "name": {
          "type": "keyword"
        }
      }
  }
}

2. 添加记录

POST my_index/products
{
  "name":"washing machin"
}

3. 采用term查询记录

GET my_index/_search
{
  "query": {
    "term": {
      "name": "washing"
    }
  }
}

出现查询不到添加的记录。

{
  "took" : 0,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 0,
      "relation" : "eq"
    },
    "max_score" : null,
    "hits" : [ ]
  }
}

原因是,字段为keyword类型,是整个字段建立的索引,term查询的时候,查询条件也是作为整体进行搜索,所以没有和搜索条件name="washing"匹配的记录。

修改查询条件如下:

GET my_index/_search
{
  "query": {
    "term": {
      "name": "washing machin"
    }
  }
}

这样就可以查询到记录了:

{
  "took" : 0,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 1,
      "relation" : "eq"
    },
    "max_score" : 0.18232156,
    "hits" : [      
      {
        "_index" : "my_index",
        "_type" : "_doc",
        "_id" : "1",
        "_score" : 0.18232156,
        "_source" : {
          "name" : "washing machin"
        }
      }
    ]
  }
}

4. 增加一个text字段

PUT my_index/_mapping
{
  "properties": {
      "tag": {
        "type": "text"
      }
  }
}

5. 添加数据

POST my_index/_doc/2
{
  "name":"washing machine",
  "tag":"electric household"
}

6. 执行term查询

POST  /my_index/_search
{
  "query": {
    "term": {
      "tag": "household"
    }
  }
}

查询到添加的记录

{
  "took" : 0,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 1,
      "relation" : "eq"
    },
    "max_score" : 0.2876821,
    "hits" : [
      {
        "_index" : "my_index",
        "_type" : "_doc",
        "_id" : "2",
        "_score" : 0.2876821,
        "_source" : {
          "name" : "washing machine",
          "tag" : "electric household"
        }
      }
    ]
  }
}

从以上查询结果可以验证,term查询在keyword字段和text字段的区别,keyword字段是将整个字段信息作为索引,term查询需要查询条件与keyword内容完全匹配才能查询到。text字段会进行分词建立索引,term查询时,只要term查询条件能够匹配分词后建立的索引即可查询到。

你可能感兴趣的:(大数据技术,elasticsearch,大数据,term)