Elasticsearch—Java API之index的使用

首先呢 要学会操作ES 我们需要明白一些ES的基本概念 博主知道 大家也不喜欢看文字的东西 所以挑出几个非看不可的大家稍微了解下

1.基本概念

索引(Index)
索引是具有某种相似特征的文档的集合。例如,客户数据索引,产品目录索引,以及订单数据索引。索引由名称(必须全部为小写)标识,此名称用于在对文档进行索引、搜索、更新和删除操作时使用。在单个集群中,您可以根据需要定义任意数量的索引。

类型(Type)
一个索引可以定义一个或多个类型。类型是索引的逻辑类别/分区,你怎么理解都行。通常,为具有一组公共字段的文档定义一种类型。例如,一个博客平台,假如将所有数据存储在单个索引中。在此索引中,可以定义用户数据类型,博客数据类型以及评论数据类型。

文档(document)
文档是可以被索引的基本单位。例如,用一个文档保存某个客户的数据,或者保存单个产品的数据,或者保存单个订单的数据。文档使用JSON表示。在索引/类型中可以存储大量文档。值得注意的是,尽管文档本质上是存放在索引中,但实际上是被索引/分配到索引中的一个类型中。

分片和副本(shards & replicas)
一个索引可能存储海量数据,有可能超过单个节点的硬盘容量。例如,某个索引存储了10亿个文档,占用1TB的硬盘空间,单个节点的硬盘有可能不足以存储那么大的数据量,就算可以存储下,但是可能会降低服务器处理搜索请求的速度。

为了解决这个问题, elasticsearch 提供了分片功能,即将索引细分。创建索引时,可以简单地定义所需的分片数。每个分片本身就具备索引的全部功能,可以存放在集群中的任何一个节点。

在网络/云环境中,任何时候都可能发生故障,分片会非常有用,并强烈建议使用故障转移机制,以防止分片/节点脱机或消失。为此, elasticsearch 允许您将索引的分片复制一份或多份,也就是所谓的复制分片,或简写为副本。

2.Index操作

我们会结合官网的文档来介绍API在Java中的使用 因为我们使用的ElasticSearch是5.6.10的 所以我们选择的Java API应与自己的版本对应

image

2.1.创建索引

