第四阶段 33 · index / mapping 管理(建索引、别名、reindex)

33 · index / mapping 管理(建索引、别名、reindex)

阶段:第四阶段 / 写入与索引管理

ES:建索引 / mapping / 别名 / reindex | PostgreSQL:DDL、CREATE TABLE、视图、表重建


1. 概念

索引管理相当于数据库的 DDL:

ES 操作 SQL 对照
PUT /index + mapping CREATE TABLE + 列定义
别名 alias 视图 / 可切换的表名
reindex INSERT INTO new SELECT * FROM old(表重建)
PUT /index/_mapping ALTER TABLE ADD COLUMN

本项目建索引入口:InsertToEsTask.createIndexCreateSalesIndexHandler

mapping 从 mappings/*.json(如 salesdata_idx.json)读取。


2. PostgreSQL 对照

sql 复制代码
CREATE TABLE salesdata (
  invoice_number varchar,
  net_amount     numeric,
  invoice_dt     date
);

-- 加列(ES 只能加不能改类型)
ALTER TABLE salesdata ADD COLUMN customer_group varchar;

-- 视图切换(类比别名)
CREATE VIEW salesdata_current AS SELECT * FROM salesdata_v2;

3. ES DSL

复制代码
# 建索引 + settings + mapping
PUT salesdata_idx
{
  "settings": { "number_of_shards": 3, "number_of_replicas": 1 },
  "mappings": {
    "properties": {
      "invoice_number": { "type": "keyword" },
      "net_amount":     { "type": "double" },
      "invoice_dt":     { "type": "date", "format": "yyyy-MM-dd" }
    }
  }
}

# 追加字段(不能改已有字段类型)
PUT salesdata_idx/_mapping
{ "properties": { "customer_group": { "type": "keyword" } } }

# 别名切换(原子)
POST _aliases
{
  "actions": [
    { "remove": { "index": "salesdata_v1", "alias": "salesdata" } },
    { "add":    { "index": "salesdata_v2", "alias": "salesdata" } }
  ]
}

# reindex:老索引数据搬到新索引
POST _reindex
{ "source": { "index": "salesdata_v1" }, "dest": { "index": "salesdata_v2" } }

4. Spring Boot 实现

java 复制代码
@Component
public class Doc33IndexAdmin {

    @Autowired
    private ElasticsearchClient elasticsearchClient;

    /** 建索引 + mapping(简化版,本项目实际读 mappings/*.json) */
    public void createIndex(String indexName) throws IOException {
        boolean exists = elasticsearchClient.indices()
                .exists(e -> e.index(indexName)).value();
        if (exists) {
            return;
        }
        elasticsearchClient.indices().create(c -> c
                .index(indexName)
                .settings(st -> st.numberOfShards("3").numberOfReplicas("1"))
                .mappings(m -> m
                        .properties("invoice_number", p -> p.keyword(k -> k))
                        .properties("net_amount", p -> p.double_(d -> d))
                        .properties("invoice_dt", p -> p.date(d -> d.format("yyyy-MM-dd")))));
    }

    /** 追加字段:类比 ALTER TABLE ADD COLUMN */
    public void addKeywordField(String indexName, String field) throws IOException {
        elasticsearchClient.indices().putMapping(m -> m
                .index(indexName)
                .properties(field, p -> p.keyword(k -> k)));
    }

    /** 原子切换别名 */
    public void switchAlias(String alias, String oldIndex, String newIndex) throws IOException {
        elasticsearchClient.indices().updateAliases(a -> a
                .actions(ac -> ac.remove(r -> r.index(oldIndex).alias(alias)))
                .actions(ac -> ac.add(ad -> ad.index(newIndex).alias(alias))));
    }
}

与本项目对照:建索引逻辑见 CreateSalesIndexHandler,mapping 新增字段时

参考 ADD_FIELD_SKILL 里 ES 部分(在 mapping 的 properties 追加字段)。


5. 坑与最佳实践

  1. mapping 不可改已有字段类型:改类型只能新建索引 + reindex + 切别名。
  2. 用别名解耦 :应用只认别名(如 salesdata),底层索引版本切换对上层透明、零停机。
  3. 动态映射风险:生产索引建议显式 mapping,或关掉动态映射,避免字段类型被自动猜错。
  4. 分片数建后不可改number_of_shards 定死,需重新规划只能 reindex;副本数可动态调。
  5. reindex 期间双写或停写:保证新老索引数据一致,切别名前校验文档数。

阶段小结

第四阶段完成后,你应该能:单文档增删改、bulk 批量写、按条件批量更新/删除、

建索引与 mapping、用别名做零停机切换、用 reindex 重建索引。

相关推荐
敲个大西瓜4 小时前
Redis一百道核心面试题
数据库·redis·缓存
無a伟7 小时前
Redis持久化详解:RDB与AOF原理、配置、优缺点
数据库
小罗水7 小时前
附录A 各微服务完整 application.yml 配置汇总
数据库·elasticsearch·微服务
muddjsv8 小时前
SQLite 外键进阶:CASCADE / SET NULL / 级联更新与完整性校验
数据库·sqlite
APItesterCris8 小时前
Open Claw 实战教程:5 分钟搭建京东商品自动化监控与数据分析系统
大数据·运维·数据库·数据仓库·自动化
Nturmoils8 小时前
查库存的 SQL 时灵时不灵,最后发现是 WHERE 里两个函数在打架
数据库
不想纳尼的青春9 小时前
where = 的作用?会影响性能吗?count(*) 和 count()哪个快?
数据库·oracle
倔强的石头_9 小时前
Spring Boot 接入金仓数据库:配置分层、启动自检与常见错误
数据库
杨云龙UP10 小时前
生产环境Oracle表空间扩容实战:使用Toad for Oracle图形界面新增Datafile(ASM+OMF)
linux·运维·数据库·oracle·表空间·asm 存储管理·toad
黑桃小柒710 小时前
Django模型关系:从一对多到多对多全解析
数据库·django·sqlite