ElasticSearch7.X学习四--数据类型--keyword datatype

官方文档:https://www.elastic.co/guide/en/elasticsearch/reference/current/keyword.html

概念

keyword类型是索引ID,邮箱地址,hostnames,zip codes,tags,状态码(status codes)等结构化内容。通常是在查询中用来“过滤”,“排序”,“聚合”等操作,并且当keyword类型字段作为查询条件时,是需要精确查找的。如果是需要对多文本查询的话还是使用text类型。
对于numberic类型文档中提到如果是明确需要用到范围查询(range query)的话那还是使用numberic,如果不需要使用范围查询的话就使用keyword,因为term和term-level查询对于keywrod类型来说查询是很高效的。如果不确定是否使用range查询文档中还提到可以使用多类型,如下定义:

  "state" : {
          "type" : "text",
          "fields" : {
            "keyword" : {
              "type" : "keyword",
              "ignore_above" : 256
            }
          }

多类型,不限于numberic,为了查询效率高,text类型也可以,只是我认为多类型肯定会占用更多的内存和存储。上面 "ignore_above"的含义是“state”字段长度不超过256,单位应该是字节,最大值是2147483647。

查询

查询过程中如果是keyword类型的字段,需要将这个keyword加上,不加和加前后对比:

curl -X GET "localhost:9200/bank/_search?pretty" -H 'Content-Type: application/json' -d'
{
  "query": { "bool": {"must":{"term":{"state":"KS"}}} },
  "sort": [
    { "account_number": "asc" }
  ],
  "from": 0,
  "size": 10
}
'

结果是没有数据hit到。加上后:

curl -X GET "localhost:9200/bank/_search?pretty" -H 'Content-Type: application/json' -d'
{
  "query": { "bool": {"must":{"term":{"state.keyword":"KS"}}} },
  "sort": [
    { "account_number": "asc" }
  ],
  "from": 0,
  "size": 10
}
'

结果是:

  {
        "_index" : "bank",
        "_type" : "_doc",
        "_id" : "534",
        "_score" : null,
        "_source" : {
          "account_number" : 534,
          "balance" : 20470,
          "firstname" : "Cristina",
          "lastname" : "Russo",
          "age" : 25,
          "gender" : "F",
          "address" : "500 Highlawn Avenue",
          "employer" : "Cyclonica",
          "email" : "[email protected]",
          "city" : "Gorst",
          "state" : "KS"
        },
        "sort" : [
          534
        ]
      },
      {
        "_index" : "bank",
        "_type" : "_doc",
        "_id" : "561",
        "_score" : null,
        "_source" : {
          "account_number" : 561,
          "balance" : 12370,
          "firstname" : "Sellers",
          "lastname" : "Davis",
          "age" : 30,
          "gender" : "M",
          "address" : "860 Madoc Avenue",
          "employer" : "Isodrive",
          "email" : "[email protected]",
          "city" : "Trail",
          "state" : "KS"
        },
        "sort" : [
          561
        ]
      }
    ]
  }

开始学习的时候就是因为拉下了keyword这个关键字导致查询无结果集。

发布了96 篇原创文章 · 获赞 22 · 访问量 31万+

猜你喜欢

转载自blog.csdn.net/chuan_day/article/details/103768188