当courseId
相同时,会根据该ID查找文档并更新contentName
,如果找不到匹配的文档,则插入一个新文档,且新文档的 _id
就是传入的 courseId
@PostMapping("upsertContent")
public Result<String> upsertContent(@RequestBody EsCourse esCourse) throws IOException {
// 使用ObjectMapper将对象转换为JSON字符串
ObjectMapper objectMapper = new ObjectMapper();
String jsonSource = objectMapper.writeValueAsString(esCourse);
// 准备更新请求,这里直接将courseId作为_document_id_,实现根据业务ID的更新或插入
UpdateRequest request = new UpdateRequest("course_content", esCourse.getCourseId().toString())
.doc(jsonSource, XContentType.JSON) // 直接使用转换后的JSON字符串
.upsert(jsonSource, XContentType.JSON) // 如果文档不存在,使用此内容作为插入的数据
.docAsUpsert(true); // 设置为true,确保如果文档不存在,则插入新文档
try {
UpdateResponse response = client.update(request, RequestOptions.DEFAULT);
// 根据需要处理响应,例如返回操作状态或消息
return Result.success("内容操作成功,课程ID: " + esCourse.getCourseId() + ", 操作状态: " + response.status());
} catch (IOException e) {
log.error("更新或插入课程内容失败", e);
throw new RuntimeException("操作课程内容时发生错误", e);
}
}