首页 > 其他分享 >索引管理--ES客户端(测试创建索引库以及文档的增删改查)

索引管理--ES客户端(测试创建索引库以及文档的增删改查)

时间:2023-09-16 15:48:14浏览次数:41  
标签:-- 改查 索引 文档 new restHighLevelClient public 客户端

这里使用RestClient来搭建ES客户端

  RestClient有两种: JavaLowLevelRESTClient和JavaHighLevelRESTClient  

 这里采用JavaHighLevelRESTClient

首先添加依赖:

<dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-high-level-client</artifactId>
            <version>6.2.1</version>
        </dependency>
        <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>6.2.1</version>
        </dependency>

yml配置

server:
  port: ${port:40100}
spring:
  application:
    name: xc-search-service
xuecheng:
  elasticsearch:
    hostlist: ${eshostlist:127.0.0.1:9200} #多个结点中间用逗号分隔

然后写一个配置类

@Configuration
public class ElasticsearchConfig {

    @Value("${xuecheng.elasticsearch.hostlist}")
    private String hostlist;

    @Bean
    public RestHighLevelClient restHighLevelClient(){
        //解析hostlist配置信息
        String[] split = hostlist.split(",");
        //创建HttpHost数组,其中存放es主机和端口的配置信息
        HttpHost[] httpHostArray = new HttpHost[split.length];
        for(int i=0;i<split.length;i++){
            String item = split[i];
            httpHostArray[i] = new HttpHost(item.split(":")[0], Integer.parseInt(item.split(":")[1]), "http");
        }
        //创建RestHighLevelClient客户端
        return new RestHighLevelClient(RestClient.builder(httpHostArray));
    }
}

测试删除和创建索引库:

@SpringBootTest
@RunWith(SpringRunner.class)
public class TestIndex {
    @Autowired
    RestHighLevelClient restHighLevelClient;


    /**    测试删除索引
     *
     */
    @Test
    public void testDeleteIndex() throws IOException {
        //创建索引请求对象
        DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest("xc_course");
        //删除索引
       /*DeleteIndexResponse deleteIndexResponse = restHighLevelClient.indices().delete(deleteIndexRequest);
        */
            //操作索引的客户端
            IndicesClient indices = restHighLevelClient.indices();
            //删除上面指定的索引
            DeleteIndexResponse deleteIndexResponse = indices.delete(deleteIndexRequest);
        //删除后响应的结果
            //拿到响应
            boolean acknowledged = deleteIndexResponse.isAcknowledged();
        System.out.println(acknowledged);
    }

    /**     测试创建索引库
     * number_of_replicas      副本数量
     * number_of_shards       分片数量
     */
    @Test
    public void testCreateIndex() throws IOException {
        //创建索引请求对象
        CreateIndexRequest createIndexRequest = new CreateIndexRequest("xc_course");
            //对创建的索引对象设置参数
            createIndexRequest.settings(Settings.builder().put("number_of_shards","1").put("number_of_replicas","0"));
                //指定映射
                createIndexRequest.mapping("doc","{\n" +
                        "\t\"properties\": {\n" +
                        "\t\t\"name\": {\n" +
                        "\t\"type\": \"text\"\n" +
                        "\t},\n" +
                        "\t\"description\": {\n" +
                        "\t\t\"type\": \"text\"\n" +
                        "\t},\n" +
                        "\t\"studymodel\": {\n" +
                        "\t\t\"type\": \"keyword\"\n" +
                        "\t}\n" +
                        "\t}\n" +
                        "}", XContentType.JSON);
        //创建操作索引的客户端
        IndicesClient indices = restHighLevelClient.indices();
        //执行创建索引
        CreateIndexResponse createIndexResponse = indices.create(createIndexRequest);
        //拿到响应对象
        boolean acknowledged = createIndexResponse.isAcknowledged();

        System.out.println(acknowledged);
    }

}

文档的CRUD:

