[ElasticSearch2.x]Java API 之 索引管理

本文涉及的产品
检索分析服务 Elasticsearch 版,2核4GB开发者规格 1个月
简介: 版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/SunnyYoona/article/details/52791465 ElasticSearch为了便于处理索引管理(Indices administration)请求,提供了org.elasticsearch.client.IndicesAdminClient接口。
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/SunnyYoona/article/details/52791465

ElasticSearch为了便于处理索引管理(Indices administration)请求,提供了

org.elasticsearch.client.IndicesAdminClient接口。通过如下代码从 Client 对象中获得这个接口的实现:

IndicesAdminClient indicesAdminClient = client.admin().indices(); IndicesAdminClient定义了好几种prepareXXX()方法作为创建请求的入口点。

1. 判断索引存在

索引存在API用于检查集群中是否存在由prepareExists调用指定的索引。

/**
 * 判断索引是否存在
 * @param client
 * @param index
 * @return
 */
public static boolean isIndexExists(Client client, String index) {
    if(Objects.equal(client, null)){
        logger.info("--------- IndexAPI isIndexExists 请求客户端为null");
        return false;
    }
    if(StringUtils.isBlank(index)){
        logger.info("--------- IndexAPI isIndexExists 索引名称为空");
        return false;
    }
    IndicesAdminClient indicesAdminClient = client.admin().indices();
    IndicesExistsResponse response = indicesAdminClient.prepareExists(index).get();
    return response.isExists();
    /* 另一种方式
    IndicesExistsRequest indicesExistsRequest = new IndicesExistsRequest(index);
    IndicesExistsResponse response = client.admin().indices().exists(indicesExistsRequest).actionGet();*/
}

prepareExists()可以同时指定多个索引:

IndicesExistsResponse response = indicesAdminClient.prepareExists(index1, index2 ....).get();

2. 判断类型存在

类型存在API和索引存在API类似,只是不是用来检查索引是否存在,而是检查指定索引下的指定类型是否存在。为了确保成功返回结果,请确保索引已经存在,否则不会查找到指定的类型。下面代码演示查找索引下的指定类型:

/**
 * 判断类型是否存在
 * @param client
 * @param index
 * @param type
 * @return
 */
public static boolean isTypeExists(Client client, String index, String type) {
    if(!isIndexExists(client, index)){
        logger.info("--------- isTypeExists 索引 [{}] 不存在",index);
        return false;
    }
    IndicesAdminClient indicesAdminClient = client.admin().indices();
    TypesExistsResponse response = indicesAdminClient.prepareTypesExists(index).setTypes(type).get();
    return response.isExists();
}

3. 创建索引API

创建索引API可以用来建立一个新索引。我们可以创建空索引或者给它设置它的映射(mapping)和设置信息(settings)。

3.1 创建空索引

下面代码创建了一个空索引:

/**
 * 创建空索引  默认setting 无mapping
 * @param client
 * @param index
 * @return
 */
public static boolean createSimpleIndex(Client client, String index){
    IndicesAdminClient indicesAdminClient = client.admin().indices();
    CreateIndexResponse response = indicesAdminClient.prepareCreate(index).get();
    return response.isAcknowledged();
}

查看索引状态信息:

{
    "state": "open",
    "settings": {
        "index": {
            "creation_date": "1476078197394",
            "number_of_shards": "5",
            "number_of_replicas": "1",
            "uuid": "rBATEkx_SBq_oUEIlW8ryQ",
            "version": {
                "created": "2030399"
            }
        }
    },
    "mappings": {
        
    },
    "aliases": [
        
    ]
}

3.2. 创建复杂索引

下面代码创建复杂索引,给它设置它的映射(mapping)和设置信息(settings),指定分片个数为3,副本个数为2,同时设置school字段不分词。

/**
 * 创建索引 指定setting
 * @param client
 * @param index
 * @return
 */
public static boolean createIndex(Client client, String index){
    // settings
    Settings settings = Settings.builder().put("index.number_of_shards", 3).put("index.number_of_replicas", 2).build();
    // mapping
    XContentBuilder mappingBuilder;
    try {
        mappingBuilder = XContentFactory.jsonBuilder()
                .startObject()
                    .startObject(index)
                        .startObject("properties")
                            .startObject("name").field("type", "string").field("store", "yes").endObject()
                            .startObject("sex").field("type", "string").field("store", "yes").endObject()
                            .startObject("college").field("type", "string").field("store", "yes").endObject()
                            .startObject("age").field("type", "integer").field("store", "yes").endObject()
                            .startObject("school").field("type", "string").field("store", "yes").field("index", "not_analyzed").endObject()
                        .endObject()
                    .endObject()
                .endObject();
    } catch (Exception e) {
        logger.error("--------- createIndex 创建 mapping 失败:",e);
        return false;
    }
    IndicesAdminClient indicesAdminClient = client.admin().indices();
    CreateIndexResponse response = indicesAdminClient.prepareCreate(index)
            .setSettings(settings)
            .addMapping(index, mappingBuilder)
            .get();
    return response.isAcknowledged();
}

查看索引状态信息:

{
    "state": "open",
    "settings": {
        "index": {
            "creation_date": "1476078400025",
            "number_of_shards": "3",
            "number_of_replicas": "2",
            "uuid": "ToakRDisSYyX7vjH30HR-g",
            "version": {
                "created": "2030399"
            }
        }
    },
    "mappings": {
        "simple-index": {
            "properties": {
                "college": {
                    "store": true,
                    "type": "string" },
                "school": {
                    "index": "not_analyzed",
                    "store": true,
                    "type": "string" },
                "sex": {
                    "store": true,
                    "type": "string" },
                "name": {
                    "store": true,
                    "type": "string" },
                "age": {
                    "store": true,
                    "type": "integer" }
            }
        }
    },
    "aliases": [
        
    ]
}

4. 删除索引

删除索引API允许我们反向删除一个或者多个索引。

/**
 * 删除索引
 * @param client
 * @param index
 */
public static boolean deleteIndex(Client client, String index) {
    IndicesAdminClient indicesAdminClient = client.admin().indices();
    DeleteIndexResponse response = indicesAdminClient.prepareDelete(index).execute().actionGet();
    return response.isAcknowledged();
}

5. 关闭索引

关闭索引API允许我们关闭不使用的索引,进而释放节点和集群的资源,如cpu时钟周期和内存。

/**
 * 关闭索引
 * @param client
 * @param index
 * @return
 */
public static boolean closeIndex(Client client, String index){
    IndicesAdminClient indicesAdminClient = client.admin().indices();
    CloseIndexResponse response = indicesAdminClient.prepareClose(index).get();
    return response.isAcknowledged();
}

测试:

@Test
public void closeIndex() throws Exception {
    String index = "suggestion-index";
    if(!IndexAPI.isIndexExists(client, index)){
        logger.info("--------- closeIndex 索引 [{}] 不存在", index);
        return;
    }
    boolean result = IndexAPI.closeIndex(client, index);
    logger.info("--------- closeIndex {}",result);
}

关闭之前:

image

关闭之后:

image

6. 打开索引

打开索引API允许我们打开我们之前使用关闭索引API

/**
 * 关闭索引
 * @param client
 * @param index
 * @return
 */
public static boolean openIndex(Client client, String index){
    IndicesAdminClient indicesAdminClient = client.admin().indices();
    OpenIndexResponse response = indicesAdminClient.prepareOpen(index).get();
    return response.isAcknowledged();
}

7. 设置映射API

设置映射API允许我们在指定索引上一次性创建或修改一到多个索引的映射。如果设置映射必须确保指定的索引必须存在,否则会报错。

/**
 * 设置映射
 * @param client
 * @param index
 * @param type
 * @return
 */
public static boolean putIndexMapping(Client client, String index, String type){
    // mapping
    XContentBuilder mappingBuilder;
    try {
        mappingBuilder = XContentFactory.jsonBuilder()
                .startObject()
                    .startObject(type)
                        .startObject("properties")
                            .startObject("name").field("type", "string").field("store", "yes").endObject()
                            .startObject("sex").field("type", "string").field("store", "yes").endObject()
                            .startObject("college").field("type", "string").field("store", "yes").endObject()
                            .startObject("age").field("type", "long").field("store", "yes").endObject()
                            .startObject("school").field("type", "string").field("store", "yes").field("index", "not_analyzed").endObject()
                        .endObject()
                    .endObject()
                .endObject();
    } catch (Exception e) {
        logger.error("--------- createIndex 创建 mapping 失败:", e);
        return false;
    }
    IndicesAdminClient indicesAdminClient = client.admin().indices();
    PutMappingResponse response = indicesAdminClient.preparePutMapping(index).setType(type).setSource(mappingBuilder).get();
    return response.isAcknowledged();
}

先创建一个空索引,这样该索引上不会有映射,再使用下面代码添加映射:

