索引 CRUD
PUT/GET/DELETE 文档、bulk API。
30 分钟
索引 CRUD
对 Index 中的 Document 做增删改查;单条用 REST,批量用 _bulk API。实验数据从 MySQL cf_track 导出或手工构造,不写回 MySQL。
学习目标
- 掌握 PUT / GET / DELETE 单文档操作
- 使用
_bulk批量导入 - 理解
refresh、版本冲突与_id策略
核心内容
单文档 CRUD
# Create / Replace(指定 _id = slug)
curl -X PUT "localhost:9200/tracks/_doc/spring-boot-essentials" \
-H "Content-Type: application/json" -d '
{
"slug": "spring-boot-essentials",
"title": "Spring Boot 入门",
"category": "backend",
"summary": "IoC、Web、JPA",
"lessonCount": 16,
"updatedAt": "2026-03-01T00:00:00Z"
}'
# Read
curl -s "localhost:9200/tracks/_doc/spring-boot-essentials?pretty"
# Partial update
curl -X POST "localhost:9200/tracks/_update/spring-boot-essentials" \
-H "Content-Type: application/json" -d '
{ "doc": { "lessonCount": 17 } }'
# Delete
curl -X DELETE "localhost:9200/tracks/_doc/obsolete-track"
_id 与 MySQL 主键解耦:推荐用业务自然键 slug,便于 es-sync 幂等 upsert。
Bulk 批量导入
curl -X POST "localhost:9200/_bulk" -H "Content-Type: application/x-ndjson" --data-binary @- <<'EOF'
{"index":{"_index":"tracks","_id":"mongodb-essentials"}}
{"slug":"mongodb-essentials","title":"MongoDB 入门","category":"backend","summary":"文档模型与 Spring Data","lessonCount":12,"updatedAt":"2026-03-01T00:00:00Z"}
{"index":{"_index":"tracks","_id":"postgresql-essentials"}}
{"slug":"postgresql-essentials","title":"PostgreSQL 入门","category":"devops","summary":"JSONB 与 MVCC 实验","lessonCount":12,"updatedAt":"2026-03-01T00:00:00Z"}
EOF
响应中 "errors": false 表示全部成功;失败条目会带 error 原因(常见:Mapping 冲突)。
refresh 与可见性
写入后默认 近实时(约 1s refresh_interval)。调试可 ?refresh=true 强制立即可搜,勿在生产滥用。
curl -X GET "localhost:9200/tracks/_search?q=Spring&pretty"
与 REST API 的关系
CodeRoadMap 生产路径:GET /tracks 读 MySQL(spring-boot-essentials)。ES 索引供 搜索实验端点 或 Kibana 探索,见 。