首先感谢慕课网老师
文档元数据
一个文档不只有数据。它还包含了元数据(metadata)——关于文档的信息。三个必须的元数据节点是:
节点 | 说明 |
---|---|
_index | 文档存储的地方 |
_type | 文档代表的对象的类 |
_id | 文档的唯一标识 |
_type:类型
_id:
id仅仅是一个字符串,它与_index
和_type
组合时,就可以在Elasticsearch中唯一标识一个文档。当创建一个文档,你可以自定义_id
,也可以让Elasticsearch帮你自动生成。
创建索引
127.0.0.1:9200/people 是POST请求
{
"settings":{
"number_of_shards":3,
"number_of_replicas":1
},
"mappings":{
"man":{
"properties":{
"name":{
"type":"text"
},
"country":{
"type":"keyword"
},
"age":{
"type":"integer"
},
"date":{
"type":"dat",
"format":"yyyy-MM-dd HH:mm:ss||yyyy-MM-dd||epoch_millis"
}
}
},
"woman":{
}
}
}
添加数据
127.0.0.1:9200/people/main/
结构和添加索引的结构 一一对应
{
"name":"超重瓦力",
"country":"China",
"age":40,
"date":"1977-03-07"
}
更新数据
127.0.0.1:9200/people/main/1/_update
{
"script":{
"lang":"painlss",
"inline":"ctx._source.age +=10",
"params":{
"age":100
}
}
}
删除索引
127.0.0.1:9200/people/main/1(根据id删除 people中main,提交方式是DELETE)
<!--elasticsearch 客户端-->
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>transport</artifactId>
<version>${elasticsearch.version}</version>
</dependency>
<!--ElasticSearch 5.x 根据官网配置maven 依赖, 由于 5.0x的 jar 内部使用的 apache log4日志。-->
<!--所以要配置额外的依赖支持 org.apache.logging.log4j。-->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.7</version>
</dependency>
package com.binglian;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
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.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
@SpringBootApplication
public class Application {
@Autowired
private TransportClient client;
@GetMapping("/get/book/novel")
@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","novel",id)
.get();
if (!result.isExists()) {
return new ResponseEntity(HttpStatus.NOT_FOUND);
}
return new ResponseEntity(result.getSource(), HttpStatus.OK);
}
@PostMapping("add/book/novel")
@ResponseBody
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 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","novel")
.setSource(content)
.get();
return new ResponseEntity(result.getId(),HttpStatus.OK);
} catch (IOException e) {
e.printStackTrace();
return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@DeleteMapping("delete/book/novel")
@ResponseBody
public ResponseEntity delete(@RequestParam(name = "id") String id){
DeleteResponse result = this.client.prepareDelete("book","novel",id)
.get();
return new ResponseEntity(result.getResult().toString(),HttpStatus.OK);
}
@PutMapping("update/book/novel")
@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","novel",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) {
return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);
}
try {
UpdateResponse result = this.client.update(update).get();
return new ResponseEntity(result.getResult().toString(),HttpStatus.OK);
} catch (ExecutionException | InterruptedException e) {
e.printStackTrace();
return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@PostMapping("query/book/novel")
@ResponseBody
public ResponseEntity query(
@RequestParam(name = "author",required = false) String author,
@RequestParam(name = "title",required = false) String title,
@RequestParam(name = "gt_word_count",defaultValue = "0") int 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 rangeQuery = QueryBuilders.rangeQuery("word_count")
.from(gtWordCount);
if(ltWordCount != null && ltWordCount > 0){
rangeQuery.to(ltWordCount);
}
boolQueryBuilder.filter(rangeQuery);
SearchRequestBuilder builder = this.client.prepareSearch("book")
.setTypes("novel")
.setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
.setQuery(boolQueryBuilder)
.setFrom(0)
.setSize(10);
System.out.println(builder);
SearchResponse response = builder.get();
List<Map<String,Object>> result = new ArrayList<Map<String,Object>>();
for (SearchHit hit : response.getHits()){
result.add(hit.getSource());
}
return new ResponseEntity(result,HttpStatus.OK);
}
@GetMapping("/")
public String index(){
return "index";
}
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}