一、简介
在Elasticsearch7.0之前,我们将每个文档(document)存储在索引(index)中,并分配一个映射类型。映射类型用于标识索引的文档或实体的类型。举例说明:在一个 demoIndex 索引中,可能设置 user 类型和 info 类型。在 user 类型中可能存在username、age、sex等字段,info 中可能存在username、password、createtime等字段。我们在检索的时候,在url中可以同时指定检索的type进行查询。GET demoIndex/user,info/_search
但是,在Elasticsearch7.0以后摒弃了mapping中type的设置。例如,我们如果想通过如下方式指定doc的字段属性时,就会抛出异常信息
{
"mappings":{
"doc":{
"properties":{
"title":{
"type":"text",
"similarity":"BM25"
}
}
}
}
}
异常信息如下:
大致意思就是无法解析doc
{"error":{"root_cause":[{"type":"mapper_parsing_exception","reason":"Root mapping definition has unsupported parameters: [doc : {properties={title={similarity=BM25, type=text}}}]"}],"type":"mapper_parsing_exception","reason":"Failed to parse mapping [_doc]: Root mapping definition has unsupported parameters: [doc : {properties={title={similarity=BM25, type=text}}}]","caused_by":{"type":"mapper_parsing_exception","reason":"Root mapping definition has unsupported parameters: [doc : {properties={title={similarity=BM25, type=text}}}]"}},"status":400}
通常将ElasticSearch与数据库类比,比如将index看作数据库,type看作数据库表,id看作表结构中的主键。但是,两者的内部机制却有不同。在同一个数据库中,不同的表的字段可以名称相同,类型不同,但是在ES中,由于在不同映射类型中具有相同名称的字段在内部由相同的Lucene字段支持,因此在相同的索引中,如果给不同type设置相同filed,但是filed的属性不同的话,在操作比如删除时,就可能会删除失败。除此之外,存储在同一索引中具有很少或没有共同字段的不同实体会导致数据稀疏,并影响Lucene有效压缩文档的能力。因此在ES7中,废除了mapping types 的设置。在7.0到8.0版本之间,我们可以通过include_type_name=false
指定是否使用mapping types。(7.0默认是true,7.0~8.0之间默认是false。true 开启,false关闭)
举例说明:
PUT index?include_type_name=false
{
"mappings": {
"properties": {
"foo": {
"type": "keyword"
}
}
}
}
二、ES7中mapping设置
- 每一种类型的document设置一个index
比如上面举的例子,将user和info单独设置成两个index,而不是将他们两个放到同一个index中。在ES的indices中,index之间是相互独立的,因此对于里面的字段将不会引起冲突。这样主要包含两个好处
(1)数据更加稠密,有利于lucene对数据进行压缩
(2)因为同一索引中的所有文档都表示一个实体,用于在全文搜索中得分的统计术语更可能准确
- Index APIs
方式一:映射类型直接设置在mappings下,不需要type的名称
PUT index
{
"mappings": {
"properties": {
"foo": {
"type": "keyword"
}
}
}
}
方式二:在url中加上_mappings
PUT index/_mappings
"properties": {
"bar": {
"type": "text"
}
}
}
- Document APIs
ES7.0中必须通过{index}/_doc 来自动创建id,或通过{index}/_doc/{id}指定id
PUT index/_doc/1
{
"foo": "baz"
}
类似的 get 和 delete apis 使用{index}/_doc/{id}
GET index/_doc/1