ElasticSearch操作文档

本文详细探讨了XXX的文章,揭示了其独特见解和深入分析。通过丰富的实例,作者展示了文章的亮点和核心观点,为读者提供了有价值的洞见。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用创建索引+自动创建映射(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());
    }


}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值