image
官方文档中已经给出了我们需要调用的方法 接下来就是在业务中实现的代码 代码的话博主会从controller到接口到实现类一一展示出来


    /**
     * 创建索引
     *
     * @param index       索引
     * @param shardsNum   主分片数
     * @param replicasNum 副本分片数
     * @return net.conn.es.elasticsearch.utils.ResultInfo
     * @creator Conn
     * @date 2018/10/19
     */
    @PutMapping("/createIndexSettings")
    public ResultInfo createIndexSettings(@RequestParam(name = "index") String index,
                                          @RequestParam(name = "shardsNum", defaultValue = "5") Integer shardsNum,
                                          @RequestParam(name = "replicasNum", defaultValue = "1") Integer replicasNum) {
        ResponseEntity result = null;

        try {
            result = iElasticSearchService.createIndexSettings(index, shardsNum, replicasNum);
            return ResultInfo.success().build(result);
        } catch (CustomException e) {
            e.printStackTrace();
            return ResultInfo.failure(e.getMessage());
        }
    }

    
    /**
     * 创建索引
     *
     * @param index       索引
     * @param shardsNum   主分片数
     * @param replicasNum 副本分片数
     * @return org.springframework.http.ResponseEntity
     * @throws CustomException
     * @creator Conn
     * @date 2018/10/19
     */
    ResponseEntity createIndexSettings(String index, Integer shardsNum, Integer replicasNum) throws CustomException;
    
    /**
     * 创建索引
     *
     * @param index       索引
     * @param shardsNum   主分片数
     * @param replicasNum 副本分片数
     * @return org.springframework.http.ResponseEntity
     * @throws CustomException
     * @creator Conn
     * @date 2018/10/19
     */
    @Override
    public ResponseEntity createIndexSettings(String index, Integer shardsNum, Integer replicasNum) throws CustomException {

        if (index == null) {
            throw new CustomException("索引不能为空");
        }

        try {
            //分片数及副本数
            Settings.Builder sb = Settings.builder()
                    .put("index.number_of_shards", shardsNum)
                    .put("index.number_of_replicas", replicasNum);


            //创建索引
            CreateIndexResponse response = client.admin().indices()
                    .prepareCreate(index)
                    .setSettings(sb)
                    .get();

            return new ResponseEntity(response.isAcknowledged(), HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("创建索引业务层异常");
        }
    }

至于异常的话 博主自定义了一个输出异常信息的工具类 也贴出来吧

/**
 * @Author Conn
 * @Date 2018/9/29
 */
public class CustomException extends Exception {
    public CustomException() {
        super();
    }

    public CustomException(String msg) {
        super(msg);
    }
}

2.2.修改索引

image

    /**
     * 修改索引
     *
     * @param index       索引
     * @param replicasNum 副本分片数
     * @return net.conn.es.elasticsearch.utils.ResultInfo
     * @creator Conn
     * @date 2018/10/19
     */
    @PutMapping("/updateIndexSettings")
    public ResultInfo updateIndexSettings(@RequestParam(name = "index") String index,
                                          @RequestParam(name = "replicasNum", defaultValue = "") Integer replicasNum) {
        ResponseEntity result = null;

        try {
            result = iElasticSearchService.updateIndexSettings(index, replicasNum);
            return ResultInfo.success().build(result);
        } catch (CustomException e) {
            e.printStackTrace();
            return ResultInfo.failure(e.getMessage());
        }
    }
    /**
     * 修改索引
     *
     * @param index       索引
     * @param replicasNum 副本分片数
     * @return org.springframework.http.ResponseEntity
     * @throws CustomException
     * @creator Conn
     * @date 2018/10/19
     */
    ResponseEntity updateIndexSettings(String index, Integer replicasNum) throws CustomException;
    /**
     * 修改索引
     *
     * @param index       索引
     * @param replicasNum 副本分片数
     * @return org.springframework.http.ResponseEntity
     * @throws CustomException
     * @creator Conn
     * @date 2018/10/19
     */
    @Override
    public ResponseEntity updateIndexSettings(String index, Integer replicasNum) throws CustomException {
        if (index == null) {
            throw new CustomException("索引不能为空");
        }
        if (replicasNum == null) {
            throw new CustomException("副本数不能为空");
        }

        try {
            //创建条件
            Settings.Builder sb = Settings.builder();

            //如果需要更改副本数 则加进条件  注:索引分片数在索引创建好了之后就不能调整了,只能重建索引
            sb.put("index.number_of_replicas", replicasNum);

            UpdateSettingsResponse response = client.admin().indices()
                    .prepareUpdateSettings(index)
                    .setSettings(sb)
                    .get();
            return new ResponseEntity(response.isAcknowledged(), HttpStatus.OK);

        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("修改索引业务层异常");
        }
    }

这里要提一嘴的就是 当索引分片数在索引创建完成后就不能调整了 只能通过重建索引实现调整

2.3.删除索引

删除索引的话在5.6的文档里没有具体的展示 但是我们根据常用的方法也能猜出来是prepareDelete这个方法

    /**
     * 删除索引
     *
     * @param index 索引
     * @return net.conn.es.elasticsearch.utils.ResultInfo
     * @creator Conn
     * @date 2018/10/19
     */
    @DeleteMapping("/deleteIndex")
    public ResultInfo deleteIndex(@RequestParam(name = "index") String index) {
        try {
            ResponseEntity result = iElasticSearchService.deleteIndex(index);
            return ResultInfo.success().build(result);
        } catch (CustomException e) {
            e.printStackTrace();
            return ResultInfo.failure(e.getMessage());
        }
    }
    /**
     * 删除索引
     *
     * @param index 索引
     * @return org.springframework.http.ResponseEntity
     * @throws CustomException
     * @creator Conn
     * @date 2018/10/19
     */
    ResponseEntity deleteIndex(String index) throws CustomException;
    /**
     * 删除索引
     *
     * @param index 索引
     * @return org.springframework.http.ResponseEntity
     * @throws CustomException
     * @creator Conn
     * @date 2018/10/19
     */
    @Override
    public ResponseEntity deleteIndex(String index) throws CustomException {

        try {
            DeleteIndexResponse response = client.admin().indices()
                    .prepareDelete(index)
                    .get();
            return new ResponseEntity(response.isAcknowledged(), HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("删除索引业务层异常");
        }
    }

2.4.获得索引配置信息

    /**
     * 获得索引配置信息
     *
     * @param index 索引
     * @param type  类型
     * @return net.conn.es.elasticsearch.utils.ResultInfo
     * @creator Conn
     * @date 2018/10/24
     */
    @GetMapping("/getIndexSettings")
    public ResultInfo getIndexSettings(@RequestParam(name = "index", defaultValue = "resource") String index,
                                       @RequestParam(name = "type", defaultValue = "resource") String type) {
        try {

            ResponseEntity result = iElasticSearchService.getIndexSettings(index, type);
            return ResultInfo.success().build(result);
        } catch (CustomException e) {
            e.printStackTrace();
            return ResultInfo.failure(e.getMessage());
        }
    }
    /**
     * 获得索引配置信息
     *
     * @param index 索引
     * @param type  类型
     * @return org.springframework.http.ResponseEntity
     * @throws CustomException
     * @creator Conn
     * @date 2018/10/24
     */
    ResponseEntity getIndexSettings(String index, String type) throws CustomException;
    /**
     * 获得索引配置信息
     *
     * @param index 索引
     * @param type  类型
     * @return org.springframework.http.ResponseEntity
     * @throws CustomException
     * @creator Conn
     * @date 2018/10/24
     */
    @Override
    public ResponseEntity getIndexSettings(String index, String type) throws CustomException {

        try {
            GetSettingsResponse response = client.admin().indices()
                    .prepareGetSettings(index)
                    .get();

            Map<String, Object> map = new HashMap<>();
            for (ObjectObjectCursor<String, Settings> cursor : response.getIndexToSettings()) {
                String index2 = cursor.key;
                Settings settings = cursor.value;
                Integer shards = settings.getAsInt("index.number_of_shards", null);
                Integer replicas = settings.getAsInt("index.number_of_replicas", null);

                map.put("index", index2);
                map.put("shards", shards);
                map.put("replicas", replicas);
            }

            return new ResponseEntity(map, HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("获得索引配置信息业务层异常");
        }
    }

3.测试操作

OK,到这里我们关于索引的一些基本操作介绍好了 那方法也写好了我们要怎么才能知道我们的方法是不是对的呢,这里博主推荐一款很好的接口调试工具Postman.具体软件的用途这里就不赘述了,下面会简单介绍一下软件的用法,当然 你们也可以安装Chrome插件版的.

Postman Download

安装完成后我们启动ElasticSearch以及head插件的windows客户端.如果还没有安装的朋友可以看我之前的关于安装的教程
ElasticSearch启动 运行ES/bin目录下elasticsearch.bat
Head启动 运行cmd 跳转到head目录下 grunt server 回车 如下图所示

image

3.1.创建索引测试

接下来启动项目后打开Postman 我们首先测试创建索引的接口
我们先进入head插件提供的页面看下 如下图 现在里面是空的

image

接下来就是运行Postman工具进行测试了 输入绿色框内的内容 参数的话在下面输入后会自动带入到地址栏

image

创建成功

image

这里博主提一下 因为我们是单节点所以才设置的副本数为0 因为副本不能跟分片放在一个服务器 所以对于单节点来说副本数为0就行 否则会造成副本创建失败 集群健康值也会变yellow

3.2.修改索引测试

image
image

这里便是上面说的因为我们的副本数修改为1了但是副本没地方放所以集群健康值黄了 并且出现了Unassigned 我们只要把副本数重新改成0就行了 当然也可以指定副本安放的服务器地址

3.3.删除索引测试

image
image

OK 删除成功

3.4.获得索引配置信息测试

image
image

后记

OK 下次我们将带来的是Java中Search API的使用

©喜欢我的文章就评论或点个赞吧 至少让我知道有帮助到你

猜你喜欢

转载自blog.csdn.net/tzconn/article/details/83309516