随着Elasticsearch版本的疊代,早期的
TransportClient
不推薦使用,而推薦使用 Java High Level REST Client 并将在Elasticsearch 8.0中删除-------elasticsearch官方
好像spring data elasticsearch 低層也用到了
TransportClient。
開始:
先建立一個springboot項目
引入依賴:版本要和你安裝的elasticsearch版本一緻,這裡我用到了fastjson
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.5.1</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.54</version>
</dependency>
注意:在pom.xml檔案中<properties></properties>指明ES的版本避免報錯
<properties>
<java.version>1.8</java.version>
<elasticsearch.version>7.5.1</elasticsearch.version>
</properties>
然後再application.yml配置參數如下:
如果沒有配置elasticsearch密碼驗證就把username和password删除即可
spring:
elasticsearch:
rest:
uris: ip1:9200,ip2:9200,ip3:9200
usernme: elastic #如果你設定了基于x-pack的驗證就要填寫賬号和密碼
password: 123456 #沒有則不用配置
connection-timeout: 100 #連接配接逾時
max-connection: 100 #最大連接配接數
建立一個EsClientConfiguration.java類,用于建構RestHighLevelClient用戶端。
@Configuration
public class EsClientConfiguration {
@Value("${spring.elasticsearch.rest.uris}")
private String[] esUris;
@Value("${spring.elasticsearch.rest.connection-timeout}")
private int connectTimeOut; // 連接配接逾時時間
@Value("${spring.elasticsearch.rest.max-connection}")
private int maxConnection; //最大連接配接數
@Autowired
private Environment environment;
@Bean
public RestHighLevelClient client() {
String userName = environment.getProperty("spring.elasticsearch.rest.username");
String password = environment.getProperty("spring.elasticsearch.rest.password");
HttpHost[] httpHosts = new HttpHost[esUris.length];
//将位址轉換為http主機數組,未配置端口則采用預設9200端口,配置了端口則用配置的端口
for (int i = 0; i < httpHosts.length; i++) {
if (!StringUtils.isEmpty(esUris[i])) {
if (esUris[i].contains(":")) {
String[] uris = esUris[i].split(":");
httpHosts[i] = new HttpHost(uris[0], Integer.parseInt(uris[1]), "http");
} else {
httpHosts[i] = new HttpHost(esUris[i], 9200, "http");
}
}
}
//判斷,如果未配置使用者名,則進行無使用者名密碼連接配接,配置了使用者名,則進行使用者名密碼連接配接
if (StringUtils.isEmpty(userName)) {
RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(httpHosts));
return client;
} else {
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY,
//es賬号密碼
new UsernamePasswordCredentials(userName, password));
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(httpHosts)
.setHttpClientConfigCallback((httpClientBuilder) -> {
httpClientBuilder.setMaxConnTotal(maxConnection);
httpClientBuilder.disableAuthCaching();
httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
return httpClientBuilder;
})
.setRequestConfigCallback(builder -> {
builder.setConnectTimeout(connectTimeOut);
return builder;
})
);
return client;
}
}
}
開始實作幾個簡單的功能
/**
*實作了機個操作ES API
* @param <T> 資料實體類
*/
@Component
public class EsUtils<T> {
@Autowired
private RestHighLevelClient client;
/**
* 判斷索引是否存在
* @param index
* @return
* @throws IOException
*/
public boolean existsIndex(String index) throws IOException {
GetIndexRequest request = new GetIndexRequest(index);
boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
return exists;
}
/**
* 建立索引
* @param index
* @throws IOException
*/
public boolean createIndex(String index) throws IOException {
CreateIndexRequest request = new CreateIndexRequest(index);
CreateIndexResponse createIndexResponse =client.indices().create(request,RequestOptions.DEFAULT);
return createIndexResponse.isAcknowledged();
}
/**
* 删除索引
* @param index
* @return
* @throws IOException
*/
public boolean deleteIndex(String index) throws IOException {
DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest(index);
AcknowledgedResponse response = client.indices().delete(deleteIndexRequest, RequestOptions.DEFAULT);
return response.isAcknowledged();
}
/**
* 判斷某索引下文檔id是否存在
* @param index
* @param id
* @return
* @throws IOException
*/
public boolean docExists(String index, String id) throws IOException {
GetRequest getRequest = new GetRequest(index,id);
//隻判斷索引是否存在不需要擷取_source
getRequest.fetchSourceContext(new FetchSourceContext(false));
getRequest.storedFields("_none_");
boolean exists = client.exists(getRequest, RequestOptions.DEFAULT);
return exists;
}
/**
* 添加文檔記錄
* @param index
* @param id
* @param t 要添加的資料實體類
* @return
* @throws IOException
*/
public boolean addDoc(String index,String id,T t) throws IOException {
IndexRequest request = new IndexRequest(index);
request.id(id);
//timeout
request.timeout(TimeValue.timeValueSeconds(1));
request.timeout("1s");
request.source(JSON.toJSONString(t), XContentType.JSON);
IndexResponse indexResponse = client.index(request, RequestOptions.DEFAULT);
RestStatus Status = indexResponse.status();
return Status==RestStatus.OK||Status== RestStatus.CREATED;
}
/**
* 根據id來擷取記錄
* @param index
* @param id
* @return
* @throws IOException
*/
public GetResponse getDoc(String index,String id) throws IOException {
GetRequest request = new GetRequest(index,id);
GetResponse getResponse = client.get(request, RequestOptions.DEFAULT);
return getResponse;
}
/**
* 批量添加文檔記錄
* 沒有設定id ES會自動生成一個,如果要設定 IndexRequest的對象.id()即可
* @param index
* @param list
* @return
* @throws IOException
*/
public boolean bulkAdd(String index, List<T> list) throws IOException {
BulkRequest bulkRequest = new BulkRequest();
//timeout
bulkRequest.timeout(TimeValue.timeValueMinutes(2));
bulkRequest.timeout("2m");
for (int i =0;i<list.size();i++){
bulkRequest.add(new IndexRequest(index)
.source(JSON.toJSONString(list.get(i))));
}
BulkResponse bulkResponse = client.bulk(bulkRequest, RequestOptions.DEFAULT);
return !bulkResponse.hasFailures();
}
/**
* 批量删除和更新就不寫了可根據上面幾個方法來寫
*/
/**
* 更新文檔記錄
* @param index
* @param id
* @param t
* @return
* @throws IOException
*/
public boolean updateDoc(String index,String id,T t) throws IOException {
UpdateRequest request = new UpdateRequest(index,id);
request.doc(JSON.toJSONString(t));
request.timeout(TimeValue.timeValueSeconds(1));
request.timeout("1s");
UpdateResponse updateResponse = client.update(
request, RequestOptions.DEFAULT);
return updateResponse.status()==RestStatus.OK;
}
/**
* 删除文檔記錄
* @param index
* @param id
* @return
* @throws IOException
*/
public boolean deleteDoc(String index,String id) throws IOException {
DeleteRequest request = new DeleteRequest(index,id);
//timeout
request.timeout(TimeValue.timeValueSeconds(1));
request.timeout("1s");
DeleteResponse deleteResponse = client.delete(
request, RequestOptions.DEFAULT);
return deleteResponse.status()== RestStatus.OK;
}
/**
* 根據某字段來搜尋
* @param index
* @param field
* @param key 要收搜的關鍵字
* @throws IOException
*/
public void search(String index,String field ,String key,Integer from,Integer size) throws IOException {
SearchRequest searchRequest = new SearchRequest(index);
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
sourceBuilder.query(QueryBuilders.termQuery(field, key));
//控制搜素
sourceBuilder.from(from);
sourceBuilder.size(size);
//最大搜尋時間。
sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
searchRequest.source(sourceBuilder);
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
System.out.println(JSON.toJSONString(searchResponse.getHits()));
}
}
測試代碼就不貼了,以上我都測試了沒問題的。