当前位置:   article > 正文

SpringBoot + Elasticsearch:索引的创建与删除_springboot elasticsearch7.8.0 创建索引

springboot elasticsearch7.8.0 创建索引
  • pojo
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;

@Document(indexName = "stu", type = "_doc")
@Data
public class Stu {

    private Long stuId;

    @Field(store = true)
    private String name;

    @Field(store = true)
    private Integer age;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 创建索引
@Autowired
private ElasticsearchTemplate esTemplate;

@Test
public void createIndexStu() {

    Stu stu = new Stu();
    stu.setStuId(1001L);
    stu.setName("bat man");
    stu.setAge(18);

    IndexQuery indexQuery = new IndexQueryBuilder().withObject(stu).build();
    esTemplate.index(indexQuery);
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

访问Elasticsearch管理页面可以看到索引和数据都成功生成!
在这里插入图片描述

  • 删除索引
@Test
public void deleteIndexStu() {
    esTemplate.deleteIndex(Stu.class);
}
  • 1
  • 2
  • 3
  • 4

执行一下,可以看到node上的索引已被删除!
在这里插入图片描述

不建议使用 ElasticsearchTemplate 对索引进行管理(创建索引,更新映射,删除索引)
索引就像是数据库或者数据库中的表,我们平时是不会是通过java代码频繁的去创建修改删除数据库或者表的,我们只会针对数据做CRUD的操作。
在es中也是同理,我们尽量使用 ElasticsearchTemplate 对文档数据做CRUD的操作。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小蓝xlanll/article/detail/68809
推荐阅读
相关标签
  

闽ICP备14008679号