@Configuration
public class ElasticSearchClient {
@Value("${ElasticSearch.Hosts}")
private String hosts;
@Value("${ElasticSearch.UserName}")
private String userName;
@Value("${ElasticSearch.Password}")
private String password;
@SuppressWarnings("deprecation")
@Bean(name="esClient")
public RestHighLevelClient getClient() {
String[] hosts = this.hosts.split(",");
HttpHost[] httpHosts = new HttpHost[hosts.length];
for(int i=0;i<hosts.length;i++) {
httpHosts[i] = new HttpHost(hosts[i], 9200, "http");
}
//设置密码
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(userName, password));
//设置超时
RestClientBuilder builder = RestClient.builder(httpHosts).setRequestConfigCallback(new RestClientBuilder.RequestConfigCallback() {
@Override
public RequestConfig.Builder customizeRequestConfig(RequestConfig.Builder requestConfigBuilder) {
requestConfigBuilder.setConnectTimeout(-1);
requestConfigBuilder.setSocketTimeout(-1);
requestConfigBuilder.setConnectionRequestTimeout(-1);
return requestConfigBuilder;
}
}).setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
@Override
public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
httpClientBuilder.disableAuthCaching();
return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
}
}).setMaxRetryTimeoutMillis(5*60*1000);
RestHighLevelClient client = new RestHighLevelClient(builder);
return client;
}
}
原生通过client查询数据
@Test
public void test1(){
RestHighLevelClient client = elasticSearchClient.getClient();
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
QueryStringQueryBuilder queryStringQueryBuilder = QueryBuilders.queryStringQuery("st1").field("message");
boolQueryBuilder.must(queryStringQueryBuilder);
sourceBuilder.query(boolQueryBuilder);
SearchRequest searchRequest = new SearchRequest("st_test_2021_01_25");// 这里直接配置索引名即可
// searchRequest.indices("st_test_2021_01_25");
searchRequest.source(sourceBuilder);// 把查询函数构造对象注入查询请求中
SearchResponse searchResponse;// 创建响应对象
SearchHits searchHits = null;
try {
searchResponse =client.search(searchRequest,RequestOptions.DEFAULT);
searchHits = searchResponse.getHits();//获取响应中的列表数据
long totalHits = searchHits.getTotalHits();
SearchHit[] hits = searchHits.getHits();
} catch (IOException e) {
e.printStackTrace();
}
}