4. 思云App中使用ES API对课程进行查询。贴出实现的代码,要求可以对课程的标题、作者、分类、描述信息进行查询。 springboot
时间: 2024-03-12 17:45:10 浏览: 159
好的,以下是一个使用ES API对思云App中的课程进行查询的示例代码。它可以对课程的标题、作者、分类、描述信息进行查询。
```java
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.Fuzziness;
import org.elasticsearch.index.query.MultiMatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
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 CourseService {
@Autowired
private RestHighLevelClient client;
// 搜索课程的函数
public List<Course> searchCourses(String query) throws IOException {
// 搜索的index
String index = "courses";
// 创建查询条件
MultiMatchQueryBuilder multiMatchQuery = QueryBuilders.multiMatchQuery(query, "title^3", "author^2", "category^2", "description")
.fuzziness(Fuzziness.AUTO);
// 创建搜索请求
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
sourceBuilder.query(multiMatchQuery);
sourceBuilder.from(0);
sourceBuilder.size(10);
SearchRequest searchRequest = new SearchRequest(index);
searchRequest.source(sourceBuilder);
// 执行搜索
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
// 处理搜索结果
SearchHit[] hits = searchResponse.getHits().getHits();
List<Course> results = new ArrayList<>();
for (SearchHit hit : hits) {
Course course = new Course();
course.setId(hit.getId());
course.setTitle((String) hit.getSourceAsMap().get("title"));
course.setAuthor((String) hit.getSourceAsMap().get("author"));
course.setCategory((String) hit.getSourceAsMap().get("category"));
course.setDescription((String) hit.getSourceAsMap().get("description"));
results.add(course);
}
return results;
}
}
```
你可以将 `query` 参数设置为你想要搜索的关键词,然后调用 `searchCourses` 函数来执行搜索。搜索结果是一个 `Course` 对象列表,每个对象包含课程的 ID、标题、作者、分类和描述信息。
阅读全文