ElasticSearch学习笔记十八(Java 高级客户端——索引管理)

本学习笔记基于ElasticSearch 7.10版本,旧版本已经废弃的功能暂时不做笔记,以后有涉及到再做补充。

Es 官方的高级客户端,这个应该算是目前的主流。就像上一章所说的,它将很多请求参数和响应参数都封装成了相应的 API,直接调用这些API即可。

1、创建索引

首先我们还是同样创建一个 Maven 项目,引入依赖。需要注意,依赖的版本和 Es 的版本要对应:

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

创建一个索引:

public class HighLevelTest {
    public static void main(String[] args) throws IOException {
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(
                new HttpHost("localhost", 9200, "http"),
                new HttpHost("localhost", 9201, "http"),
                new HttpHost("localhost", 9202, "http")
        ));
        // 1.删除已经存在的索引
        DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest("blog");
        client.indices().delete(deleteIndexRequest, RequestOptions.DEFAULT);
        // 2.创建一个索引
        CreateIndexRequest blog = new CreateIndexRequest("blog");
        // 3.配置 settings
        blog.settings(Settings.builder().put("index.number_of_shards", 3).put("index.number_of_replicas", 1));
        // 4.配置字段类型,字段类型可以通过 JSON 字符串、Map 以及 XContentBuilder 三种方式来构建
        // 4.1.json 字符串的方式
        blog.mapping("{\"properties\": {\"title\": {\"type\": \"text\"}}}", XContentType.JSON);
        // 5.执行请求,创建索引
        client.indices().create(blog, RequestOptions.DEFAULT);
        // 6.关闭 client
        client.close();
    }
}

通过 Map 构建 mapping:

		// 4.2.Map 方式
        Map<String, String> title = new HashMap<>();
        title.put("type", "text");
        Map<String, Object> properties = new HashMap<>();
        properties.put("title", title);
        Map<String, Object> mappings = new HashMap<>();
        mappings.put("properties", properties);
        blog.mapping(mappings);
        // 5.执行请求,创建索引
        client.indices().create(blog1, RequestOptions.DEFAULT);
        ...

通过 XContentBuilder 构建 mapping:

		// 4.3.XContentBuilder 方式
        XContentBuilder builder = XContentFactory.jsonBuilder();
        builder.startObject();
        builder.startObject("properties");
        builder.startObject("title");
        builder.field("type", "text");
        builder.endObject();
        builder.endObject();
        builder.endObject();
        blog.mapping(builder);
        // 5.执行请求,创建索引
        client.indices().create(blog1, RequestOptions.DEFAULT);
        ...

给索引配置别名:

		// 配置别名
        blog1.alias(new Alias("blog_alias"));
        // 5.执行请求,创建索引
        client.indices().create(blog1, RequestOptions.DEFAULT);
        ...

如果觉得调用 API 太麻烦,也可以跳过步骤 3 和 4,直接使用 JSON:

		//直接同构 JSON 配置索引
        blog1.source("{\"settings\": {\"number_of_shards\": 3,\"number_of_replicas\": 1},\"mappings\": {\"properties\": {\"title\": {\"type\": \"keyword\"}}},\"aliases\": {\"blog_alias\": {}}}", XContentType.JSON);
        // 5.执行请求,创建索引
        client.indices().create(blog1, RequestOptions.DEFAULT);
        ...

其他的可选配置:

		//请求超时时间,连接所有节点的超时时间
        blog1.setTimeout(TimeValue.timeValueMinutes(2));
        //连接 master 节点的超时时间
        blog1.setMasterTimeout(TimeValue.timeValueMinutes(1));
        // 5.执行请求,创建索引
        client.indices().create(blog1, RequestOptions.DEFAULT);

2、查询索引

前面创建索引的时候,我们第一步是先删除已有的索引。
需要注意,如果索引不存在,删除索引这一步会报错,因此需要先查询索引是否存在:

public class HighLevelTest2 {
    public static void main(String[] args) throws IOException {
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(
                new HttpHost("localhost", 9200, "http"),
                new HttpHost("localhost", 9201, "http"),
                new HttpHost("localhost", 9202, "http")
        ));
        GetIndexRequest blog = new GetIndexRequest("blog");
        boolean exists = client.indices().exists(blog, RequestOptions.DEFAULT);
        System.out.println("exists:" + exists);
        // 关闭 client
        client.close();
    }
}

3、关闭/打开索引

