RestHighLevelClient操作7.10.0(二)ElasticSearch索引及别名详解

为便于更好的理解,这里示例会指出通过 Kibana 的 Restful 工具操作与对应的 Java 代码操作的两个示例。


ElasticSearch索引及别名操作

  • 一、项目结构
  • 二、Restful Index APIs介绍
  • 三、项目源码
    • 3.1 类ESFieldTypeConstains.java
    • 3.2 类 ESMappingField.java
    • 3.3 SearchGoodsMappingDTO.java
    • 3.4 接口IElasticsearchIndexService.java
    • 3.5 接口实现类ElasticsearchIndexServiceImpl.java
    • 3.6 控制层,便于测试ElasticsearchIndexController.java
  • 四、实践
    • 1.给索引添加mapping
    • 2.使用别名重建索引的过程
      • 2.1通过kibana添加一条文档数据
      • 2.2 创建一个新的索引及mapping
      • 2.3执行重建索引接口
      • 2.4 进行别名替换
      • 2.5 删除旧索引


一、项目结构

RestHighLevelClient操作7.10.0(二)ElasticSearch索引及别名详解_第1张图片

主要项目目录结构介绍

  • annotation目录。自定义一些注解类。
  • dto目录。存放一搜索实体类。
  • config目录。项目的配置文件,初始化Elasticsearch连接等操作。
  • controller目录。搜索请求,系统索引,数据类型创建请求入口。
  • servcie目录。执行搜索请求等服务类。

二、Restful Index APIs介绍

官方文档Index APIs有很好的介绍
特别注意:

  • 更新索引别名,别名不能与索引同名;
  • 一个索引可以有多个别名,不同的索引可以有相同的别名。
    RestHighLevelClient操作7.10.0(二)ElasticSearch索引及别名详解_第2张图片
    这里简单介绍几个

#创建索引
PUT /blog

#创建索引及分片信息
PUT /blog
{
  "settings": {
    "index": {
      "number_of_shards": 3,  
      "number_of_replicas": 2 
    }
  }
}

#获取索引信息
GET /blog

#索引是否存在
HEAD /blog
#索引别名是否存在
HEAD /_alias/blog_alias

#更新索引别名,别名不能与索引同名
#一个索引可以有多个别名,不同的索引可以有相同的别名
POST /blog/_alias/blog_alias

#添加索引别名
POST /_aliases 
{ "actions":[ { "add":{"index":"blog","alias":"alias1"} } ] } 


#获取索引别名
GET /blogs/_alias

#删除索引
DELETE /blogs

#删除索引别名
DELETE /blog/_alias/blog_alias

可在kibana上做相关操作
RestHighLevelClient操作7.10.0(二)ElasticSearch索引及别名详解_第3张图片

三、项目源码

ElasticSearch 连接配置可参考上一篇内容
RestHighLevelClient操作7.10.0(一)ElasticSearch 连接配置,这里不再赘述。

3.1 类ESFieldTypeConstains.java

该类用于存放一些es中的常量,便于统一管理。

package com._520xuzai.es7.constains;


/**
 * \* Created with IntelliJ IDEA.
 * \* User: 煦仔
 * \* Date: 2020-12-22
 * \* Time: 10:43
 * \* To change this template use File | Settings | File Templates.
 * \* Description: es中的一些常量信息
 * \
 */
public class ESFieldTypeConstains {


    //分词策略
    public static final String SETANALYZER_IK_MAX_WORD = "ik_max_word";
    public static final String SETANALYZER_KEYWORD = "keyword";
    public static final String SETANALYZER_standard = "standard";
    public static final String SETANALYZER_IK_smart = "ik_smart";


    //数据类型
    public static final String DATATYPE_KEYWORD = "keyword";
    public static final String DATATYPE_TEXT = "text";
    public static final String DATATYPE_LONG = "long";
    public static final String DATATYPE_INTEGER = "integer";

}

3.2 类 ESMappingField.java

该注解类用于注解映射到ES中的数据字段,类似Hibernate中实体字段映射数据库中的表字段。

package com._520xuzai.es7.annotation;

import java.lang.annotation.*;

/**
 * \* Created with IntelliJ IDEA.
 * \* User: 煦仔
 * \* Date: 2020-12-22
 * \* Time: 15:23
 * \* To change this template use File | Settings | File Templates.
 * \* Description: 该注解类用于注解映射到ES中的数据字段,类似Hibernate中实体字段映射数据库中的表字段
 * \
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@Documented
@Inherited
public @interface ESMappingField {

    /**
     * 字段名称
     * @return
     */
    String fieldName() default "";

    /**
     * 数据类型
     * @return
     */
    String dataType() default "";

    /**
     * 使用哪种分词器
     * @return
     */
    String setAnalyzer() default "";

    /**
     * 是否使用分词功能
     * @return
     */
    boolean isAnalyze() default false;
}
 

3.3 SearchGoodsMappingDTO.java

商品搜索映射实体类,用于字段的映射。

package com._520xuzai.es7.dto;

import com._520xuzai.es7.annotation.ESMappingField;
import com._520xuzai.es7.constains.ESFieldTypeConstains;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

/**
 * \* Created with IntelliJ IDEA.
 * \* User: 煦仔
 * \* Date: 2020-12-22
 * \* Time: 16:00
 * \* To change this template use File | Settings | File Templates.
 * \* Description: 商品搜索映射实体类
 * \
 */
@Setter
@Getter
@AllArgsConstructor
@NoArgsConstructor
public class SearchGoodsMappingDTO implements java.io.Serializable {


    /**
     * 商品ID
     */
    @ESMappingField(fieldName = "goodsId", dataType = ESFieldTypeConstains.DATATYPE_KEYWORD)
    private String goodsId;

    /**
     * 商品名称-不分词
     */
    @ESMappingField(fieldName = "goodsName", dataType = ESFieldTypeConstains.DATATYPE_TEXT, isAnalyze = true, setAnalyzer = ESFieldTypeConstains.SETANALYZER_KEYWORD)
    private String goodsName;

    /**
     * 商品名称-使用ik_max_word分词
     */
    @ESMappingField(fieldName = "goodsNameIk", dataType = ESFieldTypeConstains.DATATYPE_TEXT, isAnalyze = true, setAnalyzer = ESFieldTypeConstains.SETANALYZER_IK_MAX_WORD)
    private String goodsNameIk;

    /**
     * 商品名称-使用ik_smart分词
     */
    @ESMappingField(fieldName = "goodsNameSmart", dataType = ESFieldTypeConstains.DATATYPE_TEXT, isAnalyze = true, setAnalyzer = ESFieldTypeConstains.SETANALYZER_IK_smart)
    private String goodsNameSmart;

    /**
     * 商品名称-使用标准分词器
     */
    @ESMappingField(fieldName = "goodsNameStandard", dataType = ESFieldTypeConstains.DATATYPE_TEXT, isAnalyze = true, setAnalyzer = ESFieldTypeConstains.SETANALYZER_standard)
    private String goodsNameStandard;

    /**
     * 商品分类ID
     */
    @ESMappingField(fieldName = "goodsClassId", dataType = ESFieldTypeConstains.DATATYPE_KEYWORD)
    private String goodsClassId;

    /**
     * 商品分类名称
     */
    @ESMappingField(fieldName = "goodsClassName", dataType = ESFieldTypeConstains.DATATYPE_KEYWORD)
    private String goodsClassName;

    /**
     * 商品图片
     */
    @ESMappingField(fieldName = "goodsImg", dataType = ESFieldTypeConstains.DATATYPE_KEYWORD)
    private String goodsImg;

    /**
     * 商品价格
     */
    @ESMappingField(fieldName = "goodsPrice", dataType = ESFieldTypeConstains.DATATYPE_LONG)
    private Long goodsPrice;

