Spring boot 实现 Elasticsearch 动态创建索引

这篇具有很好参考价值的文章主要介绍了Spring boot 实现 Elasticsearch 动态创建索引。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

查找了很多方法都是通过Spring EL表达式实现 @Document(IndexName="#{demo.getIndexName}")

这种方式的问题在于没法解决数据库里生成的序号,例如我希望通过公司ID生成索引编号。后来在外网上找到一个大佬提出的解决方案,这位大佬把两种方案都实现了一遍。

  • 通过entityId自定义index

Use an index name defined by the entity to store data in Spring Data Elasticsearch 4.0

  • 通过SpEL动态生成index

How to provide a dynamic index name in Spring Data Elasticsearch using SpEL

我这里按照entity的方式实现了需求

elasticsearch 版本7.17.3

springboot版本2.7.1

Bean


@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode(callSuper = false)
@Document(indexName = ElasticSearchIndices.ES_INDEX_TROUBLES_COMPANY+"_*",createIndex = false)
public class CompanyTroubleshootingBean implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @JsonFormat(shape = JsonFormat.Shape.STRING)
    @JsonSerialize(
            using = ToStringSerializer.class
    )
    @Field(type = FieldType.Keyword , store = true)
    private Long id;

    @Field(type = FieldType.Text, analyzer = "ik_smart")
    private String content;

    @Field(type = FieldType.Text, analyzer = "ik_smart")
    private String searchKeyword;
    @Field(type = FieldType.Text, analyzer = "ik_max_word", searchAnalyzer = "ik_smart")
    private String contentMaxWord;
    @Field(type = FieldType.Text, analyzer = "ik_max_word", searchAnalyzer = "ik_smart")
    private String searchKeywordMaxWord;

    private Integer useCounts;

    //也是内容  这个内容不能分词查询
    @Field(type = FieldType.Keyword)
    private String keywordContent;

    @Field(type = FieldType.Keyword)
    private Integer catalogId;

    public String getContentMaxWord() {
        return content;
    }
    //私有化set方法,让该属性只读
    private void setContentMaxWord(String contentMaxWord) {
        this.content = contentMaxWord;
    }

    public String getSearchKeywordMaxWord() {
        return searchKeyword;
    }
    //私有化set方法,让该属性只读
    private void setSearchKeywordMaxWord(String searchKeywordMaxWord) {
        this.searchKeyword = searchKeywordMaxWord;
    }


    /**
     * 公司ID
     */
    private Integer companyId;

    /**
     * 平台的解决方案ID
     */
    @JsonFormat(shape = JsonFormat.Shape.STRING)
    @JsonSerialize(
            using = ToStringSerializer.class
    )
    private Long platformTroubleshootingId;



}

接口

//相当于重新定义了一个repository
public interface CompanyTroubleshootElasticRepository<T> {
    <S extends T> S save(S entity);

    <S extends T> Iterable<S> save(Iterable<S> entities);
}

实现类

package online.ejiang.service.impl.troubleshooting;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import online.ejiang.enums.ElasticSearchIndices;
import online.ejiang.pojo.elasticsearch.CompanyTroubleshootingBean;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.core.document.Document;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.lang.NonNull;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Service;

import java.util.concurrent.ConcurrentHashMap;