public class HighLevelTest3 {
    public static void main(String[] args) throws IOException {
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(
                new HttpHost("localhost", 9200, "http"),
                new HttpHost("localhost", 9201, "http"),
                new HttpHost("localhost", 9202, "http")
        ));
        // 关闭索引
        CloseIndexRequest blog = new CloseIndexRequest("blog");
        CloseIndexResponse close = client.indices().close(blog, RequestOptions.DEFAULT);
        List<CloseIndexResponse.IndexResult> indices = close.getIndices();
        for (CloseIndexResponse.IndexResult index : indices) {
            System.out.println("index.getIndex()" + index.getIndex());
        }
        // 打开索引
        OpenIndexRequest blog1 = new OpenIndexRequest("blog");
        OpenIndexResponse open = client.indices().open(blog1, RequestOptions.DEFAULT);
        // 关闭 client
        client.close();
    }
}

索引关闭之后,在head面板上查看索引状态为null
在这里插入图片描述

4、修改索引

我们尝试修改索引的index.blocks.write属性:

public class HighLevelTest4 {
    public static void main(String[] args) throws IOException {
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(
                new HttpHost("localhost", 9200, "http"),
                new HttpHost("localhost", 9201, "http"),
                new HttpHost("localhost", 9202, "http")
        ));
        UpdateSettingsRequest update = new UpdateSettingsRequest("blog");
        update.settings(Settings.builder().put("index.blocks.write", true).build()); // 禁用write
        client.indices().putSettings(update, RequestOptions.DEFAULT);
        // 6.关闭 client
        client.close();
    }
}

在这里插入图片描述
设置之后,再往索引中写入内容,就会报错禁止:
在这里插入图片描述

5、克隆索引

被克隆的索引需要是只读索引,可以通过上面的方式设置索引为只读。

public class HighLevelTest5 {
    public static void main(String[] args) throws IOException {
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(
                new HttpHost("localhost", 9200, "http"),
                new HttpHost("localhost", 9201, "http"),
                new HttpHost("localhost", 9202, "http")
        ));
        ResizeRequest resize = new ResizeRequest("blog2", "blog");
        client.indices().clone(resize, RequestOptions.DEFAULT);
        // 6.关闭 client
        client.close();
    }
}

6、查看索引信息

public class HighLevelTest6 {
    public static void main(String[] args) throws IOException {
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(
                new HttpHost("localhost", 9200, "http"),
                new HttpHost("localhost", 9201, "http"),
                new HttpHost("localhost", 9202, "http")
        ));
        GetSettingsRequest request = new GetSettingsRequest().indices("blog"); // 支持数组参数,获取多个索引信息
        // 设置需要获取的具体参数名,不设置则返回所有参数
        request.names("index.blocks.write");
        GetSettingsResponse response = client.indices().getSettings(request, RequestOptions.DEFAULT);
        ImmutableOpenMap<String, Settings> settings = response.getIndexToSettings();
        System.out.println(settings);
        // 查看某个索引中的参数
        String s = response.getSetting("blog", "index.number_of_replicas");
        System.out.println(s);
        // 6.关闭 client
        client.close();
    }
}

7、Refresh & Flush

refreshflush 操作都是保存文档数据,两者都是有ElasticSearch自动执行,只是执行频率和数据保存位置有区别:

  • refresh:在ElasticSearch中,文档创建后首先添加到内存缓冲区中,然后使用refresh操作将内存缓冲区中的数据拷贝到Lucene的segment中。refresh操作发生在内存中,每秒执行一次。
  • flush:将内存中的数据持久化到磁盘中,默认30分钟执行一次。

下面代码只作为演示,实际执行效果是看不到的:

public class HighLevelTest7 {
    public static void main(String[] args) throws IOException {
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(
                new HttpHost("localhost", 9200, "http"),
                new HttpHost("localhost", 9201, "http"),
                new HttpHost("localhost", 9202, "http")
        ));
        RefreshRequest request = new RefreshRequest("blog");
        client.indices().refresh(request, RequestOptions.DEFAULT);
        FlushRequest flushRequest = new FlushRequest("blog");
        client.indices().flush(flushRequest, RequestOptions.DEFAULT);
        //关闭 client
        client.close();
    }
}

8、索引别名

索引的别名类似于 MySQL 中的视图。

8.1、添加别名

在前面创建索引的时候,我们可以添加索引别名。下面演示,创建好索引之后,如何添加别名。

添加一个普通的别名,使用该别名和使用索引效果一样:

