第一章第十八节:Elasticsearch之API保存操作

package com.applesnt.onlinemall.search;

import com.alibaba.fastjson.JSON;
import com.applesnt.onlinemall.search.config.ElasticSearchConfig;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.io.IOException;

@RunWith(SpringRunner.class)
@SpringBootTest
public class OnlinemallSearchApplicationTests {

    /*注入es操作对象*/
    @Autowired
    private RestHighLevelClient client;

    /*构建一个实体类*/
    @Data
    @AllArgsConstructor
    public class User{
        private String name;
        private Integer age;
        private String gender;
    }

    @Test
    public void saveIndex() throws IOException {
        /*初始化一个用户对象*/
        User user = new User("zhangsan",18,"男");
        /*把user对象转换成json格式*/
        String jsonUser = JSON.toJSONString(user);

        /*索引操作对象,参数为索引名称*/
        IndexRequest indexRequest = new IndexRequest("userindex");
        /*设置文档id*/
        indexRequest.id("1");
        indexRequest.source(jsonUser, XContentType.JSON);

        /*执行保存操作 ElasticSearchConfig为es配置类*/
        IndexResponse index = client.index(indexRequest, ElasticSearchConfig.COMMON_OPTIONS);
        
        System.out.println(index);

    }

    
}

posted @   努力的校长  阅读(137)  评论(0编辑  收藏  举报
(评论功能已被禁用)
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
点击右上角即可分享
微信分享提示