Java Rest High Level Client简单集成示例

1. ES官方文档地址

ES的连接查询可以使用多种方式,但有的连接方式在高版本的ES中会逐渐取消,所以使用官方推荐的Java High Level Rest Client方式,通过HTTP请求对ES进行连接查询

官方文档地址 (6.4版本)

https://www.elastic.co/guide/en/elasticsearch/client/java-rest/6.4/java-rest-high.html#java-rest-high

2. 集成示例

这里以spring boot的集成案例做一个简单的展示

2.1 maven依赖

	org.elasticsearch.client    
	elasticsearch-rest-high-level-client

    
	org.elasticsearch.client
	elasticsearch-rest-client


	org.elasticsearch  
	elasticsearch

2.2 配置文件示例
#ES的地址
spring.elasticsearch.rest.uris=10.0.0.101:9200,10.0.0.102:9200,10.0.0.103:9200
#用户名,若ES没有开启安全配置则不需要
spring.elasticsearch.rest.username=elastic
#密码,若ES没有开启安全配置则不需要
spring.elasticsearch.rest.password=123456
spring.elasticsearch.rest.timeout=600000
2.3 代码示例
@SpringBootConfiguration
public class EsClientConfiguration {    
@Value("${spring.elasticsearch.rest.uris}")    
private String[] esUris;    
@Value("${spring.elasticsearch.rest.timeout:1000000}")    
private int timeout;    
@Autowired    
private Environment environment;    

@Bean    
public RestHighLevelClient restHighLevelClient() {        
String userName = environment.getProperty("spring.elasticsearch.rest.username");        String password = environment.getProperty("spring.elasticsearch.rest.password");        HttpHost[] httpHosts = new HttpHost[esUris.length];        
//将地址转换为http主机数组,未配置端口则采用默认9200端口,配置了端口则用配置的端口       
for (int i = 0; i < httpHosts.length; i++) {            
	if (!StringUtils.isEmpty(esUris[i])) {               
		if (esUris[i].contains(":")) {                    
			String[] uris = esUris[i].split(":");                    
			httpHosts[i] = new HttpHost(uris[0], Integer.parseInt(uris[1]), "http");              } else {                    
			httpHosts[i] = new HttpHost(esUris[i], 9200, "http");                
		}            
	}        
}        
//判断,如果未配置用户名,则进行无用户名密码连接,配置了用户名,则进行用户名密码连接        
if (StringUtils.isEmpty(userName)) {            
	RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(httpHosts));
    return client;        
} else { 
	final CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); 
    credentialsProvider.setCredentials(AuthScope.ANY,
    //es账号密码                    
    new UsernamePasswordCredentials(userName, password));            
    RestHighLevelClient client = new RestHighLevelClient(
    	RestClient.builder(httpHosts)
        .setHttpClientConfigCallback((httpClientBuilder) -> { 
        	//这里可以设置一些参数,比如cookie存储、代理等等     
        	httpClientBuilder.disableAuthCaching();           
        	return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider); 
        	})            
        );            
  	return client;        
    }    
 }
 }
/** 
* @Description: 获取索引下的数据 
* @Param: [index, type, from, size] 
* @return: org.elasticsearch.action.search.SearchResponse 
* @Author: pengming.xu 
* @Date: 2019/3/27 15:57 
*/
public SearchResponse getAllIndexData(String index, String type, int from, int size) throws IOException {    
	SearchRequest request = new SearchRequest(index);
	SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); 
    searchSourceBuilder.from(from);    
    searchSourceBuilder.size(size);    
    searchSourceBuilder.query(QueryBuilders.matchAllQuery()); 
    request.source(searchSourceBuilder);    
    return client.search(request,RequestOptions.DEFAULT);
}
/** 
* @Description 多条件查询ES索引中的数据 
* @Param 
* @Return 
* @Date 2019-7-29 14:43 
* @Author xupm 
* @Since 
**/
public SearchResponse searchLogs(String indexPattern, List> searchList, String dateField, int from, int size, String startTime, String endTime) throws IOException {    
	SearchRequest request = new SearchRequest(indexPattern);    
	SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();    
	//若按时间进行排序,在查询没有时间字段的索引时会出错,暂时注销   
    BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();    
    if (StringUtils.isNotEmpty(dateField)){        
    	searchSourceBuilder.sort(new FieldSortBuilder(dateField).order(SortOrder.DESC)); 
        if(StringUtils.isEmpty(endTime)) {
	boolQueryBuilder.must(QueryBuilders.rangeQuery(dateField).gte(startTime).format("yyyy-MM-dd HH:mm:ss"));        
     	}else {
            boolQueryBuilder.must(QueryBuilders.rangeQuery(dateField).gte(startTime).lte(endTime).format("yyyy-MM-dd HH:mm:ss"));        
        }    
    }    
    BoolQueryBuilder innerBoolQueryBuilder = QueryBuilders.boolQuery();    
    for (Map searchMap:searchList) { 
    	createQueryBuilder(boolQueryBuilder,innerBoolQueryBuilder,searchMap);    
    }    
    searchSourceBuilder.query(boolQueryBuilder);    
    searchSourceBuilder.from(from);    
    searchSourceBuilder.size(size);    
    request.source(searchSourceBuilder);    
    return client.search(request,RequestOptions.DEFAULT);
}

你可能感兴趣的:(ElasticSearch)