Elasticsearch6.5+ java鏈接方式


因為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());
}
}



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM