package top.fjy8018.elasticsearch.Controller; import lombok.extern.slf4j.Slf4j; import org.elasticsearch.action.update.UpdateRequest; import org.elasticsearch.action.update.UpdateResponse; import org.elasticsearch.client.transport.TransportClient; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.format.annotation.DateTimeFormat; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.concurrent.ExecutionException; /** * @author F嘉阳 * @date 2018-05-19 22:22 */ @RequestMapping("/update/book") @RestController @Slf4j public class UpdateBookController { private static String INDEX = "book"; @Autowired private TransportClient client; /** * 更新数据 * * @param id * @param title * @param author * @param wordCount * @param publishDate * @return */ @PutMapping("/novel") public ResponseEntity update(@RequestParam(name = "id") String id, @RequestParam(name = "title", required = false) String title, @RequestParam(name = "author", required = false) String author, @RequestParam(name = "word_count", required = false) int wordCount, @RequestParam(name = "publish_date", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date publishDate) { String type = "novel"; // 构造更新请求 UpdateRequest request = new UpdateRequest(INDEX, "novel", id); UpdateResponse response = new UpdateResponse(); try { // 构造更新请求体 XContentBuilder content = XContentFactory.jsonBuilder().startObject().field("type", type); if (title != null) { content.field("title", title); } if (author != null) { content.field("author", author); } if (wordCount != 0) { content.field("word_count", wordCount); } if (publishDate != null) { // 格式化日期 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); String dateStr = sdf.format(publishDate); content.field("publish_date", dateStr); } content.endObject(); request.doc(content); response = this.client.update(request).get(); } catch (Exception e) { e.printStackTrace(); log.error("【title】" + title + "【author】" + author + "【wordCount】" + wordCount + "【publishDate】" + publishDate); return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); } if (response.getId().equals(id)) { return new ResponseEntity(HttpStatus.OK); } log.error("【response】" + response.toString() + "【title】" + title + "【author】" + author + "【wordCount】" + wordCount + "【publishDate】" + publishDate); return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); } }