mapping映射属性
mapping是对索引库中文档的约束,常见的mapping属性包括:
- type:字段数据类型,常见的简单类型有(底层Java实现):
- 字符串:text(可分词的文本)、keyword(精确值,例如:品牌、国家、ip地址)
- 数值:long、integer、short、byte、double、float、
- 布尔:boolean
- 日期:date
- 对象:object
- index:是否创建索引,默认为true
- analyzer:使用哪种分词器
- properties:该字段的子字段
创建索引库映射语法
PUT /索引库名称
{
"mappings": {
"properties": {
"字段名":{
"type": "text",
"analyzer": "ik_smart"
},
"字段名2":{
"type": "keyword",
"index": "false"
},
"字段名3":{
"properties": {
"子字段": {
"type": "keyword"
}
}
}
}
}
}
例如员工信息的文档:
设置映射信息
PUT haohong
{
"mappings": {
"properties": {
"name": {
"type": "keyword"
},
"age": {
"type": "integer"
},
"weight": {
"type": "double"
},
"birthday": {
"type": "date",
"format": "yyyy-MM-dd HH:mm:ss||yyyy-MM-dd||epoch_millis"
},
"remark": {
"type": "text",
"analyzer": "ik_smart"
},
"mobile": {
"type": "binary",
"index": false
},
"isMarried": {
"type": "boolean"
}
}
}
}
对应的每个字段映射(mapping):
- age:类型为 integer;参与搜索,因此需要index为true;无需分词器
- weight:类型为double;参与搜索,因此需要index为true;无需分词器
- birthday: 类型为date,参与搜索,因此需要index为true;无需分词器,需要指定日期的格式
- isMarried:类型为boolean;参与搜索,因此需要index为true;无需分词器
- remake:类型为字符串,需要分词,因此是text;参与搜索,因此需要index为true;分词器可以用ik_smart
- mobile:类型为字符串,但是不需要分词,因此是keyword;不参与搜索,因此需要index为false;无需分词器
添加数据
POST haohong/_doc/1
{
"name":"雷阳",
"age": 18,
"weight": 53.23,
"birthday":"2021-10-01 10:00:00",
"remark":"技术男,近期在学习ES",
"mobile":"13123399999",
"isMarried": true
}
查看索引库
GET 索引库名称
例如:GET haohong
删除索引库
DELETE 索引库名称
例如:DELETE haohong
修改索引库
索引库和mapping一旦创建无法修改,但是可以添加新的字段,语法如下:
PUT /索引库名/_mapping
{
"properties": {
"新字段名":{
"type": "integer"
}
}
}
添加email新的字段
PUT haohong/_mapping
{
"properties": {
"email" : {
"type":"keyword"
}
}
}
索引库的操作总结
- 创建索引库:PUT /索引库名
- 查询索引库:GET /索引库名
- 删除索引库:DELETE /索引库名
- 添加字段:PUT /索引库名/_mapping