Spring Boot 集成ElasticSearch:实现搜索功能
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.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;
@Service
public class SearchService {
@Autowired
private ElasticsearchTemplate elasticsearchTemplate;
public Page<Item> searchItems(String query, int page, int size) {
PageRequest pageRequest = PageRequest.of(page, size);
NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder()
.withQuery(queryStringQuery(query).field("name"))
.withPageable(pageRequest);
Page<Item> results = elasticsearchTemplate.queryForPage(nativeSearchQueryBuilder.build(), Item.class);
return results;
}
}
这段代码展示了如何在Spring Boot应用程序中使用ElasticsearchTemplate来执行基本的搜索操作。searchItems
方法接收查询字符串和分页信息,然后构建一个Elasticsearch的查询并执行它,最后返回搜索结果的页面。这个例子简单明了,并且使用了Elasticsearch的Query DSL来定义查询条件。
评论已关闭