es对于每个文档,每个字段都存在数据结构的映射关系的,那这个关系怎么查看呢?
在老版中,查询mapping:
GET /索引名称/_mapping/类型名称
在ES6一个索引只允许一种type,ES7更是弱化了type的概念,官方更是提出在ES8将会移除。。
因此,现在的mapping查询,一般这么查:
GET /索引名称/_mappings
查询product索引的映射:
GET /product/_mappings
{
"product" : {
"mappings" : {
"properties" : {
"desc" : {
"type" : "text",
"fields" : {
"keyword" : {
"type" : "keyword",
"ignore_above" : 256
}
}
},
"name" : {
"type" : "text",
"fields" : {
"keyword" : {
"type" : "keyword",
"ignore_above" : 256
}
}
},
"price" : {
"type" : "long"
},
"tags" : {
"type" : "text",
"fields" : {
"keyword" : {
"type" : "keyword",
"ignore_above" : 256
}
}
}
}
}
}
}
你会发现,我们每个字段都被赋予了类型,然而我们并没有显式的去设置,这是因为ES的自动映射。
当然,如果你想要手动设置也是可以的。
keyword
这里有个细节,发现”text“类型的字段,内部还多了一组:
"fields" : {
"keyword" : {
"type" : "keyword",
"ignore_above" : 256
}
}
这个意思是,系统额外生成一个keyword字段,这个字段的内容是截取text内容的前256位作为这个keyword字段的内容。
举例子来说,在查询时,还可以这样使用类型为text的字段name的内部的keyword字段: 使用”name.keyword“:
GET /product/_search
{
"query": {
"match": {
"name.keyword": "xiaomi erji"
}
}
}
text和keyword的区别
text 类型,当一个字段是要被全文搜索的,比如Email内容、产品描述,应该使用text类型。设置text类型
以后,字段内容会被分析,在生成倒排索引以前,字符串会被分析器分成一个一个词项(会被分词)。text类型的字段
不用于排序,很少用于聚合。
keyword类型适用于索引结构化的字段,比如email地址、主机名、状态码和标签。如果字段需要进行过
滤(比如查找已发布博客中status属性为published的文章)、排序、聚合。keyword类型的字段只能通过精
确值搜索到。
ES中的类型映射
手动创建明确类型的映射
有时候自动映射的类型并不符合我们的预期,那么此时我们需要进行手动注定每个字段的类型。
接下来我们来手动完成创建一个索引:
创建myindex索引
PUT /myindex
{
"settings": {
"index": {
"number_of_shards": "2",
"number_of_replicas": "0"
}
},
"mappings": {
"properties": {
"name": {
"type": "text"
},
"age": {
"type": "integer"
},
"mail": {
"type": "keyword"
},
"hobby": {
"type": "text"
}
}
}
}
查看一下myindex的映射:
GET /myindex/_mappings
发现就是我们指定的类型:
{
"itcast" : {
"myindex" : {
"properties" : {
"age" : {
"type" : "integer"
},
"hobby" : {
"type" : "text"
},
"mail" : {
"type" : "keyword"
},
"name" : {
"type" : "text"
}
}
}
}
}