java api implements index management in es

Table of contents

Get the configuration class for the connection

Create an index and set some mapping configuration for the created index

delete index library

Delete documents from the index

Determine whether the index exists


Get the configuration class for the connection

For the specific test environment, please refer to my previous blog: Realizing common searches in ES through java code_The future is very long, don’t just look at the blog in front of you-CSDN Blog

@Configuration
public class ElasticSearchConfig {

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

    @Bean(destroyMethod = "close") //表示连接使用完成后需要关闭
    public RestHighLevelClient restHighLevelClient(){
        String[] split = hostList.split(",");
        //这种写法是考虑到可能会配置多个es节点
        HttpHost[] httpHosts = new HttpHost[split.length];
        for (int i = 0; i < split.length; i++) {
            String item = split[i];
            httpHosts[i] = new HttpHost(item.split(":")[0],Integer.parseInt(item.split(":")[1]),"http");
        }

        return new RestHighLevelClient(RestClient.builder(httpHosts));
    }

}

Create an index and set some mapping configuration for the created index

    //创建索引 并且为创建的索引设置一些映射配置
    @Test
    public void testCreateIndex() throws IOException {
        //创建索引对象
        CreateIndexRequest createIndexRequest = new CreateIndexRequest("test_createindex");
        //设置参数
        createIndexRequest.settings(Settings.builder().put("number_of_shards", "1").put("number_of_replicas", "0"));
        //指定映射方式1 在kibana中测试一遍直接复制过来就行  不过不知道为啥一直报错:Failed to parse content to map 最后还是选择使用java来进行处理了
//        createIndexRequest.mapping(" {\n" +
//                " \t\"properties\": {\n" +
//                "            \"name\":{\n" +
//                "             \"type\":\"keyword\"\n" +
//                "           },\n" +
//                "           \"description\": {\n" +
//                "              \"type\": \"text\"\n" +
//                "           },\n" +
//                "            \"price\":{\n" +
//                "             \"type\":\"long\"\n" +
//                "           },\n" +
//                " \t}\n" +
//                "}", XContentType.JSON);

        //指定映射方式2  索引名称必须小写  这个测试成功了 但是只有一个字段 如果想要多个字段呢?
        Map<String, Object> message = new HashMap<>();
        message.put("type", "text");

        Map<String, Object> name = new HashMap<>();
        name.put("type", "keyword"); //为字段声明映射的数据类型

        //把声明好的字段塞到配置中
        Map<String, Object> properties = new HashMap<>();
        properties.put("message", message);
        properties.put("name",name);

        //把配置塞到映射中
        Map<String, Object> mapping = new HashMap<>();
        mapping.put("properties", properties);
        createIndexRequest.mapping(mapping);


        //设置别名
        createIndexRequest.alias(new Alias("create_index_test"));

        // 额外参数
        //设置超时时间
        createIndexRequest.setTimeout(TimeValue.timeValueMinutes(2));
        //设置主节点超时时间
        createIndexRequest.setMasterTimeout(TimeValue.timeValueMinutes(1));
        //在创建索引API返回响应之前等待的活动分片副本的数量,以int形式表示
        createIndexRequest.waitForActiveShards(ActiveShardCount.from(2));
        createIndexRequest.waitForActiveShards(ActiveShardCount.DEFAULT);


        //操作索引的客户端
        IndicesClient indices = client.indices();
        //执行创建索引库
        CreateIndexResponse response = indices.create(createIndexRequest, RequestOptions.DEFAULT);


    }

delete index library

    //删除索引库
    @Test
    public void testDeleteIndex() throws IOException {
        //判断索引是否存在
        GetIndexRequest getIndexRequest = new GetIndexRequest("test_createindex");
        boolean exists = client.indices().exists(getIndexRequest, RequestOptions.DEFAULT);
        if (exists){
            //删除索引对象
            DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest("test_createindex");
            //操作索引的客户端
            IndicesClient indices = client.indices();
            //执行删除索引
            AcknowledgedResponse delete = indices.delete(deleteIndexRequest, RequestOptions.DEFAULT);
            //得到响应
            boolean acknowledged = delete.isAcknowledged();
            System.out.println(acknowledged);
        }

    }

Delete documents from the index

/**
     * 删除es中指定的数据
     * @param ids 文档的id标识集合
     */
public void deleteIndexDoc(List<String> ids){
    if(ids.size()>0){
        BulkRequest request = new BulkRequest();
        //删除
        for(String id:ids){
            request.timeout(TimeValue.timeValueMinutes(5)).add(new DeleteRequest("test_createindex",id));
        }
        try {
            client.bulk(request, RequestOptions.DEFAULT);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            //可以执行一下释放资源的操作
        }
    }
}

Determine whether the index exists

    // 判断索引是否存在 可以用来初始化搜索的时候用 如果没有索引那就创建索引
    @Test
    public void testExistIndex() throws IOException {
        GetIndexRequest request = new GetIndexRequest("test_createindex");
//        request.local(false);//从主节点返回本地信息或检索状态
//        request.humanReadable(true);//以适合人类的格式返回结果
//        request.includeDefaults(false);//是否返回每个索引的所有默认设置
        boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
        System.out.println(exists);
    }
}

Guess you like

Origin blog.csdn.net/weixin_53142722/article/details/128317245