import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RequestCallback;
import org.springframework.web.client.ResponseExtractor;
import org.springframework.web.client.RestTemplate;
import java.util.HashMap;
import java.util.Map;
public class ElasticsearchIndexTemplateCreator {
public static void main(String[] args) {
// Elasticsearch 地址
String elasticsearchUrl = "
http://localhost:9200";
// Index Template 名称
String templateName = "your_index_template";
// 构建 Index Template 的映射
Map<String, Object> templateMappings = new HashMap<>();
// TODO: 添加你的 Index Template 映射内容
// 创建 Index Template
createIndexTemplate(elasticsearchUrl, templateName, templateMappings);
}
private static void createIndexTemplate(String elasticsearchUrl, String templateName, Map<String, Object> templateMappings) {
// 构建请求头
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
// 构建请求体
Map<String, Object> requestBody = new HashMap<>();
requestBody.put("index_patterns", templateName + "*");
requestBody.put("mappings", templateMappings);
// 构建 HttpEntity
HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestBody, headers);
// 创建 RestTemplate 实例
RestTemplate restTemplate = new RestTemplate();
// 发送 PUT 请求创建 Index Template
ResponseEntity<String> responseEntity = restTemplate.exchange(
elasticsearchUrl + "/_template/" + templateName,
HttpMethod.PUT,
requestEntity,
String.class);
// 输出响应
System.out.println(responseEntity.getBody());
}
}