Mapping
mapping中的字段类型一旦设置,禁止直接修改,因为 lucene实现的倒排索引生成后不允许修改,应该重新建立新的索引,然后做reindex操作。
1.dynamic
但是可以新增字段,通过 dynamic 参数来控制字段的新增,这个参数的值如下:
- true:默认值,表示允许选自动新增字段
- false:不允许自动新增字段,但是文档可以正常写入,但无法对字段进行查询等操作
- strict:严格模式,文档不能写入,报错
2.mappings
mappings 字段可以不用添加,会根据用户提交的数据自动生成,且为keyword.
3. index
index参数作用是控制当前字段是否被索引,默认为true,false表示不记录,即不可被搜索。
4.Dynamic Templates
Dynamic Templates 意为 动态模板,它的作用是允许根据es自动识别的数据类型、字段名等来动态设定字段类型。
可以实现的效果如下:
- 所有字符串类型都设置为keyword类型,即默认不分词
- 所有以message开头的字段都设置为text类型,即分词
- 所有以long_开头的字段都设置为long类型
- 所有自动匹配为double类型的都设定为float类型,以节省空间
创建动态模板类型的索引,put上来的文档 name 是个string类型,那么他的type就被设置为keytype。
Mapping 建议
一般步骤
- 写一条文档到es的临时索引中,获取es自动生成的mapping
- 修改第一步得到的mapping,自定义相关配置
- 使用第2步的mapping创建市级的索引
例如
假设我得到了需要存入es的文档,首先将文档写入临时的index中:
不用创建索引,直接复制代码
PUT test_index/doc/1
{
"referre": "-",
"response_code": "200",
"remote_ip": "172.0.0.1",
"method": "POST",
"username": "-",
"http_version": "1.1",
"body_sent": {
"bytes": "0"
},
"url": "/helloworld"
}
然后查看es自动生成的mapping:
GET test_index/_mapping
复制自动生成的mapping规则,进行简要修改创建。现在希望将bytes设置为整型,url设置为text类型,其他都使用keyword
PUT product_index
{
"mappings": {
"doc": {
"properties": {
"body_sent": {
"properties": {
"bytes": {
"type": "long"
}
}
},
"http_version": {
"type": "keyword"
},
"method": {
"type": "keyword"
},
"referre": {
"type": "keyword"
},
"remote_ip": {
"type": "keyword"
},
"response_code": {
"type": "keyword"
},
"url": {
"type": "text"
},
"username": {
"type": "keyword"
}
}
}
}
}
增
#创建test_es索引,主分片1 副分片1
PUT /person
{
"settings": {
"number_of_shards" : 1,
"number_of_replicas" : 0
},
"mappings": {
"doc": {
"properties": {
"id": {
"type": "keyword",
"index":true
},
"name": {
"type": "keyword",
"index":true
}
}
}
}
}
#添加一条数据,随机id
POST /person/_doc/
{
"id":"999",
"name":"cici"
}
#添加一条数据指定id
POST /person/_doc/1
{
"id":"888",
"name":"xixi"
}
查
#查看所有索引
GET _cat/indices
#查看索引mapping
GET person/_mapping
# 查看person索引数据
GET person/_search/
#通过Id 查询一条数据
PUT /person/_doc/1
#查询满足条件的数据
GET person/doc/_search
{
"query": {
"match": {
"name": "cc"
}
}
}
改
#修改一条数据指定id
PUT /person/_doc/1
{
"id":"888",
"name":"xx"
}
删
#删除索引
DELETE person