package org.springblade.es.service; import org.elasticsearch.client.RequestOptions; import org.elasticsearch.client.RestHighLevelClient; import org.elasticsearch.client.indices.CreateIndexRequest; import org.elasticsearch.client.indices.GetIndexRequest; import org.elasticsearch.xcontent.XContentType; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class ElasticsearchIndexInitializer { @Autowired private RestHighLevelClient client; public void initializeIndex(String indexName, String mappingJson) { try { // 检查索引是否已存在 GetIndexRequest request = new GetIndexRequest(indexName); boolean indexExists = client.indices().exists(request, RequestOptions.DEFAULT); // 如果索引不存在,则创建索引并设置映射 if (!indexExists) { CreateIndexRequest createIndexRequest = new CreateIndexRequest(indexName); createIndexRequest.mapping(mappingJson, XContentType.JSON); client.indices().create(createIndexRequest, RequestOptions.DEFAULT); } } catch (Exception e) { e.printStackTrace(); } } }