@Test
public void putIndexMapping() throws Exception {
    String index = "simple-index";
    String type = "simple-type";
    if(!IndexAPI.isIndexExists(client, index)){
        logger.info("--------- putIndexMapping 索引 [{}] 不存在", index);
        return;
    }
    boolean result = IndexAPI.putIndexMapping(client, index, type);
    logger.info("--------- putIndexMapping {}",result);
}

添加映射之后的索引信息:

{
    "state": "open",
    "settings": {
        "index": {
            "creation_date": "1476108496237",
            "number_of_shards": "5",
            "number_of_replicas": "1",
            "uuid": "9SR5OQJ-QLSARFjmimvs1A",
            "version": {
                "created": "2030399"
            }
        }
    },
    "mappings": {
        "simple-type": {
            "properties": {
                "college": {
                    "store": true,
                    "type": "string" },
                "school": {
                    "index": "not_analyzed",
                    "store": true,
                    "type": "string" },
                "sex": {
                    "store": true,
                    "type": "string" },
                "name": {
                    "store": true,
                    "type": "string" },
                "age": {
                    "store": true,
                    "type": "long" }
            }
        }
    },
    "aliases": [
        
    ]
}

8. 别名API

别名API允许我们可以为已经存在的索引创建别名

/**
 * 为索引创建别名
 * @param client
 * @param index
 * @param alias
 * @return
 */
public static boolean addAliasIndex(Client client, String index , String alias){
    IndicesAdminClient indicesAdminClient = client.admin().indices();
    IndicesAliasesResponse response = indicesAdminClient.prepareAliases().addAlias(index, alias).get();
    return response.isAcknowledged();
}

测试:下面代码为simple-index索引创建一个别名为simple:

@Test
public void addAliasIndex() throws Exception {
    String index = "simple-index";
    String aliasName = "simple";
    boolean result = IndexAPI.addAliasIndex(client, index, aliasName);
    logger.info("--------- addAliasIndex {}", result);
}

结果图:

image

9. 别名存在API

别名存在API允许我们检查是否存在至少一个我们列举出的的别名,注意是判断的索引别名,不是索引。我们可以在别名中使用星号通配符。

/**
 * 判断别名是否存在
 * @param client
 * @param aliases
 * @return
 */
public static boolean isAliasExist(Client client, String... aliases){
    IndicesAdminClient indicesAdminClient = client.admin().indices();
    AliasesExistResponse response = indicesAdminClient.prepareAliasesExist(aliases).get();
    return response.isExists();
}

测试,下面代码检查以sim开头的索引别名和test索引别名是否存在,我们列举的索引别名只要有一个存在就会返回true。

@Test
public void isAliasExist() throws Exception {
    String aliasName = "simp*";
    String aliasName2 = "test";
    boolean result = IndexAPI.isAliasExist(client, aliasName, aliasName2);
    logger.info("--------- isAliasExist {}", result); // true
}

10. 获取别名API

获取别名API可以列举出当前已经定义的的别名

/**
 * 获取别名
 * @param client
 * @param aliases
 */
public static void getAliasIndex(Client client, String... aliases){
    IndicesAdminClient indicesAdminClient = client.admin().indices();
    GetAliasesResponse response = indicesAdminClient.prepareGetAliases(aliases).get();
    ImmutableOpenMap<String, List<AliasMetaData>> aliasesMap = response.getAliases();
    UnmodifiableIterator<String> iterator = aliasesMap.keysIt();
    while(iterator.hasNext()){
        String key = iterator.next();
        List<AliasMetaData> aliasMetaDataList = aliasesMap.get(key);
        for(AliasMetaData aliasMetaData : aliasMetaDataList){
            logger.info("--------- getAliasIndex {}", aliasMetaData.getAlias());
        }
    }
}

测试,下面代码展示以sim开头的别名和test别名:

@Test
public void getAliasIndex() throws Exception {
    String aliasName = "simp*";
    String aliasName2 = "test";
    IndexAPI.getAliasIndex(client, aliasName, aliasName2); // simple test
}

11. 删除别名API

删除别名API允许我们删除指定索引的别名,如果索引没有该别名,则会报错

/**
 * 删除别名
 * @param client
 * @param index
 * @param aliases
 * @return
 */
public static boolean deleteAliasIndex(Client client, String index, String... aliases){
    IndicesAdminClient indicesAdminClient = client.admin().indices();
    IndicesAliasesResponse response = indicesAdminClient.prepareAliases().removeAlias(index, aliases).get();
    return response.isAcknowledged();
}

