Appearance
索引管理与别名
索引创建
创建索引
json
PUT /products
{
"settings": {
"number_of_shards": 3,
"number_of_replicas": 2,
"refresh_interval": "1s"
},
"mappings": {
"properties": {
"name": {"type": "text", "analyzer": "ik_max_word"},
"price": {"type": "integer"},
"category": {"type": "keyword"},
"create_date": {"type": "date"}
}
}
}Settings配置
| 参数 | 默认值 | 说明 |
|---|---|---|
number_of_shards | 1 | 主分片数 |
number_of_replicas | 1 | 副本数 |
refresh_interval | 1s | 刷新间隔 |
max_result_window | 10000 | 最大深度分页 |
json
PUT /my_index
{
"settings": {
"number_of_shards": 3,
"number_of_replicas": 2,
"refresh_interval": "5s",
"max_result_window": 50000,
"max_rescore_window": 20000,
"max_script_fields": 20,
"max_ngram_diff": 2
}
}Mappings配置
json
PUT /my_index
{
"mappings": {
"dynamic": "strict", // 严格模式
"properties": {
"title": {
"type": "text",
"analyzer": "ik_max_word",
"fields": {
"keyword": {"type": "keyword"}
}
}
}
}
}字段类型
| 类型 | 说明 |
|---|---|
| text | 文本,全文搜索 |
| keyword | 关键字,精确匹配 |
| integer/long | 整数 |
| float/double | 浮点 |
| boolean | 布尔 |
| date | 日期 |
| object | 对象 |
| nested | 嵌套对象 |
| ip | IP地址 |
| geo_point | 地理位置 |
索引别名
创建别名
json
POST /_aliases
{
"actions": [
{"add": {"index": "products_2024", "alias": "products"}}
]
}别名过滤
json
POST /_aliases
{
"actions": [
{
"add": {
"index": "products",
"alias": "products_active",
"filter": {"term": {"status": "active"}}
}
}
]
}别名路由
json
POST /_aliases
{
"actions": [
{
"add": {
"index": "products",
"alias": "products_v1",
"routing": "category"
}
}
]
}索引操作
查看索引信息
json
GET /products
GET /products/_settings
GET /products/_mappings
GET /products/_aliases修改索引设置
json
// 修改副本数
PUT /products/_settings
{
"number_of_replicas": 1
}
// 关闭自动刷新
PUT /products/_settings
{
"refresh_interval": -1
}索引打开/关闭
json
POST /products/_close
POST /products/_open删除索引
json
DELETE /products
DELETE /products,logs
DELETE /products*动态映射
dynamic配置
json
PUT /my_index
{
"mappings": {
"dynamic": "strict", // 严格,不允许新字段
// "dynamic": false, // 忽略新字段
// "dynamic": true, // 动态添加(默认)
"properties": {...}
}
}动态模板
json
PUT /my_index
{
"mappings": {
"dynamic_templates": [
{
"strings_as_keywords": {
"match_mapping_type": "string",
"mapping": {"type": "keyword"}
}
},
{
"long_as_integer": {
"match_mapping_type": "long",
"mapping": {"type": "integer"}
}
}
]
}
}索引重建
Reindex
json
POST /_reindex
{
"source": {"index": "old_index"},
"dest": {"index": "new_index"}
}跨集群Reindex
json
POST /_reindex
{
"source": {
"remote": {
"host": "http://remotehost:9200",
"username": "user",
"password": "pass"
},
"index": "old_index"
},
"dest": {"index": "new_index"}
}索引收缩
json
POST /my_index/_shrink/my_index_shrunk
{
"settings": {
"index.number_of_shards": 1
}
}分裂索引
json
POST /my_index/_split/my_index_split_2
{
"settings": {
"index.number_of_shards": 2
}
}面试考点
Q: 主分片数能改吗?
❌ 不能,只能重建
Q: 副本数可以改吗?
✅ 可以动态调整
Q: 为什么用别名?
- 零停机重建索引
- 实现路由
- 过滤查询
Q: dynamic strict vs false?
- strict:严格模式,拒绝新字段
- false:忽略新字段,不索引
