1.首先导入es的依赖包:当然我百度查到 客户端连接es,并实现插入的方式在6版本之前已经废弃
注意:客户端连接端口号:9300,Http端口号连接:9200
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-client</artifactId>
<version>6.2.2</version>
</dependency>
2.创建连接,并重写RestClient中的方法
package gsa.tool.elasticsearch.biz;
import java.io.IOException;
import java.util.Collections;
import java.util.Map;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.ParseException;
import org.apache.http.RequestLine;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.apache.http.impl.nio.reactor.IOReactorConfig;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import org.elasticsearch.client.Response;
import org.elasticsearch.client.ResponseListener;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
public class RestEsTool {
private static String HOST_IP = "127.0.0.1";//es服务器地址
private static int HOST_PORT = 9200;//es服务器端口
private static String HOST_HTTP = "http";//es连接方式
private static int timeout=10000;//超时时间
public static String METHOD_GET = "GET";
public static String METHOD_POST = "POST";
public static String METHOD_PUT = "PUT";
public static String METHOD_DELETE = "DELETE";
public static String _UPDATE = "/_update";
public static String _SEARCH = "/_search";
public static Map map = Collections.<String, String>emptyMap();
private volatile static RestClient restClient;
static{
build();
}
public static Header[] getDefaultHeaders(){
//默认请求头
Header[] defaultHeaders = new Header[]{new BasicHeader("content-type", "application/json; charset=utf-8")};
return defaultHeaders;
}
/**
* 加载ES restful连接
*/
public static void build(){
if(restClient==null){
synchronized (RestClient.class) {
if(restClient==null){
RestClientBuilder builder = RestClient.builder(
new HttpHost(HOST_IP, HOST_PORT, HOST_HTTP));
builder.setMaxRetryTimeoutMillis(timeout); // 超时时间
// builder.setDefaultHeaders(getDefaultHeaders()); // 请求头
// builder.setFailureListener(new RestClient.FailureListener() {
// @Override
// public void onFailure(HttpHost host) {
//
// }
// });//设置监听
builder.setRequestConfigCallback(new RestClientBuilder.RequestConfigCallback() {
@Override
public RequestConfig.Builder customizeRequestConfig(RequestConfig.Builder requestConfigBuilder) {
return requestConfigBuilder.setSocketTimeout(10000); // (4)
}
});
//我们可以通过提供一个HttpClientConfigCallback来实现基础身份验证。
//通过构建RestClient的builder进行设置。HttpClientConfigCallback是一个接口,
//这个接口有一个方法,该方法接收一个org.apache.http.impl.nio.client.
//HttpAsyncClientBuilder实例作为参数,并且返回值是也是这个实例类型。
//http client builder可以被修改并返回。
//在下面的例子中我们设置了一个默认的凭证提供者(credentials provider)来提供基础的身份认证。
// final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
// credentialsProvider.setCredentials(AuthScope.ANY,
// new UsernamePasswordCredentials("user", "password"));
//Apache Http Async Client启动时,默认一个调度线程和一些工作线程,
//这些工作线程用来进行连接管理,工作线程的数量和本地处理器的数量相同
//(使用Runtime.getRuntime().availableProcessors()获取处理器数量)。
//线程的数量可以通过如下方式修改:
builder.setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
@Override
public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
return httpClientBuilder.setDefaultIOReactorConfig(
IOReactorConfig.custom().setIoThreadCount(3).build())
// .setDefaultCredentialsProvider(credentialsProvider)
;
}
});
restClient = builder.build();
}
}
}
}
public static Response request(String method,String url){
try {
Response Response = restClient.performRequest(method, url);
return Response;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} // (1)
return null;
}
public static Response request(String method,String url,Map obj){
try {
Response Response = restClient.performRequest(method, url,obj);
return Response;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} // (1)
return null;
}
public static Response request(String method,String url,Map obj,HttpEntity entity){
try {
//Response Response = restClient.performRequest(method, url,obj);
Response Response = restClient.performRequest(method, url,obj,entity);
return Response;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} // (1)
return null;
}
public static void requestAsync(String method,String url,Map<String,String> obj,ResponseListener listener,Header[] headers){
restClient.performRequestAsync(method, url,obj,listener,headers);
}
public static void response(Response response){
try {
RequestLine requestLine = response.getRequestLine(); // 请求的信息
HttpHost host = response.getHost(); // 响应的主机信息
int statusCode = response.getStatusLine().getStatusCode(); // 响应状态行,例如你可以从中获取响应状态码
Header[] headers = response.getHeaders(); // 响应头信息,也可以使用getHeader(String)通过名称获取具体的响应头
String responseBody = EntityUtils.toString(response.getEntity());// 响应体信息,在org.apache.http.HttpEntity对象中
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void close(){
try {
restClient.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
3测试方法
public static void main(String[] args) {
Map<String, Object> params = new HashMap<>();
Map<String, Object> params1 = new HashMap<>();
Map<String, Object> params2 = new HashMap<>();
Map<String, Object> params3 = new HashMap<>();
params.put("name","测试");
params.put("age","108");
params1.put("card","1");
params.put("base", params1);
params2.put("name1", "皇上");
params2.put("age1", "23");
params2.put("card1", "2441");
params3.put("BIRTHDAY", "1990年11月12日");
Map<String, Object> _search = new HashMap<>();
Map<String, Object> _search1 = new HashMap<>();
List<String> _source = new ArrayList<>();
Map<String, Object> _search2 = new HashMap<>();
Map<String, Object> _search3 = new HashMap<>();
Map<String, Object> _search4 = new HashMap<>();
// _search1.put("match_all", new HashMap<>());
_search2.put("name", "测试");
_search1.put("match", _search2);
_search1.put("match_all", _search2);
_source.add("name");
// _source.add("age");
_search.put("_source",_source);
_search.put("query", _search1);
_search3.put("match_all", new HashMap<>());
_search4.put("query", _search3);
// String jsonString = JSON.toJSONString(params);
String jsonString = JSON.toJSONString(_search4);
System.out.println("search:"+jsonString);
HttpEntity entity = new NStringEntity(jsonString, ContentType.APPLICATION_JSON);
//判断 es 集群是否正常
// Response res=RestEsTool.request(RestEsTool.METHOD_GET, "/_cat/health?pretty");
//创建索引 建议 /库_表 格式
// Response res=RestEsTool.request(RestEsTool.METHOD_PUT, "/test_index?pretty");
//新建 文档 put:请求 url:/库_表/表/id RestEsTool.map HttpEntity
// Response res=RestEsTool.request(RestEsTool.METHOD_PUT, "/test_index/type/1?pretty", Collections.<String, String>emptyMap(),entity);
// Response res=RestEsTool.request(RestEsTool.METHOD_PUT, "/test_index/type/2?pretty", Collections.<String, String>emptyMap(),entity);
// Response res=RestEsTool.request(RestEsTool.METHOD_PUT, "/test_index/type/3?pretty", Collections.<String, String>emptyMap(),entity);
// Response res=RestEsTool.request(RestEsTool.METHOD_PUT, "/test_index/type/4?pretty", Collections.<String, String>emptyMap(),entity);
// Response res=RestEsTool.request(RestEsTool.METHOD_PUT, "/test_index1/type1/8?pretty", Collections.<String, String>emptyMap(),entity);
//按照 文档id 检索 没有参数exdb_guotu";
String tabelName="MV_WJJ_YWRYDA";
// Response res=RestEsTool.request(RestEsTool.METHOD_GET, "/test_index1/type1/8?pretty");
// Response res=RestEsTool.request(RestEsTool.METHOD_GET, "/exdb_guotu/MV_WJJ_YWRYDA/6?pretty");
//复杂检索 post 请求 url /库_表/表+RestEsTool._SEARCH RestEsTool.map HttpEntity(检索条件search)
// Response res=RestEsTool.request(RestEsTool.METHOD_POST, "/test_index1/type1"+RestEsTool._SEARCH+"?pretty",RestEsTool.map,entity);
Response res=RestEsTool.request(RestEsTool.METHOD_POST, "/exdb_guotu/MV_WJJ_YWRYDA"+RestEsTool._SEARCH+"?pretty",RestEsTool.map,entity);
try {
String responseBody = EntityUtils.toString(res.getEntity());
System.out.println("测试:"+responseBody);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}// 响应体信息,在org.apache.http.HttpEntity对象中
}