测试,下面代码删除test-index索引的别名test:

@Test
public void deleteAliasIndex() throws Exception {
    String index = "test-index";
    String aliasName = "test";
    boolean result = IndexAPI.deleteAliasIndex(client, index, aliasName);
    logger.info("--------- deleteAliasIndex {}", result); // true
}

12. 更新设置API

更新设置API允许我们更新特定索引或全部索引的设置。

/**
 * 更新设置
 * @param client
 * @param index
 * @param settings
 * @return
 */
public static boolean updateSettingsIndex(Client client, String index, Settings settings){
    IndicesAdminClient indicesAdminClient = client.admin().indices();
    UpdateSettingsResponse response = indicesAdminClient.prepareUpdateSettings(index).setSettings(settings).get();
    return response.isAcknowledged();
}

测试,下面代码更改副本数为2,修改分片个数会报错:

@Test
public void updateSettingsIndex() throws Exception {
    String index = "test-index";
    Settings settings = Settings.builder().put("index.number_of_replicas", 2).build();
    if(!IndexAPI.isIndexExists(client, index)){
        logger.info("--------- updateSettingsIndex 索引 [{}] 不存在", index);
        return;
    }
    boolean result = IndexAPI.updateSettingsIndex(client, index, settings);
    logger.info("--------- updateSettingsIndex {}", result); // true
}

13. 索引统计API

索引统计API可以提供关于索引,文档,存储以及操作的信息,如获取,查询,索引等。这些信息按类别进行了划分,如果需要输出特定信息需要在请求时指定。下面代码演示了获取指定索引的全部信息:

/**
 * 索引统计
 * @param client
 * @param index
 */
public static void indexStats(Client client, String index) {
    IndicesAdminClient indicesAdminClient = client.admin().indices();
    IndicesStatsResponse response = indicesAdminClient.prepareStats(index).all().get();
    ShardStats[] shardStatsArray = response.getShards();
    for(ShardStats shardStats : shardStatsArray){
        logger.info("shardStats {}",shardStats.toString());
    }
    Map<String, IndexStats> indexStatsMap = response.getIndices();
    for(String key : indexStatsMap.keySet()){
        logger.info("indexStats {}", indexStatsMap.get(key));
    }
    CommonStats commonStats = response.getTotal();
    logger.info("total commonStats {}",commonStats.toString());
    commonStats = response.getPrimaries();
    logger.info("primaries commonStats {}", commonStats.toString());
}

完成代码与演示地址:

https://github.com/sjf0115/OpenDiary/blob/master/ElasticSearchDemo/src/main/java/com/sjf/open/api/IndexAPI.java

https://github.com/sjf0115/OpenDiary/blob/master/ElasticSearchDemo/src/test/java/com/sjf/open/api/IndexAPITest.java

