ElasticSearch 认识和深入(三),结合Springboot 操作Api
官网文档地址:https://www.elastic.co/guide/en/elasticsearch/client/java-rest/current/java-rest-low-usage-maven.html
<parent>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-parentartifactId>
<version>2.2.5.RELEASEversion>
parent>
<properties>
<elasticsearch.version>7.9.3elasticsearch.version>
properties>
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-testartifactId>
<scope>testscope>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-aopartifactId>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-context-supportartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-data-redisartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-configuration-processorartifactId>
<optional>trueoptional>
dependency>
<dependency>
<groupId>org.elasticsearch.clientgroupId>
<artifactId>elasticsearch-rest-high-level-clientartifactId>
<version>${elasticsearch.version}version>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>fastjsonartifactId>
<version>${fastjson.version}version>
dependency>
dependencies>
/**
* 功能描述:es配置类
*
* @author: keLeCc
*/
@Configuration
public class ElasticSearchClientConfig {
@Bean
public RestHighLevelClient restHighLevelClient() {
//初始化对象
RestHighLevelClient client = new RestHighLevelClient(
//集群环境多个服务器地址
RestClient.builder(
new HttpHost("127.0.0.1", 9200, "http")
)
);
return client;
}
}
package com.kelecc;
import com.alibaba.fastjson.JSON;
import com.kelecc.entity.User;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.admin.indices.get.GetIndexRequest;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.FetchSourceContext;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
/**
* @author: keLeCc
*/
@SpringBootTest
@RunWith(SpringRunner.class)
public class EsApiTest {
@Autowired
private RestHighLevelClient restHighLevelClient;
/**
* 创建索引,索引必须小写
*
* @throws IOException
*/
@Test
public void testCreateIndex() throws IOException {
CreateIndexRequest request = new CreateIndexRequest("test_java");
CreateIndexResponse createIndexResponse = restHighLevelClient.indices().create(request, RequestOptions.DEFAULT);
System.out.println(createIndexResponse);
}
/**
* 获得索引
*/
@Test
public void getIndex() throws IOException {
//获得test1索引
GetIndexRequest request = new GetIndexRequest().indices("test1");
boolean exists = restHighLevelClient.indices().exists(request, RequestOptions.DEFAULT);
System.out.println(exists);
}
/**
* 删除索引
*/
@Test
public void deleteIndex() throws IOException {
//删除索引
DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest("test1");
AcknowledgedResponse delete = restHighLevelClient.indices().delete(deleteIndexRequest, RequestOptions.DEFAULT);
System.out.println(delete.isAcknowledged());
}
/**
* 创建添加文档
*
*/
@Test
public void addDocument() throws IOException {
//创建对象
User user = new User("张三", 18);
// 创建请求
IndexRequest indexRequest = new IndexRequest("test1");
//创建规则 put /test1/_doc/1
indexRequest.id("1");
indexRequest.timeout("60s");
//数据转成json
indexRequest.source(JSON.toJSONString(user), XContentType.JSON);
//客户端发送请求
IndexResponse indexResponse = restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
System.out.println(indexResponse.toString());
System.out.println(indexResponse.status());
}
/**
* 文档是否存在
* @throws IOException
*/
@Test
public void testIndexExists() throws IOException {
GetRequest request = new GetRequest("test1", "1");
//不获取返回的 _source 的上下文了
request.fetchSourceContext( new FetchSourceContext(false));
request.storedFields("_none_");
boolean exists = restHighLevelClient.exists(request, RequestOptions.DEFAULT);
System.out.println(exists);
}
/**
* 获取文档信息
* @throws IOException
*/
@Test
public void testGetDocument() throws IOException {
GetRequest request = new GetRequest("test1", "1");
//不获取返回的 _source 的上下文了
request.fetchSourceContext( new FetchSourceContext(false));
request.storedFields("_none_");
GetResponse getResponse = restHighLevelClient.get(request, RequestOptions.DEFAULT);
System.out.println(getResponse.getSourceAsString());
}
/**
* 更新文档信息
*/
@Test
public void testUpdateDocument() throws IOException {
UpdateRequest updateRequest = new UpdateRequest("test1", "1");
updateRequest.timeout("60s");
User user = new User("李四",20);
updateRequest.doc(JSON.toJSONString(user),XContentType.JSON);
UpdateResponse updateResponse = restHighLevelClient.update(updateRequest, RequestOptions.DEFAULT);
System.out.println(updateResponse.status());
}
/**
* 删除文档
*/
@Test
public void testDelDocument() throws IOException {
DeleteRequest deleteRequest = new DeleteRequest("test1", "1");
deleteRequest.timeout("60s");
DeleteResponse deleteResponse = restHighLevelClient.delete(deleteRequest, RequestOptions.DEFAULT);
System.out.println(deleteResponse.status());
}
/**
* 批量更新
*/
@Test
public void testBulkDocument()throws IOException{
BulkRequest bulkRequest = new BulkRequest();
bulkRequest.timeout("60s");
List<User> list = new ArrayList<>();
list.add(new User("王五",12));
list.add(new User("刘德华",16));
list.add(new User("张学友",17));
list.add(new User("周星驰",21));
list.add(new User("吴孟达",22));
//批处理请求
for (int i = 0; i < list.size(); i++) {
bulkRequest.add( new IndexRequest("test1")
.source(JSON.toJSONString(list.get(i)),XContentType.JSON));
}
BulkResponse bulkItemResponses = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
System.out.println(bulkItemResponses.status());
}
/**
* 查询
*
*/
@Test
public void testSearch() throws IOException {
SearchRequest searchRequest = new SearchRequest("test1");
//构建查询条件
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
//查询条件,我们可以使用 QueryBuilders 工具来实现
searchSourceBuilder.query();
TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name", "周星驰");
searchSourceBuilder.query(termQueryBuilder);
searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
searchRequest.source(searchSourceBuilder);
SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
System.out.println(JSON.toJSONString(searchResponse.getHits()));
for (SearchHit searchHits: searchResponse.getHits().getHits()){
System.out.println(searchHits.getSourceAsMap());
}
}
}
源码地址:https://gitee.com/Crazycw/kelecc-es.git