76 lines
2.7 KiB
Java
76 lines
2.7 KiB
Java
package top.fjy8018.elasticsearch.Controller;
|
|
|
|
import lombok.extern.slf4j.Slf4j;
|
|
import org.elasticsearch.action.index.IndexResponse;
|
|
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.PostMapping;
|
|
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;
|
|
|
|
/**
|
|
* @author F嘉阳
|
|
* @date 2018-05-19 16:33
|
|
*/
|
|
@RestController
|
|
@RequestMapping("/add/book")
|
|
@Slf4j
|
|
public class AddBookController {
|
|
|
|
@Autowired
|
|
private TransportClient client;
|
|
|
|
/**
|
|
* 插入数据
|
|
*
|
|
* @param title
|
|
* @param author
|
|
* @param wordCount
|
|
* @param publishDate 限定日期格式为yyyy-MM-dd
|
|
* @return
|
|
*/
|
|
@PostMapping("/novel")
|
|
public ResponseEntity add(@RequestParam(name = "title") String title,
|
|
@RequestParam(name = "author") String author,
|
|
@RequestParam(name = "word_count") int wordCount,
|
|
@RequestParam(name = "publish_date")
|
|
@DateTimeFormat(pattern = "yyyy-MM-dd") Date publishDate) {
|
|
String type = "novel";
|
|
|
|
// 格式化日期
|
|
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
|
|
String dateStr = sdf.format(publishDate);
|
|
|
|
try {
|
|
// 用自带的构造文档
|
|
XContentBuilder content = XContentFactory.jsonBuilder().startObject()
|
|
.field("title", title)
|
|
.field("author", author)
|
|
.field("word_count", wordCount)
|
|
.field("publish_date", dateStr)
|
|
.field("type", type)
|
|
.endObject();
|
|
|
|
IndexResponse response = this.client.prepareIndex("book", type).setSource(content).get();
|
|
|
|
// 返回结果带上新增的ID
|
|
return new ResponseEntity(response.getId(), HttpStatus.OK);
|
|
} catch (IOException e) {
|
|
e.printStackTrace();
|
|
log.error("【title】" + title + "【author】" + author + "【wordCount】" + wordCount + "【publishDate】" + publishDate);
|
|
return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);
|
|
}
|
|
|
|
}
|
|
}
|