    /**
     * 商品状态,1正常,0下架,-1已删除
     */
    @ESMappingField(fieldName = "goodsStatus", dataType = ESFieldTypeConstains.DATATYPE_KEYWORD)
    private String goodsStatus;

    /**
     * 商品销量
     */
    @ESMappingField(fieldName = "goodsSales", dataType = ESFieldTypeConstains.DATATYPE_LONG)
    private Long goodsSales;

    /**
     * 商品库存
     */
    @ESMappingField(fieldName = "goodsNum", dataType = ESFieldTypeConstains.DATATYPE_INTEGER)
    private Integer goodsNum;

    /**
     * 搜索结果匹配度
     */
    private float score;

}

3.4 接口IElasticsearchIndexService.java

package com._520xuzai.es7.service;


import java.io.IOException;

/**
 * \* Created with IntelliJ IDEA.
 * \* User: 煦仔
 * \* Date: 2020-12-22
 * \* Time: 10:44
 * \* To change this template use File | Settings | File Templates.
 * \* Description: es索引相关操作
 * \
 */
public interface IElasticsearchIndexService {

    /**
     * 判断索引是否存在
     * @param indexName
     * @return
     */
    Boolean isIndexExists(String indexName) throws IOException;

    /**
     * 创建索引
     *
     * @param indexName
     * @param numberOfShards
     * @param numberOfReplicas
     * @return
     */
    Boolean createIndexWithShards(String indexName, Integer numberOfShards, Integer numberOfReplicas) throws IOException;

    /**
     * 创建索引(默认1个分片,1个副本)
     *
     * @param indexName
     * @return
     */
    Boolean createIndex(String indexName) throws IOException;

    /**
     * 删除索引
     * @param indexName
     * @return
     * @throws IOException
     */
    Boolean deleteIndex(String indexName) throws IOException;

    /**
     * 判断索引别名是否存在
     * @param aliasName
     * @return
     */
    Boolean isAliasExists(String aliasName) throws IOException;

    /**
     * 创建索引同时给索引创建别名
     *
     * @param indexName
     * @param aliasName
     * @return
     */
    Boolean createIndexWithAlias(String indexName, String aliasName) throws IOException;

    /**
     * 给索引添加别名
     * @param indexName
     * @param aliasName
     * @return
     * @throws IOException
     */
    Boolean addAlias(String indexName, String aliasName) throws IOException;

    /**
     * 删除某个索引的别名
     * @param aliasName
     * @return
     * @throws IOException
     */
    Boolean deleteAlias(String indexName,String aliasName) throws IOException;

    /**
     * 重建索引,拷贝数据
     *
     * @param oldIndexname
     * @param newIndexname
     */
    void reindex(String oldIndexname, String newIndexname) throws IOException;

    /**
     * 重建索引后修改别名
     *
     * @param aliasname
     * @param oldIndexname
     * @param newIndexname
     * @return
     */
    Boolean changeAliasAfterReindex(String aliasname, String oldIndexname, String newIndexname) throws IOException ;

    /**
     * 添加mapping
     * @param indexName
     * @param clazz
     * @return
     */
    Boolean addMapping(String indexName, Class<?> clazz) throws IOException;

}

3.5 接口实现类ElasticsearchIndexServiceImpl.java

package com._520xuzai.es7.service.impl;


import com._520xuzai.es7.annotation.ESMappingField;
import com._520xuzai.es7.service.IElasticsearchIndexService;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.admin.indices.alias.Alias;
import org.elasticsearch.action.admin.indices.alias.IndicesAliasesRequest;
import org.elasticsearch.action.admin.indices.alias.get.GetAliasesRequest;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.support.IndicesOptions;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.*;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.index.reindex.ReindexRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.lang.reflect.Field;
import java.util.Map;

