需要的jar包,我这里使用maven的pom.xml导入,可以自己下载jar包并导入到项目中
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.24</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-core -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.10.0</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.2</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>transport</artifactId>
<version>5.4.2</version>
</dependency>
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>5.4.2</version>
</dependency>
连接集群ClientConnect.java
package util;
import java.net.InetSocketAddress;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
/**
*
* @createDate 2018年3月8日
* @class_name ClientConnect 连接ES集群
* @description : 建立es的client,通过getClient()调用,只能连接es5.4.2
*/
public class ClientConnect {
private TransportClient client;
public TransportClient getClient() {
return client;
}
/**
*
* @param clusterName 集群名称
* @param clusterAddress 集群ip地址
* @param port 端口号
*/
@SuppressWarnings({ "unchecked", "resource" })
public ClientConnect(String clusterName, String clusterAddress, int port) {
Settings settings = Settings.builder().put("cluster.name", clusterName)
.build();
client = new PreBuiltTransportClient(settings)
.addTransportAddress(new InetSocketTransportAddress(
new InetSocketAddress(clusterAddress, port)));
System.out.println("success connect");
}
}
mapping结构获取与构建Mapping.java
package util;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protoc