在Elasticsearch的旧版本中,字符串类型使用String
表示。然而,从Elasticsearch 5.x版本起,String
类型不再被支持,取而代之的是text
类型和keyword
类型。
text类型:用于存储需要进行全文搜索的文本数据。例如,商品描述字段,用户可以通过关键词检索到该商品。通常,text
类型不适合用于排序和过滤。
keyword类型:用于存储不需要分词处理的数据,如电话号码、标签等。这类数据常用于精确过滤、排序和聚合。
Elasticsearch没有专门的数组类型,但一个字段可以存储多个值。
对象类型允许在一个字段中嵌套多个键值对。例如:
```json PUT /myindex2/mapping { "properties": { "num3": { "type": "object" } } }
POST /myindex2/doc { "num3": { "name": "四川", "size": 10 } } ```
嵌套类型是对对象类型的一种扩展,允许为嵌套文档单独进行索引和查询。查询嵌套文档需要使用嵌套查询。
json
GET /my_index2/_search
{
"query": {
"nested": {
"path": "path_to_nested_doc",
"query": {}
}
}
}
静态映射是在创建索引时手动设置字段的数据类型的机制。
json
PUT /my_index8
{
"settings": {
"number_of_replicas": 2,
"number_of_shards": 2
},
"mappings": {
"properties": {
"cusName": {
"type": "keyword"
},
"cusAddr": {
"type": "text"
}
}
}
}
动态映射是指向Elasticsearch写入数据时,不需要提前创建索引、字段和映射类型。Elasticsearch会根据写入的数据自动创建索引和字段,并推断字段的数据类型。
dynamic
: true
开启自动添加字段功能(默认)dynamic
: false
忽略新字段dynamic
: "strict"
遇到未知字段时抛出异常json
PUT /my_index3/_mapping
{
"dynamic": false
}
默认情况下,Elasticsearch会自动检测新增字段的数据内容是否符合日期格式,并将其映射为date
类型。
json
PUT /my_index3/_mapping
{
"date_detection": false
}
默认情况下,数字类型检测是关闭的。如果开启,Elasticsearch会将时间戳字符串自动转换为数值类型。
json
PUT /my_index3/_mapping
{
"numeric_detection": true
}
模板映射是一种自动应用模板的机制,适用于创建新索引时。
json
PUT /_template/my_test_template1
{
"index_patterns": ["*"],
"order": 1,
"settings": {
"number_of_shards": 2,
"number_of_replicas": 2
},
"mappings": {
"date_detection": true,
"numeric_detection": true
}
}
动态模板映射允许根据字段名称动态设置字段的数据类型。
json
PUT /my_index6
{
"mappings": {
"dynamic_templates": [
{
"template_profix_is": {
"match": "is*",
"match_mapping_type": "string",
"mapping": {
"type": "boolean"
}
}
},
{
"template_profix_content": {
"match": "detail*",
"match_mapping_type": "string",
"mapping": {
"type": "text"
}
}
},
{
"template_profix_search": {
"match": "search*",
"match_mapping_type": "string",
"mapping": {
"type": "keyword"
}
}
}
]
}
}
此模板中,以is
开头的字段将被映射为boolean
类型,以detail
开头的字段将被映射为text
类型,以search
开头的字段将被映射为keyword
类型。