elasticsearch 的字符串动态映射
环境信息
操作系统:Ubuntu 18.04.2 LTS
elasticsearch:6.7.1
kibana:6.7.1
官网解释
来自官网的解释,如下图,地址是:https://www.elastic.co/guide/en/elasticsearch/reference/current/dynamic-field-mapping.html
官网的解释为:
如果是日期类型,就映射为 date;
如果是数字,就映射为 double 或者 long;
否则就是 text,并且还会带上 keyword 子类型;
映射为 text 好理解,但是带上 keyword 子类型怎么理解呢?应该是达到静态绑定的映射参数 fields 效果,让该字段有两种索引方式,这样可以用 text 类型做全文检索,再用 keyword 类型做聚合和排序;
接下来实战验证:
创建文档
在 Kibana 上执行以下命令,创建索引、类型、一个文档:
PUT book/es/101
{"title":"Elasticsearch IN ACTION","language":"java","author":"Radu Gheorghe","price":58.80,"publish_time":"2018-10-01","description":"本书主要展示如何使用 Elasticsearch 构建可扩展的搜索应用程序。"}
再创建一条:
PUT book/es/102
{"title":"ELK Stack 权威指南 ","language":"java","author":"拉斐尔·酷奇","price":62.40,"publish_time":"2017-05-01","description":"本书涵盖了
Elasticsearch 的许多中高级功能。"}
检查动态映射结果
执行命令 GET book/_mapping 查看动态映射结果,字符串动态映射后,字段类型为 text,但是都有了 fields 参数,里面是 keyword 的子类型:
{
"book" : {
"mappings" : {
"es" : {
"properties" : {
"author" : {
"type" : "text",
"fields" : {
"keyword" : {
"type" : "keyword",
"ignore_above" : 256
}
}
},
"description" : {
"type" : "text",
"fields" : {
"keyword" : {
"type" : "keyword",
"ignore_above" : 256
}
}
},
"language" : {
"type" : "text",
"fields" : {
"keyword" : {
"type" : "keyword",
"ignore_above" : 256
}
}
},
"price" : {
"type" : "float"
},
"publish_time" : {
"type" : "date"
},
"title" : {
"type" : "text",
"fields" : {
"keyword" : {
"type" : "keyword",
"ignore_above" : 256
}
}
}
}
}
}
}
}
验证检索
执行以下检索命令验证检索:
GET book/_search
{
"query": {
"match": {"title":"Elasticsearch"}
}
}
第一条记录都可以搜索到,证明 description 字段已经被分词和索引了;
2. title 字段还有一种索引方式 keyword,也来试试,查 keyword 是要用完整内容做查询条件的,如下:
GET book/_search
{
"query": {
"term": {"title":"Elasticsearch IN ACTION"}
}
}
得到的结果如下,没有记录:
{
"took" : 0,
"timed_out" : false,
"_shards" : {
"total" : 5,
"successful" : 5,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : 0,
"max_score" : null,
"hits" : [ ]
}
}
这是怎么回事呢?对于这种 sub-field 的查询,不能直接使用 title,而是要用 title.keyword,改成如下请求:
GET book/_search
{
"query": {
"term": {"title.keyword":"Elasticsearch IN ACTION"}
}
}
这次顺利查到:
{
"took" : 0,
"timed_out" : false,
"_shards" : {
"total" : 5,
"successful" : 5,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : 1,
"max_score" : 0.2876821,
"hits" : [
{
"_index" : "book",
"_type" : "es",
"_id" : "101",
"_score" : 0.2876821,
"_source" : {
"title" : "Elasticsearch IN ACTION",
"language" : "java",
"author" : "Radu Gheorghe",
"price" : 58.8,
"publish_time" : "2018-10-01",
"description" : "本书主要展示如何使用 Elasticsearch 构建可扩展的搜索应用程序。"
}
}
]
}
}
评论