package es_02_index; import org.elasticsearch.action.ActionListener; 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.elasticsearch.common.xcontent.XContentType; 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; /** * 异步创建索引 * * @author : qinyingjie * @version : 2.2.0 * @date : 2023/5/13 11:10 */ @SpringBootTest @RunWith(SpringRunner.class) public class TestIndex_04_Async { @Autowired private RestHighLevelClient client; //创建索引异步方式 @Test public void testCreateIndexAsync() { //创建索引对象 CreateIndexRequest createIndexRequest = new CreateIndexRequest("itheima_book"); //设置参数 createIndexRequest.settings(Settings.builder().put("number_of_shards", "1").put("number_of_replicas", "0")); //指定映射1 createIndexRequest.mapping(" {\n" + " \t\"properties\": {\n" + " \"name\":{\n" + " \"type\":\"keyword\"\n" + " },\n" + " \"description\": {\n" + " \"type\": \"text\"\n" + " },\n" + " \"price\":{\n" + " \"type\":\"long\"\n" + " },\n" + " \"pic\":{\n" + " \"type\":\"text\",\n" + " \"index\":false\n" + " }\n" + " \t}\n" + "}", XContentType.JSON); //设置别名 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(); //执行创建索引库 ActionListener listener = new ActionListener() { @Override public void onResponse(CreateIndexResponse createIndexResponse) { //得到响应(全部) boolean acknowledged = createIndexResponse.isAcknowledged(); //得到响应 指示是否在超时前为索引中的每个分片启动了所需数量的碎片副本 boolean shardsAcknowledged = createIndexResponse.isShardsAcknowledged(); System.out.println("acknowledged:" + acknowledged); System.out.println("shardsAcknowledged:" + shardsAcknowledged); } @Override public void onFailure(Exception e) { e.printStackTrace(); } }; client.indices().createAsync(createIndexRequest, RequestOptions.DEFAULT, listener); try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } } }