因为ES 6.5之上进行了大改版,相应的JAVA的链接方式也发生了变化。

在6.5之前的众多版本中,java链接到ES需要ES打开9300端口,而新版本的client类可以规定链接链接方式和端口。

 

第一步 : POM文件

<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>6.4.3</version>
</dependency>

第二步:新建一个类,此类是client的配置。

import java.util.ArrayList;

import org.apache.http.HttpHost;
import org.apache.http.client.config.RequestConfig.Builder;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestClientBuilder.HttpClientConfigCallback;
import org.elasticsearch.client.RestClientBuilder.RequestConfigCallback;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class EsConfiguration {

private static String hosts = "地址"; // 集群地址,多个用,隔开
private static int port = 端口; // 使用的端口号
private static String schema = "http"; // 使用的协议
private static ArrayList<HttpHost> hostList = null;

private static int connectTimeOut = 1000; // 连接超时时间
private static int socketTimeOut = 30000; // 连接超时时间
private static int connectionRequestTimeOut = 500; // 获取连接的超时时间

private static int maxConnectNum = 100; // 最大连接数
private static int maxConnectPerRoute = 100; // 最大路由连接数

static {
hostList = new ArrayList<>();
String[] hostStrs = hosts.split(",");
for (String host : hostStrs) {
hostList.add(new HttpHost(host, port, schema));
}
}

@Bean
public RestHighLevelClient client() {
RestClientBuilder builder = RestClient.builder(hostList.toArray(new HttpHost[0]));
// 异步httpclient连接延时配置
builder.setRequestConfigCallback(new RequestConfigCallback() {
@Override
public Builder customizeRequestConfig(Builder requestConfigBuilder) {
requestConfigBuilder.setConnectTimeout(connectTimeOut);
requestConfigBuilder.setSocketTimeout(socketTimeOut);
requestConfigBuilder.setConnectionRequestTimeout(connectionRequestTimeOut);
return requestConfigBuilder;
}
});
// 异步httpclient连接数配置
builder.setHttpClientConfigCallback(new HttpClientConfigCallback() {
@Override
public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
httpClientBuilder.setMaxConnTotal(maxConnectNum);
httpClientBuilder.setMaxConnPerRoute(maxConnectPerRoute);
return httpClientBuilder;
}
});
RestHighLevelClient client = new RestHighLevelClient(builder);
return client;
}
}

第三步:调用client,完成增删改查。

@Autowired
private RestHighLevelClient client; //记得注入client哦~


1.创建索引
/**
* 创建索引
* @throws IOException
*/
@Test
public void testAdd() throws IOException {
CreateIndexRequest request = new CreateIndexRequest("index");
CreateIndexResponse createIndexResponse = client.indices().create(request,RequestOptions.DEFAULT);
System.out.println("createIndex: " + JSON.toJSONString(createIndexResponse));
}
2.判断索引是否存在
 @Test
public void existsIndex() throws IOException {
String index = "需要判断的索引";
GetIndexRequest request = new GetIndexRequest();
request.indices(index);
boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
System.out.println("existsIndex: " + exists);
}
3.判断记录是否存在
 @Test
public void exists() throws IOException {
String index = "";
String type = "";
GetRequest getRequest = new GetRequest(index, type, "数据的主键");
getRequest.fetchSourceContext(new FetchSourceContext(false));
getRequest.storedFields("_none_");
boolean exists = client.exists(getRequest, RequestOptions.DEFAULT);
System.out.println("exists: " + exists);
}
4.更新记录信息
@Test
public void update() throws IOException {
String index = "";
String type = "";
MajorInfo majorInfo = new MajorInfo();
UpdateRequest request = new UpdateRequest(index, type, majorInfo.getId());
request.doc(JSON.toJSONString(majorInfo), XContentType.JSON);
UpdateResponse updateResponse = client.update(request, RequestOptions.DEFAULT);
System.out.println("update: " + JSON.toJSONString(updateResponse));
}

5.删除记录
public void delete(String index, String type, Long id) throws IOException {
DeleteRequest deleteRequest = new DeleteRequest(index, type, id.toString());
DeleteResponse response = client.delete(deleteRequest, RequestOptions.DEFAULT);
System.out.println("delete: " + JSON.toJSONString(response));
}

6.查询
 @Test
public void search() throws IOException {
String index = "你的index";
String type = "你的type";
String name = "搜索的value"; //搜索的value
BoolQueryBuilder boolBuilder = QueryBuilders.boolQuery();
boolBuilder.must(QueryBuilders.matchQuery("title", name)); // 这里可以根据字段进行搜索,must表示符合条件的,相反的mustnot表示不符合条件的
// boolBuilder.should(QueryBuilders.fuzzyQuery("字段", 值)); //模糊搜索
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
sourceBuilder.query(boolBuilder);
sourceBuilder.from(0);
sourceBuilder.size(100); // 获取记录数,默认10
sourceBuilder.fetchSource(new String[] { "id", "name" }, new String[] {}); // 第一个是获取字段,第二个是过滤的字段,默认获取全部
SearchRequest searchRequest = new SearchRequest(index);
searchRequest.types(type);
searchRequest.source(sourceBuilder);
SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
System.out.println("search: " + JSON.toJSONString(response));
SearchHits hits = response.getHits();
SearchHit[] searchHits = hits.getHits();
for (SearchHit hit : searchHits) {
System.out.println("search -> " + hit.getSourceAsString());
}
}