【ES常用查询】基于ElasticsearchRestTemplate及NativeSearchQuery的查询
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.query.Criteria;
import org.springframework.data.elasticsearch.core.query.CriteriaQuery;
import org.springframework.data.elasticsearch.core.query.IndexQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.Query;
import org.springframework.stereotype.Service;
@Service
public class ElasticsearchService {
@Autowired
private ElasticsearchRestTemplate elasticsearchRestTemplate;
public void index(Document document) {
IndexQuery indexQuery = new IndexQuery();
indexQuery.setId(document.getId().toString());
indexQuery.setObject(document);
elasticsearchRestTemplate.index(indexQuery);
}
public Page<Document> search(String queryString, int page, int size) {
Query query = new NativeSearchQueryBuilder()
.withQuery(queryStringQuery(queryString))
.withPageable(PageRequest.of(page, size))
.build();
return elasticsearchRestTemplate.queryForPage(query, Document.class);
}
private QueryBuilder queryStringQuery(String queryString) {
return new QueryStringQueryBuilder(queryString);
}
}
这个代码示例展示了如何使用Spring Data Elasticsearch的ElasticsearchRestTemplate
来执行索引和搜索操作。index
方法用于将一个Document
对象索引到Elasticsearch中,而search
方法则使用NativeSearchQueryBuilder
来构建一个搜索查询,并返回分页结果。这里的Document
类应该是一个映射到Elasticsearch文档的实体类。
评论已关闭