/**
     * 添加文档
     */
    @Test
    public void testAddDocument() throws IOException {
        //添加的JSON数据
        HashMap<String, Object> jsonMap = new HashMap<>();
            jsonMap.put("name","springCloud实战");
            jsonMap.put("description","Bootstrap是由Twitter推出的一个前台页面开发框架");
            jsonMap.put("studymodel","201002");
        //索引请求对象
        IndexRequest indexRequest = new IndexRequest("xc_course", "doc");
        //指定文档内容
        IndexRequest source = indexRequest.source(jsonMap);
        //客户端进行HTTP请求   拿到响应
        IndexResponse indexResponse = restHighLevelClient.index(indexRequest);
        //响应结果
        DocWriteResponse.Result result = indexResponse.getResult();
        System.out.println(result);
    }
    /**
     * 查询文档
     */
    @Test
    public void testGetDocument() throws IOException {
        //索引请求对象
        GetRequest indexRequest = new GetRequest("xc_course", "doc","VRLLnIoBrB8-xp-foVZu");
        //客户端查询
        GetResponse getResponse= restHighLevelClient.get(indexRequest);
            //得到文档内容
            Map<String, Object> source = getResponse.getSourceAsMap();
        //打印输出
        System.out.println(source);
    }

    /**
     * 更新文档
     */
    @Test
    public void testUpdateDocument() throws IOException {
        //索引请求对象
        UpdateRequest updateRequest = new UpdateRequest("xc_course", "doc","VRLLnIoBrB8-xp-foVZu");
            //更新信息
            HashMap<String, Object> map = new HashMap<>();
            map.put("name","updateInfo");
            //存入请求
            updateRequest.doc(map);
        //客户端更新
        UpdateResponse updateResponse = restHighLevelClient.update(updateRequest);
        //获取更新状态
        RestStatus status = updateResponse.status();
        //打印输出
        System.out.println(status);
    }

    /**
     * 删除文档
     */
    @Test
    public void testDeleteDocument() throws IOException {
        //索引请求对象
        DeleteRequest deleteRequest = new DeleteRequest("xc_course", "doc","VRLLnIoBrB8-xp-foVZu");
        //客户端删除信息
        DeleteResponse deleteResponse = restHighLevelClient.delete(deleteRequest);
        //获取删除结果
        RestStatus status = deleteResponse.status();
        //打印输出
        System.out.println(status);
    }

 

标签:--,改查,索引,文档,new,restHighLevelClient,public,客户端
From: https://www.cnblogs.com/lksses/p/17706680.html

相关文章

  • 王道408--CN---计算机网络体系结构
    一、考点分布1、选择题2、大题二、性能指标速率速率=数据率=数据传输率=⽐特率单位是b/s,kb/s,Mb/s,Gb/s,Tb/s带宽1、带宽<=>某个信号具有的频带宽度。单位Hz2、带宽<=>表示⽹络的通信线路传输数据的能⼒=单位时间内从⽹络中某信道所能所能通过的“最⾼数据率......
  • Kerberos知识点
    hivejdbc连接串中的principal参数值,为hive-site.xml中hive.server2.authentication.kerberos.principal配置项的值出处:https://www.cnblogs.com/sheng-sjk/p/14535727.html......
  • js call
    js中function其实就是class,functionname就是classname;在方法体中,想要实现继承的效果,可以通过call来实现:call方法更改对象内部this的指向;functionAnimal(name){ this.name=name; this.showName=function(){ console.log(name) }}functionDog(nam......
  • 44-字典-元素的访问-键的访问-值的访问-键值对的访问
           ......
  • Excel 三列数据如何合并为一列
    1、用公式法:假定ABC三列数据要合并,请在D1输入公式=A1&B1&C1,鼠标放在D1单元格右下角,出现十字叉后双击。如果要删除原有三列数据,请选定D列==复制==选择性粘贴==数值,再删除A、B、C三列 2. 用函数法:使用TEXTJOIN()函数,此方法可以设置分隔符。......
  • 第二范式(传递函数依赖问题)
       ......
  • 软件工程-个人项目
    这个作业属于哪个课程https://edu.cnblogs.com/campus/gdgy/CSGrade21-34/这个作业要求在哪里https://edu.cnblogs.com/campus/gdgy/CSGrade21-34/homework/13023这个作业的目标完成一个论文查重系统github链接https://github.com/SoyoOfficial/SoyoOfficial......
  • 【vulnhub】——DC-9靶机
    【vulnhub】——DC-9靶机1.主机发现扫描kali主机C段(Kali和DC-9主机在同一个网关下):发现主机为192.168.108.146,进行详细端口扫描:可以看到靶机开了一个ssh和http服务。可以使用ssh弱密码爆破,但是可以看到22端口的状态是filter,这里先看web部分。2.SQL注入打开相应网页可以......
  • elastic安装
    一、安装ElasticSearch1.ElasticSearch下载地址:https://www.elastic.co/downloads/elasticsearch2.下载安装包后解压(我的是windows8.0以上的版本)打开bin/elasticsearch.bat,通过url127.0.0.1:9200访问涉及到登录认证问题(重置密码)./elasticsearch-reset-password-i--us......
  • 45-字典-元素的添加-修改-删除
           ......