Elasticearch索引管理CRUD

1.搭建工程

1.1项目结构

在这里插入图片描述

1.2 application.yml

server:
  port: 8081
spring:
  application:
    name: es-crud
springcloud-es:
  elasticsearch:
    hostlist: ${eshostlist:127.0.0.1:9200} #多个结点中间用逗号分隔

1.3 EsConfig

@Configuration
public class EsConfig {
    @Value("${springcloud-es.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));
    }


    //项目主要使用RestHighLevelClient,对于低级的客户端暂时不用
      /*@Bean
    public RestClient restClient(){
        //解析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 RestClient.builder(httpHostArray).build();
    }*/
}

1.4 启动类

@SpringBootApplication
public class EsCrudApplication {
    public static void main(String[] args) {
        SpringApplication.run(EsCrudApplication.class);
    }
}

2.创建索引库以及映射

@Autowired
    RestHighLevelClient highLevelClient;

    //创建索引库以及映射*******************************************************************
    @Test
    public void creatIndex() throws IOException {
        //1.索引库的名称 。2.分片数以及副本数
        CreateIndexRequest createIndexRequest = new CreateIndexRequest("wang-002",
                    Settings.builder().put("number_of_shards", 1)
                                      .put("number_of_replicas", 0).build());
        //设置当前索引库的映射
        createIndexRequest.mapping("doc","{\n" +
                "    \"properties\":{\n" +
                "        \"name\":{\n" +
                "            \"type\":\"text\"\n" +
                "        },\n" +
                "        \"address\":{\n" +
                "            \"type\":\"text\"\n" +
                "        },\n" +
                "        \"age\":{\n" +
                "            \"type\":\"integer\"\n" +
                "        },\n" +
                "        \"pic\":{\n" +
                "            \"type\":\"text\",\n" +
                "            \"index\":false\n" +
                "        },\n" +
                "        \"phone\":{\n" +
                "            \"type\":\"keyword\"\n" +
                "        }\n" +
                "    }\n" +
                "}", XContentType.JSON);
        //使用高版本客户端获取操作对象
        IndicesClient indices = highLevelClient.indices();
        //使用操作对象执行 索引库 对象 创建索引库
        CreateIndexResponse createIndexResponse = indices.create(createIndexRequest);

        boolean shardsAcknowledged = createIndexResponse.isShardsAcknowledged();
        System.out.println("索引库是否创建成功:"+shardsAcknowledged);
    }

3.删除索引

@Test
    public void delIndex() throws IOException {
        //声明删除索引库对象。1.你要删除索引库的名称
        DeleteIndexRequest deleteIndexRequest  = new DeleteIndexRequest("wang-002");
        //声明操作对象
        IndicesClient indices = highLevelClient.indices();
        //使用操作对象删除索引库
        DeleteIndexResponse delete = indices.delete(deleteIndexRequest );
        //解析返回值
        boolean acknowledged = delete.isAcknowledged();
        System.out.println("当前索引库是否删除成功:"+acknowledged);
    }

4.文档添加

//文档添加
    @Test
    public void insertDoc() throws IOException {
        //设置要添加的内容
        Map map=new HashMap<>();
        map.put("name","尼古拉斯赵四");
        map.put("age",18);
        map.put("address","南窑国际");
        map.put("pic","http://asf");
        map.put("phone",12345);

        //设置索引请求对象
        //1.数据添加到的索引库名称。2.类型。3.id 如何不设置,es自动生成id
        IndexRequest indexRequest = new IndexRequest("wang-002","doc","1");
        //将数据放置到索引请求对象中
        indexRequest.source(map);
        //使用高版本客户端添加数据,获取到返回值
        IndexResponse index = highLevelClient.index(indexRequest);
        //解析返回值
        DocWriteResponse.Result result = index.getResult();
        System.out.println("添加结果:"+result);
    }

5.通过ID查询索引库

//通过ID查询索引库
    @Test
    public void testGet() throws IOException {
        //声明通过ID获取客户端的值
        GetRequest getRequest = new GetRequest("wang-002");
        //设置ID
        getRequest.id("1");
        //设置类型
        getRequest.type("doc");
        //使用高版本客户端进行查询
        GetResponse documentFields = highLevelClient.get(getRequest);
        //判断是否为空
        boolean exists = documentFields.isExists();
        if(exists){
            Map<String, Object> sourceAsMap = documentFields.getSourceAsMap();
            System.out.println(sourceAsMap);
        }
    }

6.通过ID来进行修改数据

@Test
    public void update() throws IOException {
        //声明修改的客户端
        UpdateRequest updateRequest = new UpdateRequest();
        updateRequest.id("1");
        updateRequest.type("doc");
        updateRequest.index("wang-002");
        //修改哪些内容
        Map map=new HashMap<>();
        map.put("name","赵四");
        //将要修改的内容设置到修改客户端
        updateRequest.doc(map);
        //使用高版本客户端进行修改
        UpdateResponse update = highLevelClient.update(updateRequest);
        //解析返回值
        DocWriteResponse.Result result = update.getResult();
        System.out.println("修改数据的结果:"+result);
    }

7.删除索引的文档

 //删除索引库的文档
    @Test
    public void testDel() throws IOException {
        //声明删除请求客户端
        DeleteRequest deleteRequest = new DeleteRequest("wang-002");
        //设置删除文档的ID
        deleteRequest.id("1");
        //设置类型
        deleteRequest.type("doc");
        //使用高版本客户端执行删除请求客户端h
        DeleteResponse delete = highLevelClient.delete(deleteRequest);
        //解析返回值
        DocWriteResponse.Result result = delete.getResult();
        System.out.println("删除是否成功:"+result);
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值