springboot整合elasticsearch-RestHighLevelClient api查询
1. 依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-elasticsearch</artifactId> </dependency> <dependency> <groupId>org.elasticsearch.client</groupId> <artifactId>elasticsearch-rest-high-level-client</artifactId> <version>${elastic.version}</version> </dependency> <dependency> <groupId>org.elasticsearch.client</groupId> <artifactId>elasticsearch-rest-client</artifactId> <version>${elastic.version}</version> </dependency> <dependency> <groupId>org.elasticsearch</groupId> <artifactId>elasticsearch</artifactId> <version>${elastic.version}</version> </dependency>
2. 连接
spring: elasticsearch: address: ip:port username: '' password: ''
public RestHighLevelClient elasticsearchClient() { final ClientConfiguration clientConfiguration = ClientConfiguration.builder() .connectedTo(elasticsearchUrl) .withBasicAuth(elasticsearchUsername, elasticsearchPassword)
.withSocketTimeout(10000) .build(); return RestClients.create(clientConfiguration).rest(); }
3. 查询
SearchRequest searchRequest = new SearchRequest(queryindex); BoolQueryBuilder boolQuery = QueryBuilders.boolQuery(); boolQuery.filter(QueryBuilders.matchPhraseQuery("field1", "value1")); boolQuery.filter(QueryBuilders.matchPhraseQuery("field2", "value2")); searchRequest.source().query(boolQuery); SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT); searchResponse.getHits().getHits().getSourceAsString();