/**
 * \* Created with IntelliJ IDEA.
 * \* User: 煦仔
 * \* Date: 2020-12-22
 * \* Time: 10:50
 * \* To change this template use File | Settings | File Templates.
 * \* Description: es索引相关操作实现
 * \
 */

@Service
public class ElasticsearchIndexServiceImpl implements IElasticsearchIndexService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;


    @Override
    public Boolean isIndexExists(String indexName) throws IOException {
        GetIndexRequest getIndexRequest = new GetIndexRequest(indexName);
        getIndexRequest.humanReadable(true);
        return restHighLevelClient.indices().exists(getIndexRequest, RequestOptions.DEFAULT);
    }

    @Override
    public Boolean createIndexWithShards(String indexName, Integer numberOfShards, Integer numberOfReplicas) throws IOException {
        CreateIndexRequest createIndexRequest = new CreateIndexRequest(indexName);
        //设置分片信息
        numberOfShards = numberOfShards == null ? 1 : numberOfShards;
        numberOfReplicas = numberOfReplicas == null ? 1 : numberOfReplicas;
        createIndexRequest.settings(Settings.builder().
                put("index.number_of_shards", numberOfShards)
                .put("index.number_of_replicas", numberOfReplicas));
        //创建索引
        CreateIndexResponse createIndexResponse = restHighLevelClient.indices().create(createIndexRequest, RequestOptions.DEFAULT);
        return createIndexResponse.isAcknowledged();
    }

    @Override
    public Boolean createIndex(String indexName) throws IOException {
        CreateIndexRequest createIndexRequest = new CreateIndexRequest(indexName);
        CreateIndexResponse createIndexResponse = restHighLevelClient.indices().create(createIndexRequest, RequestOptions.DEFAULT);
        return createIndexResponse.isAcknowledged();
    }

    @Override
    public Boolean deleteIndex(String indexName) throws IOException {
        DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest(indexName);
        deleteIndexRequest.indicesOptions(IndicesOptions.LENIENT_EXPAND_OPEN);
        AcknowledgedResponse delete = restHighLevelClient.indices().delete(deleteIndexRequest, RequestOptions.DEFAULT);
        return delete.isAcknowledged();
    }

    @Override
    public Boolean isAliasExists(String aliasName) throws IOException {
        GetAliasesRequest getAliasesRequest = new GetAliasesRequest(aliasName);
        return restHighLevelClient.indices().existsAlias(getAliasesRequest, RequestOptions.DEFAULT);
    }


    @Override
    public Boolean createIndexWithAlias(String indexName, String aliasName) throws IOException {
        CreateIndexRequest request = new CreateIndexRequest(indexName);
        if (StringUtils.isNotEmpty(aliasName)) {
            request.alias(new Alias(aliasName));
        }
        CreateIndexResponse createIndexResponse = restHighLevelClient.indices().create(request, RequestOptions.DEFAULT);
        return createIndexResponse.isAcknowledged();
    }

    @Override
    public Boolean addAlias(String indexName, String aliasName) throws IOException {
        IndicesAliasesRequest aliasesRequest = new IndicesAliasesRequest();
        IndicesAliasesRequest.AliasActions aliasAction =
                new IndicesAliasesRequest.AliasActions(IndicesAliasesRequest.AliasActions.Type.ADD)
                        .index(indexName)
                        .alias(aliasName);
        aliasesRequest.addAliasAction(aliasAction);
        AcknowledgedResponse acknowledgedResponse = restHighLevelClient.indices().updateAliases(aliasesRequest,RequestOptions.DEFAULT);
        return acknowledgedResponse.isAcknowledged();
    }

    @Override
    public void reindex(String oldIndexname, String newIndexname) throws IOException {
        ReindexRequest request = new ReindexRequest();
        request.setSourceIndices(oldIndexname);
        request.setDestIndex(newIndexname);
        request.setSourceBatchSize(1000);
        request.setDestOpType("create");
        request.setConflicts("proceed");
//        request.setScroll(TimeValue.timeValueMinutes(10));
//        request.setTimeout(TimeValue.timeValueMinutes(20));
        request.setRefresh(true);
        restHighLevelClient.reindex(request, RequestOptions.DEFAULT);
    }

    @Override
    public Boolean deleteAlias(String indexName,String aliasName) throws IOException {
        DeleteAliasRequest deleteAliasRequest = new DeleteAliasRequest(indexName,aliasName);
        org.elasticsearch.client.core.AcknowledgedResponse acknowledgedResponse = restHighLevelClient.indices().deleteAlias(deleteAliasRequest, RequestOptions.DEFAULT);
        return acknowledgedResponse.isAcknowledged();
    }

    @Override
    public Boolean changeAliasAfterReindex(String aliasname, String oldIndexname, String newIndexname) throws IOException {
        IndicesAliasesRequest.AliasActions addIndexAction = new IndicesAliasesRequest.AliasActions(
                IndicesAliasesRequest.AliasActions.Type.ADD).index(newIndexname).alias(aliasname);
        IndicesAliasesRequest.AliasActions removeAction = new IndicesAliasesRequest.AliasActions(
                IndicesAliasesRequest.AliasActions.Type.REMOVE).index(oldIndexname).alias(aliasname);

        IndicesAliasesRequest indicesAliasesRequest = new IndicesAliasesRequest();
        indicesAliasesRequest.addAliasAction(addIndexAction);
        indicesAliasesRequest.addAliasAction(removeAction);
        AcknowledgedResponse indicesAliasesResponse = restHighLevelClient.indices().updateAliases(indicesAliasesRequest,
                RequestOptions.DEFAULT);
        return indicesAliasesResponse.isAcknowledged();
    }


    @Override
    public Boolean addMapping(String indexName, Class<?> clazz) throws IOException {
        PutMappingRequest putMappingRequest = new PutMappingRequest(indexName);
        Map<String, Object> jsonMap = Maps.newHashMap();
        Map<String, Object> properties = Maps.newHashMap();

        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            ESMappingField esMappingField = field.getDeclaredAnnotation(ESMappingField.class);
            if (esMappingField != null) {
                String fieldname = esMappingField.fieldName();
                String datatype = esMappingField.dataType();
                String analyzer = esMappingField.setAnalyzer();
                boolean isanalye = esMappingField.isAnalyze();
                Map<String, Object> m = Maps.newHashMap();
                m.put("type", datatype);
                if (isanalye && StringUtils.isNotEmpty(analyzer)) {
                    m.put("analyzer", analyzer);
                    m.put("search_analyzer", analyzer);
                }
                properties.put(fieldname, m);
            }
        }
        jsonMap.put("properties", properties);
        putMappingRequest.source(jsonMap);
        AcknowledgedResponse putMappingResponse = restHighLevelClient.indices().putMapping(putMappingRequest,
                RequestOptions.DEFAULT);
        return putMappingResponse.isAcknowledged();
    }

}