相关实践学习
使用阿里云Elasticsearch体验信息检索加速
通过创建登录阿里云Elasticsearch集群,使用DataWorks将MySQL数据同步至Elasticsearch,体验多条件检索效果,简单展示数据同步和信息检索加速的过程和操作。
ElasticSearch 入门精讲
ElasticSearch是一个开源的、基于Lucene的、分布式、高扩展、高实时的搜索与数据分析引擎。根据DB-Engines的排名显示,Elasticsearch是最受欢迎的企业搜索引擎,其次是Apache Solr(也是基于Lucene)。 ElasticSearch的实现原理主要分为以下几个步骤: 用户将数据提交到Elastic Search 数据库中 通过分词控制器去将对应的语句分词,将其权重和分词结果一并存入数据 当用户搜索数据时候,再根据权重将结果排名、打分 将返回结果呈现给用户 Elasticsearch可以用于搜索各种文档。它提供可扩展的搜索,具有接近实时的搜索,并支持多租户。
目录
相关文章
|
3天前
|
数据采集 JSON Java
Java爬虫获取微店快递费用item_fee API接口数据实现
本文介绍如何使用Java开发爬虫程序,通过微店API接口获取商品快递费用(item_fee)数据。主要内容包括:微店API接口的使用方法、Java爬虫技术背景、需求分析和技术选型。具体实现步骤为:发送HTTP请求获取数据、解析JSON格式的响应并提取快递费用信息,最后将结果存储到本地文件中。文中还提供了完整的代码示例,并提醒开发者注意授权令牌、接口频率限制及数据合法性等问题。
|
3天前
|
数据采集 存储 Java
Java爬虫获取微店店铺所有商品API接口设计与实现
本文介绍如何使用Java设计并实现一个爬虫程序,以获取微店店铺的所有商品信息。通过HttpClient发送HTTP请求,Jsoup解析HTML页面,提取商品名称、价格、图片链接等数据,并将其存储到本地文件或数据库中。文中详细描述了爬虫的设计思路、代码实现及注意事项,包括反爬虫机制、数据合法性和性能优化。此方法可帮助商家了解竞争对手,为消费者提供更全面的商品比较。
|
7天前
|
缓存 Java 应用服务中间件
java语言后台管理若依框架-登录提示404-接口异常-系统接口404异常如何处理-登录验证码不显示prod-api/captchaImage 404 (Not Found) 如何处理-解决方案优雅草卓伊凡
java语言后台管理若依框架-登录提示404-接口异常-系统接口404异常如何处理-登录验证码不显示prod-api/captchaImage 404 (Not Found) 如何处理-解决方案优雅草卓伊凡
35 5
|
25天前
|
算法 Java 程序员
菜鸟之路Day06一一Java常用API
《菜鸟之路Day06——Java常用API》由blue编写,发布于2025年1月24日。本文详细介绍了Java中常用的API,包括JDK7的时间类(Date、SimpleDateFormat、Calendar)和JDK8新增的时间API(ZoneId、Instant、DateTimeFormatter等),以及包装类的使用。通过多个实例练习,如时间计算、字符串转整数、十进制转二进制等,帮助读者巩固所学内容,提升编程技能。文章强调了理论与实践结合的重要性,鼓励读者多做练习以提高学习效率。
76 28
|
1月前
|
JSON Java 数据挖掘
利用 Java 代码获取淘宝关键字 API 接口
在数字化商业时代,精准把握市场动态与消费者需求是企业成功的关键。淘宝作为中国最大的电商平台之一,其海量数据中蕴含丰富的商业洞察。本文介绍如何通过Java代码高效、合规地获取淘宝关键字API接口数据,帮助商家优化产品布局、制定营销策略。主要内容包括: 1. **淘宝关键字API的价值**:洞察用户需求、优化产品标题与详情、制定营销策略。 2. **获取API接口的步骤**:注册账号、申请权限、搭建Java开发环境、编写调用代码、解析响应数据。 3. **注意事项**:遵守法律法规与平台规则,处理API调用限制。 通过这些步骤,商家可以在激烈的市场竞争中脱颖而出。
|
2月前
|
JSON Java Apache
Java基础-常用API-Object类
继承是面向对象编程的重要特性,允许从已有类派生新类。Java采用单继承机制,默认所有类继承自Object类。Object类提供了多个常用方法,如`clone()`用于复制对象,`equals()`判断对象是否相等,`hashCode()`计算哈希码,`toString()`返回对象的字符串表示,`wait()`、`notify()`和`notifyAll()`用于线程同步,`finalize()`在对象被垃圾回收时调用。掌握这些方法有助于更好地理解和使用Java中的对象行为。
|
2月前
|
存储 人工智能 API
(Elasticsearch)使用阿里云 infererence API 及 semantic text 进行向量搜索
本文展示了如何使用阿里云 infererence API 及 semantic text 进行向量搜索。
123 8
|
2月前
|
算法 Java API
如何使用Java开发获得淘宝商品描述API接口?
本文详细介绍如何使用Java开发调用淘宝商品描述API接口,涵盖从注册淘宝开放平台账号、阅读平台规则、创建应用并申请接口权限,到安装开发工具、配置开发环境、获取访问令牌,以及具体的Java代码实现和注意事项。通过遵循这些步骤,开发者可以高效地获取商品详情、描述及图片等信息,为项目和业务增添价值。
121 10
|
2月前
|
存储 Java 数据挖掘
Java 8 新特性之 Stream API:函数式编程风格的数据处理范式
Java 8 引入的 Stream API 提供了一种新的数据处理方式,支持函数式编程风格,能够高效、简洁地处理集合数据,实现过滤、映射、聚合等操作。
103 6
|
3月前
|
存储 安全 数据管理
如何在 Rocky Linux 8 上安装和配置 Elasticsearch
本文详细介绍了在 Rocky Linux 8 上安装和配置 Elasticsearch 的步骤,包括添加仓库、安装 Elasticsearch、配置文件修改、设置内存和文件描述符、启动和验证 Elasticsearch,以及常见问题的解决方法。通过这些步骤,你可以快速搭建起这个强大的分布式搜索和分析引擎。
108 5

热门文章

最新文章