1.dynamic
(1).简介
mapping中的字段类型一旦设定后,禁止直接修改,原因是lucene实现的倒排索引产生后不允许修改,要解决索引结构修改的方式是重新建立新的索引然后重新插入文档数据。mapping字段虽然不允许修改,但是却可以新增,通过dynamic字段进行配置。

(2).dynamic的值及其含义

  • true:默认值,允许新增字段,当文档中包含mapping中不存在的字段时,elasticsearch会自动新增字段,并插入内容
  • false:不允许新增字段,但文档可以正常写入,但不会新建字段以及插入内容
  • strict:文档不能插入mapping中定义以外的字段,否则会报错

(3).案例

PUT /people
{
"settings": {
"number_of_shards": 5,
"number_of_replicas": 1
}
}
PUT /people/_mapping
{
"dynamic": false,
"properties": {
"name": {
"type": "text"
},
"country": {
"type": "keyword"
},
"age": {
"type": "integer"
},
"birthday": {
"type": "date",
"format": "yyyy-MM-dd HH:mm:ss"
},
"description": {
"type": "text"
}
}
}

2.copy_to
(1).简介
将该字段的值复制到目标字段,实现类似_all的作用,复制的内容并不会出现在_source中,只是用来搜索。

(2).案例

PUT /people
{
"settings": {
"number_of_shards": 5,
"number_of_replicas": 1
}
}
PUT /people/_mapping
{
"properties": {
"first_name": {
"type": "text",
"copy_to": "full_name"
},
"last_name": {
"type": "text",
"copy_to": "full_name"
},
"full_name": {
"type": "text"
}
}
}
POST /people/_doc
{
"first_name": "Kobe",
"last_name": "Bryant"
}
POST /people/_search
{
"query": {
"match": {
"full_name": "Kobe"
}
}
}
{
"took" : 470,
"timed_out" : false,
"_shards" : {
"total" : 5,
"successful" : 5,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 1,
"relation" : "eq"
},
"max_score" : 0.2876821,
"hits" : [
{
"_index" : "people",
"_type" : "_doc",
"_id" : "yInBmnsBEsHOdz1Y9crd",
"_score" : 0.2876821,
"_source" : {
"first_name" : "Kobe",
"last_name" : "Bryant"
}
}
]
}
}

3.index
(1).简介
控制当前字段是否索引,默认为true(即文档可被索引),false为不可搜索。当存储在elasticsearch中的敏感信息,如身份证和手机号,不希望被查询时,就可以将该字段的index设置为false。

(2).案例

PUT /people
{
"settings": {
"number_of_shards": 5,
"number_of_replicas": 1
}
}
PUT /people/_mapping
{
"properties": {
"name": {
"type": "text",
"index": false
}
}
}
POST /people/_doc
{
"name": "Kobe Bryant"
}
POST /people/_search
{
"query": {
"match": {
"name": "Kobe"
}
}
}
{
"took" : 8,
"timed_out" : false,
"_shards" : {
"total" : 5,
"successful" : 5,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 0,
"relation" : "eq"
},
"max_score" : null,
"hits" : [ ]
}
}

4.index_options
(1).简介
用于控制倒排索引记录的内容,有如下配置。

  • docs:只记录文档id
  • freqs:记录文档id和词频
  • positions:记录文档id、词频和位置
  • offsets:记录文档id、词频、位置和偏移量
  • text类型默认配置为positions,其它类型默认为docs
  • 记录的内容越多,占用的空间越大

(2).案例

PUT /people
{
"settings": {
"number_of_shards": 5,
"number_of_replicas": 1
}
}
PUT /people/_mapping
{
"properties": {
"name": {
"type": "text",
"index_options": "offsets"
}
}
}

5.null_value
(1).简介
当字段遇到null值时的处理策略,默认为null(即空值),此时会忽略该值,也可以通过设定其它值作为默认值。

(2).案例

PUT /people
{
"settings": {
"number_of_shards": 5,
"number_of_replicas": 1
}
}
PUT /people/_mapping
{
"properties": {
"name": {
"type": "text",
"null_value": "空"
}
}
}