3.6 控制层,便于测试ElasticsearchIndexController.java

package com._520xuzai.es7.controller;

import com._520xuzai.es7.service.IElasticsearchIndexService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;

/**
 * \* Created with IntelliJ IDEA.
 * \* User: 煦仔
 * \* Date: 2020-12-22
 * \* Time: 10:43
 * \* To change this template use File | Settings | File Templates.
 * \* Description:elasticsearch索引相关接口
 * \
 */
@RestController
@RequestMapping("/es/index")
@Api(tags = "elasticsearch索引相关接口")
public class ElasticsearchIndexController {

    @Autowired
    private IElasticsearchIndexService elasticsearchIndexService;


    @GetMapping("/isIndexExists")
    @ApiImplicitParam(value = "索引名称", name = "indexName", dataType = "String", required = true, paramType = "query")
    Boolean isIndexExists(@RequestParam(value = "indexName")String indexName) throws IOException{
        return elasticsearchIndexService.isIndexExists(indexName);
    }


    @PostMapping("/createIndex")
    @ApiOperation(value = "创建索引")
    @ApiImplicitParam(value = "索引名称", name = "indexName", dataType = "String", required = true, paramType = "query")
    Boolean createIndex(@RequestParam(value = "indexName")String indexName) throws IOException {
        return elasticsearchIndexService.createIndex(indexName);
    }

