Elasticsearch RESTful API入门:索引的增删改查完全指南

Elasticsearch RESTful API入门:索引的增删改查完全指南

本文专为Java开发初学者设计,将手把手教你掌握Elasticsearch索引的核心操作

一、环境准备与基本概念

1.1 安装Elasticsearch(Windows版)

1.访问官网下载ZIP包

2.解压后进入bin目录,双击elasticsearch.bat启动

3.验证安装:浏览器访问http://localhost:9200,看到JSON响应即成功

1.2 核心概念

索引(Index): 相当于关系型数据库中的"数据库"

类型(Type): 7.x后已弃用,现默认为_doc

文档(Document): 索引中的基本单位,JSON格式

分片(Shard): 索引的分区,用于水平扩展

副本(Replica): 分片的备份,提高可用性

二、索引操作实战

2.1 创建索引

bash 复制代码
PUT /products
{
  "settings": {
    "number_of_shards": 1,
    "number_of_replicas": 1
  },
  "mappings": {
    "properties": {
      "name": {"type": "text"},
      "price": {"type": "double"},
      "description": {"type": "text"},
      "category": {"type": "keyword"},
      "stock": {"type": "integer"},
      "created_at": {"type": "date"}
    }
  }
}

2.2 查看索引信息

bash 复制代码
GET /products

// 响应示例
{
  "products": {
    "aliases": {},
    "mappings": {
      "properties": {
        "category": {"type": "keyword"},
        "created_at": {"type": "date"},
        "description": {"type": "text"},
        "name": {"type": "text"},
        "price": {"type": "double"},
        "stock": {"type": "integer"}
      }
    },
    "settings": {
      "index": {
        "creation_date": "1689987632211",
        "number_of_shards": "1",
        "number_of_replicas": "1",
        // ...其他设置
      }
    }
  }
}

2.3 删除索引

bash 复制代码
DELETE /products

// 成功响应
{
  "acknowledged": true
}

2.4 修改索引设置

bash 复制代码
PUT /products/_settings
{
  "index": {
    "number_of_replicas": 2
  }
}

2.5 索引状态管理

bash 复制代码
// 关闭索引
POST /products/_close

// 打开索引
POST /products/_open

// 清除缓存
POST /products/_cache/clear

三、索引操作可视化界面

https://example.com/es-index-management.png

实际界面示例 - 显示索引状态、分片分布和统计信息

四、Java客户端操作示例

java 复制代码
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.client.indices.GetIndexResponse;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentType;

public class IndexOperations {

    private final RestHighLevelClient client;

    public IndexOperations(RestHighLevelClient client) {
        this.client = client;
    }

    // 创建索引
    public boolean createProductIndex() throws Exception {
        CreateIndexRequest request = new CreateIndexRequest("products");
        
        // 索引设置
        request.settings(Settings.builder()
                .put("index.number_of_shards", 1)
                .put("index.number_of_replicas", 1)
        );
        
        // 映射定义
        String mapping = "{\"properties\":{\"name\":{\"type\":\"text\"},\"price\":{\"type\":\"double\"}," +
                         "\"description\":{\"type\":\"text\"},\"category\":{\"type\":\"keyword\"}," +
                         "\"stock\":{\"type\":\"integer\"},\"created_at\":{\"type\":\"date\"}}}";
        
        request.mapping(mapping, XContentType.JSON);
        
        CreateIndexResponse response = client.indices()
                .create(request, RequestOptions.DEFAULT);
        
        return response.isAcknowledged();
    }

    // 检查索引是否存在
    public boolean indexExists(String indexName) throws Exception {
        GetIndexRequest request = new GetIndexRequest(indexName);
        return client.indices().exists(request, RequestOptions.DEFAULT);
    }

    // 获取索引信息
    public GetIndexResponse getIndexInfo(String indexName) throws Exception {
        GetIndexRequest request = new GetIndexRequest(indexName);
        return client.indices().get(request, RequestOptions.DEFAULT);
    }

    // 删除索引
    public boolean deleteIndex(String indexName) throws Exception {
        DeleteIndexRequest request = new DeleteIndexRequest(indexName);
        AcknowledgedResponse response = client.indices()
                .delete(request, RequestOptions.DEFAULT);
        return response.isAcknowledged();
    }
}

五、最佳实践与常见问题

5.1 索引命名规范

1. 仅小写字母

2. 不能包含:, /, *, ?, ", <, >, |, (空格), , #

3. 避免使用-和_开头

4. 长度限制255字符

5.2 常见错误处理

java 复制代码
// 索引已存在
{
  "error": {
    "root_cause": [
      {"type": "resource_already_exists_exception", "reason": "index [products] already exists"}
    ],
    "status": 400
  }
}

// 解决方案:先删除或使用不同名称
DELETE /products

5.3 索引设计建议

1. 根据数据量预估合理分片数(每个分片20-50GB)

2. 冷热数据分离:使用ILM(Index Lifecycle Management)

3. 定期监控索引健康状态

4. 重要索引启用快照备份

相关推荐
寻星探路32 分钟前
【深度长文】万字攻克网络原理:从 HTTP 报文解构到 HTTPS 终极加密逻辑
java·开发语言·网络·python·http·ai·https
曹牧3 小时前
Spring Boot:如何测试Java Controller中的POST请求?
java·开发语言
AI_56783 小时前
AWS EC2新手入门:6步带你从零启动实例
大数据·数据库·人工智能·机器学习·aws
CRzkHbaXTmHw3 小时前
探索Flyback反激式开关电源的Matlab Simulink仿真之旅
大数据
爬山算法4 小时前
Hibernate(90)如何在故障注入测试中使用Hibernate?
java·后端·hibernate
七夜zippoe4 小时前
CANN Runtime任务描述序列化与持久化源码深度解码
大数据·运维·服务器·cann
盟接之桥4 小时前
盟接之桥说制造:引流品 × 利润品,全球电商平台高效产品组合策略(供讨论)
大数据·linux·服务器·网络·人工智能·制造
kfyty7254 小时前
集成 spring-ai 2.x 实践中遇到的一些问题及解决方案
java·人工智能·spring-ai
猫头虎4 小时前
如何排查并解决项目启动时报错Error encountered while processing: java.io.IOException: closed 的问题
java·开发语言·jvm·spring boot·python·开源·maven
李少兄4 小时前
在 IntelliJ IDEA 中修改 Git 远程仓库地址
java·git·intellij-idea