首先随意往ES插一条数据:

put my_index/_doc/1
{
  "name": "李星云"
}

查看ES自动生成的mapping,name是text类型,其下还有keyword子类型,且"ignore_above" : 256

GET /my_index/_mapping

name定义如下:
"properties" : {
  "name" : {
    "type" : "text",
    "fields" : {
      "keyword" : {
        "type" : "keyword",
        "ignore_above" : 256
      }
    }
  }
}

对于keyword类型, 可设置ignore_above限定字符长度。超过 ignore_above 的字符会被存储,但不会被倒排索引。比如ignore_above=4,”abc“,”abcd“,”abcde“都能存进ES,但是不能根据”abcde“检索到数据。

【1】创建一个keyword类型的字段,ignore_above=4

PUT test_index
{
  "mappings": {
    "_doc": {
      "properties": {
        "message": {
          "type": "keyword",
          "ignore_above": 4
        }
      }
    }
  }
}

【2】向索引插入3条数据:

PUT /test_index/_doc/1
{
  "message": "abc"
}

PUT /test_index/_doc/2
{
  "message": "abcd"
}

PUT /test_index/_doc/3
{
  "message": "abcde"
}

此时ES倒排索引是:

词项文档ID
abc1
abcd2

【3】根据message进行terms聚合

GET /test_index/_search
{
  "size": 0, 
  "aggs": {
    "term_message": {
      "terms": {
        "field": "message",
        "size": 10
      }
    }
  }
}

返回结果:

{
  "took" : 2,
  "timed_out" : false,
  "_shards" : {
    "total" : 5,
    "successful" : 5,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : 3,
    "max_score" : 1.0,
    "hits" : [
      {
        "_index" : "test_index",
        "_type" : "_doc",
        "_id" : "2",
        "_score" : 1.0,
        "_source" : {
          "message" : "abcd"
        }
      },
      {
        "_index" : "test_index",
        "_type" : "_doc",
        "_id" : "1",
        "_score" : 1.0,
        "_source" : {
          "message" : "abc"
        }
      },
      {
        "_index" : "test_index",
        "_type" : "_doc",
        "_id" : "3",
        "_score" : 1.0,
        "_source" : {
          "message" : "abcde"
        }
      }
    ]
  },
  "aggregations" : {
    "term_message" : {
      "doc_count_error_upper_bound" : 0,
      "sum_other_doc_count" : 0,
      "buckets" : [#注意这分组里没有”abcde“
        {
          "key" : "abc",
          "doc_count" : 1
        },
        {
          "key" : "abcd",
          "doc_count" : 1
        }
      ]
    }
  }
}

【4】根据”abcde“进行term精确查询,结果为空

GET /test_index/_search
{
  "query": {
    "term": {
      "message": "abcde"
    }
  }
}

然后结果:
  "hits" : {
    "total" : 0,
    "max_score" : null,
    "hits" : [ ]
  }

通过上面结果能知道”abcde“已经存入ES,也可以搜索出来,但是不存在词项”abcde“,不能根据”abcde“作为词项进行检索。
对于已存在的keyword字段,其ignore_above子属性可以修改,但只对新数据有效。

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