import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
@Service
public class SearchService {
@Autowired
private RestHighLevelClient client;
public List<SearchItem> searchItems(String keyword) throws IOException {
// 1. 创建查询构建器
SearchRequest searchRequest = new SearchRequest("items");
// 2. 查询条件构建
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
// 2.1. 使用match查询
searchSourceBuilder.query(QueryBuilders.matchQuery("name", keyword));
// 2.2. 分页设置
searchSourceBuilder.from(0);
searchSourceBuilder.size(10);
// 2.3. 排序设置
searchSourceBuilder.sort("id", SortOrder.ASC);
searchRequest.source(searchSourceBuilder);
// 3. 执行查询
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
// 4. 解析结果
SearchHits hits = searchResponse.getHits();
List<SearchItem> itemList = new ArrayList<>();
for (SearchHit hit : hits) {
String json = hit.getSourceAsString();
SearchItem item = JSON.parseObject(json, SearchItem.class);
itemList.add(item);
}
// 5. 返回结果
return itemList;
}
}
这段代码实现了一个简单的搜索服务,它使用Elasticsearch的RestHighLevelClient来执行搜索查询。它构建了一个搜索请求,并设置了查询条件,然后执行查询并解析返回的结果。这个例子展示了如何在实际的电商项目中使用Elasticsearch来实现前台搜索功能。