zhongrj
2024-04-09 66b6525861e566adb3db8f06f824de7751fbca9e
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
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();
        }
    }
}