package es_02_index; import org.elasticsearch.action.admin.indices.alias.Alias; import org.elasticsearch.action.support.ActiveShardCount; import org.elasticsearch.client.IndicesClient; 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.common.settings.Settings; import org.elasticsearch.common.unit.TimeValue; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import java.io.IOException; import java.util.HashMap; import java.util.Map; /** * 创建索引 * * @author : qinyingjie * @version : 2.2.0 * @date : 2023/5/13 11:06 */ @SpringBootTest @RunWith(SpringRunner.class) public class TestIndex_02_Create { @Autowired private RestHighLevelClient client; //创建索引 @Test public void testCreateIndex() throws IOException { // PUT /my_index // { // "settings": { // "number_of_shards": 1, // "number_of_replicas": 1 // }, // "mappings": { // "properties": { // "field1":{ // "type": "text" // }, // "field2":{ // "type": "text" // } // } // }, // "aliases": { // "default_index": {} // } // } //创建索引对象 CreateIndexRequest createIndexRequest = new CreateIndexRequest("itheima_book"); //设置参数 createIndexRequest.settings(Settings.builder().put("number_of_shards", "1").put("number_of_replicas", "0")); //指定映射 Map message = new HashMap<>(); message.put("type", "text"); Map properties = new HashMap<>(); properties.put("message", message); Map mapping = new HashMap<>(); mapping.put("properties", properties); createIndexRequest.mapping(mapping); //设置别名 createIndexRequest.alias(new Alias("itheima_index_new")); // 额外参数 //设置超时时间 createIndexRequest.setTimeout(TimeValue.timeValueMinutes(2)); //设置主节点超时时间 createIndexRequest.setMasterTimeout(TimeValue.timeValueMinutes(1)); //在创建索引API返回响应之前等待的活动分片副本的数量,以int形式表示 createIndexRequest.waitForActiveShards(ActiveShardCount.from(2)); createIndexRequest.waitForActiveShards(ActiveShardCount.DEFAULT); //操作索引的客户端 IndicesClient indices = client.indices(); //执行创建索引库 CreateIndexResponse createIndexResponse = indices.create(createIndexRequest, RequestOptions.DEFAULT); //得到响应(全部) boolean acknowledged = createIndexResponse.isAcknowledged(); //得到响应 指示是否在超时前为索引中的每个分片启动了所需数量的碎片副本 boolean shardsAcknowledged = createIndexResponse.isShardsAcknowledged(); System.out.println("acknowledged:" + acknowledged); System.out.println("shardsAcknowledged:" + shardsAcknowledged); } }