IDEA中对ElasticSearch的使用

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)<
  • 3
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值