    @PostMapping("/createIndexWithShards")
    @ApiOperation(value = "创建索引及自定义分片信息")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "索引名称", name = "indexName", dataType = "String", required = true, paramType = "query"),
            @ApiImplicitParam(value = "分片数量", name = "numberOfShards", dataType = "int", required = true, paramType = "query"),
            @ApiImplicitParam(value = "副本数量", name = "numberOfReplicas", dataType = "int", required = true, paramType = "query")
    })
    Boolean createIndexWithShards(@RequestParam(value = "indexName")String indexName,
                                  @RequestParam(value = "numberOfShards")int numberOfShards,
                                  @RequestParam(value = "numberOfReplicas")int numberOfReplicas) throws IOException {
        return elasticsearchIndexService.createIndexWithShards(indexName,numberOfShards,numberOfReplicas);
    }

    @PostMapping("/deleteIndex")
    @ApiOperation(value = "删除索引")
    @ApiImplicitParam(value = "索引名称", name = "indexName", dataType = "String", required = true, paramType = "query")
    Boolean deleteIndex(@RequestParam(value = "indexName")String indexName) throws IOException {
        return elasticsearchIndexService.deleteIndex(indexName);
    }

    /**
     * 判断索引别名是否存在
     * @param aliasName
     * @return
     */
    @GetMapping("/isAliasExists")
    @ApiOperation(value = "判断索引别名是否存在")
    @ApiImplicitParam(value = "别名", name = "aliasName", dataType = "String", required = true, paramType = "query")
    Boolean isAliasExists(@RequestParam(value = "aliasName")String aliasName) throws IOException{
        return elasticsearchIndexService.isAliasExists(aliasName);
    }

    @PostMapping("/createIndexWithAlias")
    @ApiOperation(value = "创建索引同时给索引创建别名")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "索引名称", name = "indexName", dataType = "String", required = true, paramType = "query"),
            @ApiImplicitParam(value = "别名", name = "aliasName", dataType = "String", required = true, paramType = "query")
    })
    Boolean createIndexWithAlias(@RequestParam(value = "indexName")String indexName,
                                 @RequestParam(value = "aliasName")String aliasName) throws IOException{
        return elasticsearchIndexService.createIndexWithAlias(indexName,aliasName);
    }

    @PostMapping("/addAlias")
    @ApiOperation(value = "给索引添加别名")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "索引名称", name = "indexName", dataType = "String", required = true, paramType = "query"),
            @ApiImplicitParam(value = "别名", name = "aliasName", dataType = "String", required = true, paramType = "query")
    })
    Boolean addAlias(@RequestParam(value = "indexName")String indexName,
                                 @RequestParam(value = "aliasName")String aliasName) throws IOException{
        return elasticsearchIndexService.addAlias(indexName,aliasName);
    }

    @PostMapping("/deleteAlias")
    @ApiOperation(value = "删除某个索引的别名")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "索引名称", name = "indexName", dataType = "String", required = true, paramType = "query"),
            @ApiImplicitParam(value = "别名", name = "aliasName", dataType = "String", required = true, paramType = "query")
    })
    Boolean deleteAlias(@RequestParam(value = "indexName")String indexName,
                        @RequestParam(value = "aliasName")String aliasName) throws IOException{
        return elasticsearchIndexService.deleteAlias(indexName,aliasName);
    }

    @PostMapping("/reindex")
    @ApiOperation(value = "重建索引,拷贝数据")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "原索引名称", name = "oldIndexName", dataType = "String", required = true, paramType = "query"),
            @ApiImplicitParam(value = "新索引名称", name = "newIndexName", dataType = "String", required = true, paramType = "query")
    })
    void reindex(@RequestParam(value = "oldIndexName")String oldIndexName,
                 @RequestParam(value = "newIndexName")String newIndexName) throws IOException{
        elasticsearchIndexService.reindex(oldIndexName,newIndexName);

    }

    @PostMapping("/changeAliasAfterReindex")
    @ApiOperation(value = "重建索引后修改别名")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "原索引名称别名", name = "aliasName", dataType = "String", required = true, paramType = "query"),
            @ApiImplicitParam(value = "原索引名称", name = "oldIndexName", dataType = "String", required = true, paramType = "query"),
            @ApiImplicitParam(value = "新索引名称", name = "newIndexName", dataType = "String", required = true, paramType = "query")
    })
    Boolean changeAliasAfterReindex(@RequestParam(value = "aliasName")String aliasName,
                                    @RequestParam(value = "oldIndexName")String oldIndexName,
                                    @RequestParam(value = "newIndexName")String newIndexName) throws IOException{
        return elasticsearchIndexService.changeAliasAfterReindex(aliasName,oldIndexName,newIndexName);
    }


    /**
     * 添加mapping
     * @param indexName
     * @param className
     * @return
     */
    @PostMapping("/addMapping")
    @ApiOperation(value = "添加mapping")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "索引名称", name = "indexName", dataType = "String", required = true, paramType = "query"),
            @ApiImplicitParam(value = "添加的映射实体权限定名", name = "className", dataType = "String", required = true, paramType = "query")
    })
    Boolean addMapping(@RequestParam(value = "indexName")String indexName,
                       @RequestParam(value = "className")String className) throws IOException, ClassNotFoundException {
        Class<?> clazz = Class.forName(className);
        return elasticsearchIndexService.addMapping(indexName,clazz);
    }


}


