本人使用的是ElasticSearch 6.1.3版本,使用springboot来创建项目。
添加maven中pom.xml文件
org.elasticsearch.client
transport
${elasticserach.version}
org.apache.logging.log4j
log4j-core
2.9.1
org.elasticsearch
elasticsearch
${elasticserach.version}
resources下创建log4j配置文件log4j2.properties:
appender.console.type = Console
appender.console.name = console
appender.console.layout.type = PatternLayout
rootLogger.level = info
rootLogger.appenderRef.console.ref = console
注:可以参考官网进行配置: https://www.elastic.co/guide/en/elasticsearch/client/java-api/current/_log4j_2_logger.html
首先,创建elasticsearch 6.1.3配置相关java类:
@Configuration
public class Myconfig {
@Bean
public TransportClient client() throws UnknownHostException {
TransportAddress node = new TransportAddress(
InetAddress.getByName("localhost"), 9300);
Settings settings = Settings.builder()
.put("cluster.name", "jgy").build();
TransportClient client = new PreBuiltTransportClient(settings);
client.addTransportAddress(node);
return client;
}
}
1、创建索引文档查询(GET请求)
@GetMapping("/get/book/man")
@ResponseBody
public ResponseEntity get(@RequestParam(name = "id",defaultValue = "") String id){
if(id.isEmpty()){
return new ResponseEntity(HttpStatus.NOT_FOUND);
}
GetResponse result = this.client.prepareGet("book","man",id).get();
if(!result.isExists()) {
return new ResponseEntity(HttpStatus.NOT_FOUND);
}
return new ResponseEntity(result.getSource(),HttpStatus.OK);
}
2、索引添加文档(POST请求)
@PostMapping("/add/book/man")
@ResponseBody
public ResponseEntity add(@RequestParam(name = "title") String title,
@RequestParam(name = "author") String author,
@RequestParam(name = "word_count") String wordCount,
@RequestParam(name = "publish_date")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
Date publishDate){
try {
XContentBuilder content = XContentFactory.jsonBuilder()
.startObject()
.field("title",title)
.field("author",author)
.field("word_count",wordCount)
.field("publish_date",publishDate.getTime())
.endObject();
IndexResponse result = this.client.prepareIndex("book","man")
.setSource(content)
.get();
return new ResponseEntity(result.getId(),HttpStatus.OK);
} catch (IOException e) {
e.printStackTrace();
return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
3、索引删除文档(DELETE请求)
@DeleteMapping("/delete/book/man")
@ResponseBody
public ResponseEntity delete(@RequestParam(name = "id") String id){
DeleteResponse result = this.client.prepareDelete("book","man",id).get();
return new ResponseEntity(result.getResult().toString(),HttpStatus.OK);
}
4、索引文档查询(POST请求)
@PostMapping("/query/book/man")
@ResponseBody
public ResponseEntity query(@RequestParam(name = "title",required = false) String title,
@RequestParam(name = "author",required = false) String author,
@RequestParam(name = "gt_word_count",defaultValue = "0") String gtWordCount,
@RequestParam(name = "lt_word_count",required = false) Integer ltWordCount){
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
if(author != null){
boolQueryBuilder.must(QueryBuilders.matchQuery("author",author));
}
if(title != null){
boolQueryBuilder.must(QueryBuilders.matchQuery("title",title));
}
RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("word_count").from(gtWordCount);
if(ltWordCount != null && ltWordCount >0){
rangeQueryBuilder.to(ltWordCount);
}
boolQueryBuilder.filter(rangeQueryBuilder);
SearchRequestBuilder builder = this.client.prepareSearch("book")
.setTypes("man")
.setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
.setQuery(boolQueryBuilder)
.setFrom(0)
.setSize(10);
System.out.println(builder);
SearchResponse response = builder.get();
List
5、索引文档修改(PUT请求)
@PutMapping("/update/book/man")
@ResponseBody
public ResponseEntity update(@RequestParam(name = "id") String id,
@RequestParam(name = "title",required = false) String title,
@RequestParam(name = "author",required = false) String author){
UpdateRequest update = new UpdateRequest("book","man",id);
try {
XContentBuilder builder = XContentFactory.jsonBuilder().startObject();
if(title != null){
builder.field("title",title);
}
if(author != null){
builder.field("author",author);
}
builder.endObject();
update.doc(builder);
} catch (IOException e) {
e.printStackTrace();
return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);
}
try {
UpdateResponse result = this.client.update(update).get();
return new ResponseEntity(result.getResult().toString(),HttpStatus.OK);
} catch (Exception e) {
e.printStackTrace();
return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
后端操作elasticSearch基本方法完成,完整代码下载已放在github上。