public class HighLevelTest8 {
    public static void main(String[] args) throws IOException {
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(
                new HttpHost("localhost", 9200, "http"),
                new HttpHost("localhost", 9201, "http"),
                new HttpHost("localhost", 9202, "http")
        ));
        IndicesAliasesRequest request = new IndicesAliasesRequest();
        IndicesAliasesRequest.AliasActions aliasAction = new IndicesAliasesRequest.AliasActions(IndicesAliasesRequest.AliasActions.Type.ADD);
        aliasAction.index("books").alias("books_alias");
        request.addAliasAction(aliasAction);
        client.indices().updateAliases(request, RequestOptions.DEFAULT);
        // 6.关闭 client
        client.close();
    }
}

添加一个带 filter 的别名,自动过滤 name 中含有 java 的文档:

public class HighLevelTest8 {
    public static void main(String[] args) throws IOException {
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(
                new HttpHost("localhost", 9200, "http"),
                new HttpHost("localhost", 9201, "http"),
                new HttpHost("localhost", 9202, "http")
        ));
        IndicesAliasesRequest request = new IndicesAliasesRequest();
        IndicesAliasesRequest.AliasActions aliasAction = new IndicesAliasesRequest.AliasActions(IndicesAliasesRequest.AliasActions.Type.ADD);
        aliasAction.index("books").alias("books_alias2").filter("{\"term\": {\"name\": \"java\"}}");
        request.addAliasAction(aliasAction);
        client.indices().updateAliases(request, RequestOptions.DEFAULT);
        // 6.关闭 client
        client.close();
    }
}

8.2、删除别名

有两种方式删除别名:

public class HighLevelTest9 {
    public static void main(String[] args) throws IOException {
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(
                new HttpHost("localhost", 9200, "http"),
                new HttpHost("localhost", 9201, "http"),
                new HttpHost("localhost", 9202, "http")
        ));
        IndicesAliasesRequest request = new IndicesAliasesRequest();
        IndicesAliasesRequest.AliasActions aliasAction = new IndicesAliasesRequest.AliasActions(IndicesAliasesRequest.AliasActions.Type.REMOVE);
        aliasAction.index("books").alias("books_alias");
        request.addAliasAction(aliasAction);
        client.indices().updateAliases(request, RequestOptions.DEFAULT);
        // 6.关闭 client
        client.close();
    }
}

第二种方式:

public class HighLevelTest9 {
    public static void main(String[] args) throws IOException {
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(
                new HttpHost("localhost", 9200, "http"),
                new HttpHost("localhost", 9201, "http"),
                new HttpHost("localhost", 9202, "http")
        ));
        DeleteAliasRequest deleteAliasRequest = new DeleteAliasRequest("books", "books_alias2");
        client.indices().deleteAlias(deleteAliasRequest, RequestOptions.DEFAULT);
        // 6.关闭 client
        client.close();
    }
}

8.3、判断别名是否存在

和删除索引一样,删除别名时如果别名不存在,也会报错。所以删除之前可以先判断别名是否存在:

public class HighLevelTest10 {
    public static void main(String[] args) throws IOException {
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(
                new HttpHost("localhost", 9200, "http"),
                new HttpHost("localhost", 9201, "http"),
                new HttpHost("localhost", 9202, "http")
        ));
        GetAliasesRequest request = new GetAliasesRequest("books_alias");
        //指定查看某一个索引的别名,不指定,则会搜索所有的别名
        request.indices("books");
        boolean existsAlias = client.indices().existsAlias(request, RequestOptions.DEFAULT);
        System.out.println(existsAlias);
        // 6.关闭 client
        client.close();
    }
}

8.4、获取别名

public class HighLevelTest11 {
    public static void main(String[] args) throws IOException {
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(
                new HttpHost("localhost", 9200, "http"),
                new HttpHost("localhost", 9201, "http"),
                new HttpHost("localhost", 9202, "http")
        ));
        GetAliasesRequest request = new GetAliasesRequest("books_alias2");
        request.indices("books");
        GetAliasesResponse response = client.indices().getAlias(request, RequestOptions.DEFAULT);
        Map<String, Set<AliasMetadata>> aliases = response.getAliases();
        System.out.println(aliases);
        // 6.关闭 client
        client.close();
    }
}

版权声明:

本文仅记录ElasticSearch学习心得,如有侵权请联系删除。
更多内容请访问原创作者:江南一点雨
微信公众号:江南一点雨

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值