四、实践

对于以上关于索引相关的接口,我这里不再一一将测试内容放上来了,简单介绍几个重要的操作。

RestHighLevelClient操作7.10.0(二)ElasticSearch索引及别名详解_第4张图片

1.给索引添加mapping

  • 我们这里通过swagger来给索引添加一个映射
    RestHighLevelClient操作7.10.0(二)ElasticSearch索引及别名详解_第5张图片

  • 在es-head中查看mapping信息
    RestHighLevelClient操作7.10.0(二)ElasticSearch索引及别名详解_第6张图片

  • 在kibana中查看

#获取索引信息
GET /blogs

{
  "blogs" : {
    "aliases" : { },
    "mappings" : {
      "properties" : {
        "goodsClassId" : {
          "type" : "keyword"
        },
        "goodsClassName" : {
          "type" : "keyword"
        },
        "goodsId" : {
          "type" : "keyword"
        },
        "goodsImg" : {
          "type" : "keyword"
        },
        "goodsName" : {
          "type" : "text",
          "analyzer" : "keyword"
        },
        "goodsNameIk" : {
          "type" : "text",
          "analyzer" : "ik_max_word"
        },
        "goodsNameSmart" : {
          "type" : "text",
          "analyzer" : "ik_smart"
        },
        "goodsNameStandard" : {
          "type" : "text",
          "analyzer" : "standard"
        },
        "goodsNum" : {
          "type" : "integer"
        },
        "goodsPrice" : {
          "type" : "long"
        },
        "goodsSales" : {
          "type" : "long"
        },
        "goodsStatus" : {
          "type" : "keyword"
        }
      }
    },
    "settings" : {
      "index" : {
        "routing" : {
          "allocation" : {
            "include" : {
              "_tier_preference" : "data_content"
            }
          }
        },
        "number_of_shards" : "1",
        "provided_name" : "blogs",
        "creation_date" : "1608703505760",
        "number_of_replicas" : "1",
        "uuid" : "JZ6AKiAvR6q67GLUhfRnbg",
        "version" : {
          "created" : "7100099"
        }
      }
    }
  }
}