/**
 * <p>
 * 公司故障排除及定价 服务实现类
 *
 * </p>clo
 *
 * @author Phil
 * @since 2020-07-22
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class CompanyTroubleshootingRepositoryImpl implements CompanyTroubleshootElasticRepository<CompanyTroubleshootingBean> {

    private final ElasticsearchOperations operations;

    @Nullable
    private Document mapping;

    @Override
    public <S extends CompanyTroubleshootingBean> S save(S entity) {
        IndexCoordinates indexCoordinates = getIndexCoordinates(entity);
        S saved = operations.save(entity, indexCoordinates);
        operations.indexOps(indexCoordinates).refresh();
        return saved;
    }

    @Override
    public <S extends CompanyTroubleshootingBean> Iterable<S> save(Iterable<S> entities) {
        if (entities != null && entities.iterator().hasNext()) {
            IndexCoordinates indexCoordinates = getIndexCoordinates(entities.iterator().next());
            Iterable<S> saved = operations.save(entities, indexCoordinates);
            operations.indexOps(indexCoordinates).refresh();
            return saved;
        }
        return null;
    }

    @NonNull
    private <S extends CompanyTroubleshootingBean> IndexCoordinates getIndexCoordinates(S entity) {
        String indexName = ElasticSearchIndices.ES_INDEX_TROUBLES_COMPANY + "_" + entity.getCompanyId();
        //把单实例的Map变成每次调用都初始化,解决重新同步时需要重启服务器的问题。
        ConcurrentHashMap<String, IndexCoordinates> knownIndexCoordinates = new ConcurrentHashMap<>();
        return knownIndexCoordinates.computeIfAbsent(indexName, i -> {
            IndexCoordinates indexCoordinates = IndexCoordinates.of(i);
            IndexOperations indexOps = operations.indexOps(indexCoordinates);
            if (!indexOps.exists()) {
                indexOps.create();
                if (mapping == null) {
                    mapping = indexOps.createMapping(CompanyTroubleshootingBean.class);
                }
                indexOps.putMapping(mapping);
            }
            return indexCoordinates;
        });
    }
}

调用文章来源地址https://www.toymoban.com/news/detail-506256.html

do {
            IPage<CompanyTroubleshootingBean> beanPage = this.pageByCustom(new MyPage<>(index, 800), companyId);
            pages = beanPage.getPages();

            Iterable<CompanyTroubleshootingBean> saved = companyTroubleshootElasticRepository.save(beanPage.getRecords());
            if (saved != null && saved.iterator().hasNext()) {
                index++;
            } else {
                break;
            }

        } while (index <= pages);
Spring boot 实现 Elasticsearch 动态创建索引

到了这里,关于Spring boot 实现 Elasticsearch 动态创建索引的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • ElasticSearch 根据环境自动创建动态索引

            我的客户端的版本是7.13.0,对应springboot与spring-data-elasticsearch的版本如下:(2.5.8与4.2.7)         引入依赖:      1、创建es mapping类  2、启动服务模块自动创建索引,与mapping

    2024年02月15日
    浏览(33)
  • spring elasticsearch:启动项目时自动创建索引

    在springboot整合spring data elasticsearch项目中,当索引数量较多,mapping结构较为复杂时,我们常常希望启动项目时能够自动创建索引及mapping,这样就不用再到各个环境中创建索引了 所以今天咱们就来看看如何自动创建索引 如股票使用的是spring data elasticsearch包,其 @Document 注解中

    2024年02月11日
    浏览(36)
  • spring data elasticsearch:启动项目时自动创建索引

    在springboot整合spring data elasticsearch项目中,当索引数量较多,mapping结构较为复杂时,我们常常希望启动项目时能够自动创建索引及mapping,这样就不用再到各个环境中创建索引了 所以今天咱们就来看看如何自动创建索引 我们已经在实体类中声明了索引数据结构了,只需要识别

    2024年02月05日
    浏览(32)
  • spring data elasticsearch:动态配置实体类索引名称indexName

    最近接到一个需要,需要在spring data elasticsearch关联的实体类中动态的根据配置文件动态创建索引名称,比如开发环境下索引名称为user-dev,测试环境下为user-test,生产环境为user-prod 一开始接到这个需要觉得很怪,因为不同环境的区分直接搭建不同的es服务器环境不就行了吗,

    2023年04月21日
    浏览(34)
  • Spring Boot 中动态创建 Flowable 工作流

    在 Spring Boot 中动态创建 Flowable 工作流可以通过以下步骤实现: 1. 创建 Flowable 配置:首先,您需要在 Spring Boot 应用程序中配置 Flowable。您可以使用 Spring Boot 的配置文件或注解来配置 Flowable。 2. 创建工作流定义:接下来,您需要创建工作流定义。您可以使用 Flowable 的 API 来

    2024年02月10日
    浏览(28)
  • springboot3整合elasticsearch8.7.0实现为bean对象创建索引添加映射

    目录 准备工作 添加相关依赖 在yml中配置elasticsearch 主要内容 实体类 ElasticSearch配置类 测试 确认当前没有counter索引 启动spring 再次查询counter索引​ 在测试类中输出counter索引的映射 官方文档 要注意版本对应关系 spring官方文档中有版本对照表 目前我使用的都是最新的版本,

    2024年02月03日
    浏览(51)
  • [Spring Boot]12 ElasticSearch实现分词搜索功能

    我们在使用搜索功能的时候,有时,为了使搜索的结果更多更广,比如搜索字符串“领导力”,希望有这些组合的结果(领导力、领导、领、导、力)都要能够全部展示出来。 这里我们引入ElasticSearch结合分词插件,来实现这样的搜索功能。 比如:一款app需要对“课程”进行

    2024年02月03日
    浏览(34)
  • Spring Boot进阶(19):探索ElasticSearch:如何利用Spring Boot轻松实现高效数据搜索与分析

            ElasticSearch是一款基于Lucene的开源搜索引擎,具有高效、可扩展、分布式的特点,可用于全文搜索、日志分析、数据挖掘等场景。Spring Boot作为目前最流行的微服务框架之一,也提供了对ElasticSearch的支持。本篇文章将介绍如何在Spring Boot项目中整合ElasticSearch,并展

    2024年02月11日
    浏览(40)
  • Spring Boot 实现定时任务动态管理,太爽了!

    SpringBoot的定时任务的加强工具,实现对SpringBoot原生的定时任务进行动态管理,完全兼容原生@Scheduled注解,无需对原本的定时任务进行修改 具体的功能已经封装成SpringBoot-starter即插即用: 使用方法和源码: 码云:https://gitee.com/qiaodaimadewangcai/super-scheduled github:https://github.com/g

    2024年02月09日
    浏览(36)
  • Spring Boot 中使用 Elasticsearch 实现商品搜索功能

    作者:禅与计算机程序设计艺术 Elasticsearch 是开源分布式搜索引擎,它提供了一个分布式、RESTful 搜索接口。基于 Elasticsearch 的搜索方案能够轻松应对复杂的检索场景并提供高扩展性。在 Web 应用中,Elasticsearch 可以作为后台服务支持用户的检索需求。本文将会教你如何使用

    2024年02月06日
    浏览(37)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包