使用Java客户端创建索引库
步骤
(1)创建一个Java工程。
(2)添加jar包,添加maven坐标。
(3)编写测试方法实现创建索引库。
-
创建一个Settings对象,相当于是一个配置信息。主要配置集群的名称。
-
创建一个客户端Client对象。
-
使用client对象创建一个索引库。
-
关闭client对象。
代码:
package com.itdemo.es;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.junit.Test;
import java.net.InetAddress;
public class ElasticSearchClientTest {
/*
实现创建索引库步骤:
1.创建一个Settings对象,相当于是一个配置信息。主要配置集群的名称。
2.创建一个客户端Client对象。
3.使用client对象创建一个索引库。
4.关闭client对象。
*/
@Test
public void createIndex() throws Exception {
// 1.创建一个Settings对象
Settings settings = Settings.builder().put("cluster.name", "my-elasticsearch").build();
// 2.创建一个客户端Client对象
TransportClient client = new PreBuiltTransportClient(settings);
// 指定集群中节点的列表
client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9301));
client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9302));
client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9303));
// 3.使用client对象创建一个索引库,索引库名称为index_hello(前面为设置,get()为执行操作)
client.admin().indices().prepareCreate("index_hello").get();
// 关闭client对象
client.close();
}
}
实现效果:
(1)执行单元测试,执行成功:
(2)观察效果:
执行前:
执行后: