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;
}
}
这段代码定义了一个SearchService
服务类,它使用ElasticsearchTemplate
来执行基于Spring Data Elasticsearch的搜索查询。它构建了一个NativeSearchQueryBuilder
来定义查询和分页参数,然后使用elasticsearchTemplate.queryForPage
方法来执行查询并返回分页结果。这个例子展示了如何在Spring Boot应用中集成Elasticsearch进行全文搜索。