参考文章链接
SpringBoot操作ES,实现各种骚操作查询 - 知乎
二、整合方式
boot整合es三种方式
SpringBoot整合ES的三种方式(API、REST Client、Data-ES)_jacksonary的博客-CSDN博客_springboot集成es三种方式
三、整合
1、引入依赖
//注意版本一致
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
2、配置类
@Configuration
public class ESConfiguration {
@Bean
public RestHighLevelClient elasticsearchClient() {
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("admin", "admin"));
return new RestHighLevelClient(RestClient.builder(
//使用公网地址 new HttpHost("www.xxx.com", 9200,"https")
new HttpHost("localhost", 9200)
).setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
httpClientBuilder.disableAuthCaching();
return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
}
}));
}
}
3、使用
//搜索条件
SearchRequest searchRequest = new SearchRequest(indexName);
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
//分页
sourceBuilder.from(pageNo);
sourceBuilder.size(pageSize);//聚合时都默认返回10条数据,我们可以通过指定size值来修改这个默认值
//查询条件构造 调用sourceBuilder相关api设置即
//指定字段查询
sourceBuilder.fetchSource(include,exclude);//可以是数组
//超时设置
sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
//查询
searchRequest.source(sourceBuilder);
SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
//结果
SearchHit[] searchHits = searchResponse.getHits().getHits();
List<Map<String, Object>> maps = new ArrayList<>();
for (SearchHit hit : searchHits) {
Map<String, Object> sourceAsMap = hit.getSourceAsMap();
maps.add(sourceAsMap);
}
备注
size的大小不能超过index.max_result_window这个参数的设置,默认为10,000可以通过下面语句设置
PUT /indexName/_settings
{
"index": {
"max_result_window": "10000000"
}
}
设置完查看
GET /indexName/_settings