使用java代码提供一个根据ElasticsearchRestTemplate查询的ElasticSearch查询工具类
时间: 2024-01-06 11:07:12 浏览: 142
可以参考以下代码实现一个基于ElasticsearchRestTemplate的查询工具类:
```java
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Component;
import java.io.IOException;
@Component
public class ElasticsearchQueryUtils {
private final ElasticsearchRestTemplate elasticsearchRestTemplate;
public ElasticsearchQueryUtils(ElasticsearchRestTemplate elasticsearchRestTemplate) {
this.elasticsearchRestTemplate = elasticsearchRestTemplate;
}
public SearchRequest buildSearchRequest(String index, QueryBuilder queryBuilder) {
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(queryBuilder);
return new SearchRequest(index).source(searchSourceBuilder);
}
public <T> T search(String index, QueryBuilder queryBuilder, Class<T> clazz) throws IOException {
SearchRequest searchRequest = buildSearchRequest(index, queryBuilder);
RestHighLevelClient client = elasticsearchRestTemplate.getClient();
return client.search(searchRequest, RequestOptions.DEFAULT).getHits().getHits()[0].getSourceAsObject(clazz);
}
public <T> T search(NativeSearchQuery query, Class<T> clazz) {
return elasticsearchRestTemplate.queryForObject(query, clazz);
}
public <T> NativeSearchQuery buildQuery(QueryBuilder queryBuilder) {
return new NativeSearchQueryBuilder().withQuery(queryBuilder).build();
}
}
```
这个工具类提供了三个方法:
- `buildSearchRequest`: 根据index和查询条件QueryBuilder构建SearchRequest。
- `search`: 根据index和查询条件QueryBuilder执行查询,返回符合条件的第一个对象。
- `buildQuery`: 根据查询条件QueryBuilder构建NativeSearchQuery。
其中,`search`方法使用了`RestHighLevelClient`进行查询,因此需要在Elasticsearch的配置文件中配置`RestHighLevelClient`的bean。`buildQuery`方法可以用于构建更复杂的查询,例如聚合查询。
阅读全文