使用创建索引+自动创建映射(Elasticsearch帮助我们自动建立映射,后续手动建立映射)
(1)创建POJO 用于存储数据转成JSON
public class Article {
private Long id;//文章ID
private String title;//文章标题
private String content;//文章内容
public Article() {
}
public Article(Long id, String title, String content) {
this.id = id;
this.title = title;
this.content = content;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
(2)创建测试类并完成创建索引和添加文档(自动添加映射)下创建测试类 完成CRUD
@SpringBootTest
//springboot 2.1 有 2.3 之后就没了 不需要了
public class EsTest1 {
@Autowired
private RestHighLevelClient restHighLevelClient;
@Autowired
private ObjectMapper objectMapper;//用过springmvc的@responsebody注解默认使用他
//增 删 查 改
/**
* 需求: 建立 博客系统 搜索文章
* <p>
* 1. 创建索引 index 库
* 2. 创建类型 type 表 默认就是_doc 不需要创建
* 3. 创建映射mapping 约束(ddl) 暂时不管(会默认进行自动的映射)
* <p>
* 4. 添加文档document(一起) 文档需要唯一的标识
*/
@Test
public void add() throws Exception {
//参数1 设置索引名称
IndexRequest indexrequest = new IndexRequest("blog");
//添加设置文档数据 创建POJO对象 ---》转成JSON
Article article = new Article(1L, "文章666", XXX的文章非常666");
String jsonstr = objectMapper.writeValueAsString(article);
//参数1 指定内容 (JSON字符串)
//参数2 指定数据类型 JSON数据类型
indexrequest.source(jsonstr, XContentType.JSON)
//设置文档的唯一标识
.id("1");
//参数1 指定请求对象 (封装各种数据的:请求头 请求体 请求数据类型等...)
//参数2 指定选项 (请求头 的选项 ,可以使用默认的就可以的)
restHighLevelClient.index(indexrequest, RequestOptions.DEFAULT);//添加索引和类型和文档
}
//更新
//查询 根据文档的唯一标识查询
@Test
public void get() throws Exception {
GetRequest getrequest = new GetRequest("blog", "1");
GetResponse documentFields = restHighLevelClient.get(getrequest, RequestOptions.DEFAULT);
String sourceAsString = documentFields.getSourceAsString();
System.out.println(sourceAsString);
}
//删除
@Test
public void delete() throws Exception {
DeleteRequest deleteRequst = new DeleteRequest("blog", "1");
DeleteResponse delete = restHighLevelClient.delete(deleteRequst, RequestOptions.DEFAULT);
System.out.println(delete.getVersion());
}
}