POM依赖
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.6.2</version>
</dependency>
<properties>
<!--需要覆盖默认的ES版本配置,与本地引入的ES版本保持一致-->
<elasticsearch.version>7.6.2</elasticsearch.version>
</properties>
配置文件
importorg.apache.http.HttpHost;importorg.elasticsearch.client.RestClient;importorg.elasticsearch.client.RestHighLevelClient;importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;@ConfigurationpublicclassElasticSearchClientConfig{@Bean// 硬编码的值可以设置到配置文件,通过@Value读取publicRestHighLevelClientrestHighLevelClient(){//不带账号密码RestHighLevelClient client =newRestHighLevelClient(RestClient.builder(newHttpHost("192.168.0.1",9200,"http")));//带账号密码/*HttpHost host=new HttpHost("192.168.0.1", 9200, HttpHost.DEFAULT_SCHEME_NAME);
RestClientBuilder builder=RestClient.builder(host);
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("elastic","mypass"));
builder.setHttpClientConfigCallback(f -> f.setDefaultCredentialsProvider(credentialsProvider));
RestHighLevelClient client = new RestHighLevelClient( builder);*/System.out.println("es-config-success............");return client;}}
示例代码
importlombok.AllArgsConstructor;importlombok.Data;@Data@AllArgsConstructorpublicclassUser{privateString name;privateint age;}
importjava.io.IOException;importjava.util.ArrayList;importjava.util.UUID;importjava.util.concurrent.TimeUnit;importcom.yfapi.apinodb.entity.User;importorg.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;importorg.elasticsearch.action.bulk.BulkRequest;importorg.elasticsearch.action.bulk.BulkResponse;importorg.elasticsearch.action.delete.DeleteRequest;importorg.elasticsearch.action.delete.DeleteResponse;importorg.elasticsearch.action.get.GetRequest;importorg.elasticsearch.action.get.GetResponse;importorg.elasticsearch.action.index.IndexRequest;importorg.elasticsearch.action.index.IndexResponse;importorg.elasticsearch.action.search.SearchRequest;importorg.elasticsearch.action.search.SearchResponse;importorg.elasticsearch.action.support.master.AcknowledgedResponse;importorg.elasticsearch.action.update.UpdateRequest;importorg.elasticsearch.action.update.UpdateResponse;importorg.elasticsearch.client.RequestOptions;importorg.elasticsearch.client.RestHighLevelClient;importorg.elasticsearch.client.indices.CreateIndexRequest;importorg.elasticsearch.client.indices.CreateIndexResponse;importorg.elasticsearch.client.indices.GetIndexRequest;importorg.elasticsearch.common.unit.TimeValue;importorg.elasticsearch.common.xcontent.XContentType;importorg.elasticsearch.index.query.QueryBuilders;importorg.elasticsearch.index.query.TermQueryBuilder;importorg.elasticsearch.search.SearchHit;importorg.elasticsearch.search.builder.SearchSourceBuilder;importorg.elasticsearch.search.fetch.subphase.FetchSourceContext;importorg.junit.jupiter.api.Test;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.beans.factory.annotation.Qualifier;importorg.springframework.boot.test.context.SpringBootTest;importcom.alibaba.fastjson.JSON;/**
* es7.6.x 高级客户端测试 API
*/@SpringBootTestpublicclassElasticsearchJdApplicationTests{// 面向对象来操作@Autowired@Qualifier("restHighLevelClient")privateRestHighLevelClient client;// 测试索引的创建 Request PUT zzzili_index@TestvoidtestCreateIndex()throwsIOException{// 1、创建索引请求CreateIndexRequest request =newCreateIndexRequest("zzzili_index");// 2、客户端执行请求 IndicesClient,请求后获得响应CreateIndexResponse createIndexResponse = client.indices().create(request,RequestOptions.DEFAULT);System.out.println(createIndexResponse);}// 测试获取索引,判断其是否存在@TestvoidtestExistIndex()throwsIOException{GetIndexRequest request =newGetIndexRequest("zzzili_index2");boolean exists = client.indices().exists(request,RequestOptions.DEFAULT);System.out.println(exists);}// 测试删除索引@TestvoidtestDeleteIndex()throwsIOException{DeleteIndexRequest request =newDeleteIndexRequest("zzzili_index");// 删除AcknowledgedResponse delete = client.indices().delete(request,RequestOptions.DEFAULT);System.out.println(delete.isAcknowledged());}// 测试添加文档@TestvoidtestAddDocument()throwsIOException{// 创建对象User user =newUser("zzzili",3);// 创建请求IndexRequest request =newIndexRequest("zzzili_index");// 规则 put /zzzili_index/_doc/1
request.id(UUID.randomUUID().toString());
request.timeout(TimeValue.timeValueSeconds(1));
request.timeout("1s");// 将我们的数据放入请求 json
request.source(JSON.toJSONString(user),XContentType.JSON);// 客户端发送请求 , 获取响应的结果IndexResponse indexResponse = client.index(request,RequestOptions.DEFAULT);System.out.println(indexResponse.toString());//System.out.println(indexResponse.status());// 对应我们命令返回的状态CREATED*/}// 获取文档,判断是否存在 get /index/doc/1@TestvoidtestIsExists()throwsIOException{GetRequest getRequest =newGetRequest("zzzili_index","1");// 不获取返回的 _source 的上下文了
getRequest.fetchSourceContext(newFetchSourceContext(false));
getRequest.storedFields("_none_");boolean exists = client.exists(getRequest,RequestOptions.DEFAULT);System.out.println(exists);}// 获得文档的信息@TestvoidtestGetDocument()throwsIOException{GetRequest getRequest =newGetRequest("zzzili_index","1");GetResponse getResponse = client.get(getRequest,RequestOptions.DEFAULT);System.out.println(getResponse.getSourceAsString());// 打印文档的内容System.out.println(getResponse);// 返回的全部内容和命令式一样的}// 更新文档的信息@TestvoidtestUpdateRequest()throwsIOException{UpdateRequest updateRequest =newUpdateRequest("zzzili_index","1");
updateRequest.timeout("1s");User user =newUser("zzziliJava",18);
updateRequest.doc(JSON.toJSONString(user),XContentType.JSON);UpdateResponse updateResponse = client.update(updateRequest,RequestOptions.DEFAULT);System.out.println(updateResponse.status());}// 删除文档记录@TestvoidtestDeleteRequest()throwsIOException{DeleteRequest request =newDeleteRequest("zzzili_index","1");
request.timeout("1s");DeleteResponse deleteResponse = client.delete(request,RequestOptions.DEFAULT);System.out.println(deleteResponse.status());}// 特殊的,真的项目一般都会批量插入数据!@TestvoidtestBulkRequest()throwsIOException{BulkRequest bulkRequest =newBulkRequest();
bulkRequest.timeout("10s");ArrayList<User> userList =newArrayList<>();
userList.add(newUser("zzzili1",3));
userList.add(newUser("zzzili2",3));
userList.add(newUser("zzzili3",3));
userList.add(newUser("zzl1",3));
userList.add(newUser("zzl1",3));
userList.add(newUser("zzl1",3));// 批处理请求for(int i =0; i < userList.size(); i++){// 批量更新和批量删除,就在这里修改对应的请求就可以了
bulkRequest.add(newIndexRequest("zzzili_index").id(""+(i +1)).source(JSON.toJSONString(userList.get(i)),XContentType.JSON));}BulkResponse bulkResponse = client.bulk(bulkRequest,RequestOptions.DEFAULT);System.out.println(bulkResponse.hasFailures());// 是否失败,返回 false 代表 成功!}// 查询// SearchRequest 搜索请求// SearchSourceBuilder 条件构造// HighlightBuilder 构建高亮// TermQueryBuilder 精确查询// MatchAllQueryBuilder// xxx QueryBuilder 对应我们刚才看到的命令!@TestvoidtestSearch()throwsIOException{SearchRequest searchRequest =newSearchRequest("zzzili_index");// 构建搜索条件SearchSourceBuilder sourceBuilder =newSearchSourceBuilder();
sourceBuilder.highlighter();// 查询条件,我们可以使用 QueryBuilders 工具来实现// QueryBuilders.termQuery 精确// QueryBuilders.matchAllQuery() 匹配所有TermQueryBuilder termQueryBuilder =QueryBuilders.termQuery("name","zzzili1");// MatchAllQueryBuilder matchAllQueryBuilder =QueryBuilders.matchAllQuery();
sourceBuilder.query(termQueryBuilder);
sourceBuilder.timeout(newTimeValue(60,TimeUnit.SECONDS));
searchRequest.source(sourceBuilder);SearchResponse searchResponse = client.search(searchRequest,RequestOptions.DEFAULT);System.out.println(JSON.toJSONString(searchResponse.getHits()));System.out.println("=================================");for(SearchHit documentFields : searchResponse.getHits().getHits()){System.out.println(documentFields.getSourceAsMap());}}}
本文转载自: https://blog.csdn.net/zzzili/article/details/130964589
版权归原作者 清雨小竹 所有, 如有侵权,请联系我们删除。
版权归原作者 清雨小竹 所有, 如有侵权,请联系我们删除。