赞
踩
1、ElasticSearch依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
2、构建RestHighLevelClient(高级客户端)对象,实现SpringBoot和elasticSearch集成,返回一个client
在IDEA中,如何使用已经配好的ElasticSearch,将项目个ElasticSearch和SpringBoot整合在一起
首先在官网是看到
翻译:
所以一个高级的客户端(RestHighLevelClient)需要一个Rest低级客户端构造器来构建
所以我们要在定义一个配之类来提供这种功能。elasticSearch就是通过这一步和SpringBoot集成的
@Configuration
public RestHighLevelClient restHighLevelClient(){
@Bean
public RestHighLevelClient restHighLevelClient() {
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(
//整个new HttpHost("localhost",9200,“http”)可以配置多个
//在集群的时候就可以配置多个
new HttpHost("localhost", 9200, "http")));
return client;
}
}
ElasticSearch中的常用方法工具类封装(就是在一个类中封装了对索引的创建、删除等一系列的操作)
/** *@Component声明这个类将被SpringIOC容器扫描装配 */ @Component public class ElasticSearchUtils<T> { @Autowired private RestHighLevelClient restHighLevelClient; /** * 判断索引是否存在 */ public boolean existsIndex(String index) throws IOException { GetIndexRequest request = new GetIndexRequest(index); boolean exists = client.indices().exists(request,RequestOptions.DEFAULT); return exists; } /** *创建索引 */ public boolean createIndex(String index) throws IOException { CreateIndexRequest request = new CreateIndexRequest(index); CreateIndexResponse createIndexResponse=client.indices().create(request,RequestOptions.DEFAULT); return createIndexResponse.isAcknowledged(); } /** *删除索引 */ public boolean deleteIndex(String index) throws IOException { DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest(index); AcknowledgedResponse response = client.indices().delete(deleteIndexRequest, RequestOptions.DEFAULT); return response.isAcknowledged(); } /** *判断某索引下文档id是否存在 */ 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; } /** *添加文档记录 */ public boolean addDoc(String index,String id,T t) throws IOException { IndexRequest request = new IndexRequest(index); request.id(id); //设置超时时间 request.timeout(TimeValue.timeValueSeconds(1)); request.timeout("1s"); //将前端获取来的数据封装成一个对象转换成JSON格式放入请求中 request.source(JSON.toJSONString(t), XContentType.JSON);
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。