2.使用别名重建索引的过程

restful api端相关操作可阅读博文Elasticsearch基础11——索引之别名使用

  • 为当前索引建立一个别名
  • 将需要调整后的映射建立一个索引
  • 将旧索引的数据同步到新索引中
  • 将新索引和当前索引别名关联
  • 删除旧索引,完成数据转移

2.1通过kibana添加一条文档数据

POST /blogs/_doc/1
{
  "goodsClassId":"1",
  "goodsClassName":"大家电",
  "goodsId":"1",
  "goodsName":"高效多功能洗衣机,值得一试",
  "goodsNameIk":"高效多功能洗衣机,值得一试",
  "goodsNameStandard":"高效多功能洗衣机,值得一试",
  "goodsNum":10,
  "goodsPrice":12668,
  "goodsSales":198,
  "goodsStatus":1,
  "goodsBrand":"小天鹅"
}

2.2 创建一个新的索引及mapping

新建一个索引blogsbak,并在mapping中添加一个商品详情的字段。

	PUT /blogsbak

 	/**
     * 商品详情
     */
    @ESMappingField(fieldName = "goodsContent", dataType = ESFieldTypeConstains.DATATYPE_TEXT,isAnalyze = true, setAnalyzer = ESFieldTypeConstains.SETANALYZER_IK_MAX_WORD)
    private Integer goodsContent;

添加后新的索引blogsbak及mapping如下:

{
  "blogsbak" : {
    "aliases" : { },
    "mappings" : {
      "properties" : {
        "goodsClassId" : {
          "type" : "keyword"
        },
        "goodsClassName" : {
          "type" : "keyword"
        },
        "goodsContent" : {
          "type" : "text",
          "analyzer" : "ik_max_word"
        },
        "goodsId" : {
          "type" : "keyword"
        },
        "goodsImg" : {
          "type" : "keyword"
        },
        "goodsName" : {
          "type" : "text",
          "analyzer" : "keyword"
        },
        "goodsNameIk" : {
          "type" : "text",
          "analyzer" : "ik_max_word"
        },
        "goodsNameSmart" : {
          "type" : "text",
          "analyzer" : "ik_smart"
        },
        "goodsNameStandard" : {
          "type" : "text",
          "analyzer" : "standard"
        },
        "goodsNum" : {
          "type" : "integer"
        },
        "goodsPrice" : {
          "type" : "long"
        },
        "goodsSales" : {
          "type" : "long"
        },
        "goodsStatus" : {
          "type" : "keyword"
        }
      }
    },
    "settings" : {
      "index" : {
        "routing" : {
          "allocation" : {
            "include" : {
              "_tier_preference" : "data_content"
            }
          }
        },
        "number_of_shards" : "1",
        "provided_name" : "blogsbak",
        "creation_date" : "1608711776108",
        "number_of_replicas" : "1",
        "uuid" : "oG4LE1AXR6WpFK3l8gx7AQ",
        "version" : {
          "created" : "7100099"
        }
      }
    }
  }
}

2.3执行重建索引接口

RestHighLevelClient操作7.10.0(二)ElasticSearch索引及别名详解_第7张图片
通过kibana查看数据已被拷贝
RestHighLevelClient操作7.10.0(二)ElasticSearch索引及别名详解_第8张图片

2.4 进行别名替换

调用重建索引后修改别名接口
RestHighLevelClient操作7.10.0(二)ElasticSearch索引及别名详解_第9张图片
RestHighLevelClient操作7.10.0(二)ElasticSearch索引及别名详解_第10张图片

2.5 删除旧索引

RestHighLevelClient操作7.10.0(二)ElasticSearch索引及别名详解_第11张图片

你可能感兴趣的:(Elasticsearch,elasticsearch,java,es,搜索引擎)