springboot与es集成操作-基础篇3(动态创建索引)


需求:动态创建索引,数据每天更新,更新后创建新的索引,然后删除原来索引。为了不影响再创建索引的时候影响功能的使用。
前面的添加依赖、yml中增加es配置、实现Repository操作与 springboot与es集成操作-基础篇保持一致。。。。。。

1.固定索引实体类:

@Data
@FieldNameConstants
@AllArgsConstructor
@NoArgsConstructor
@Document(indexName = "index_search")
public class IndexSearch {
    @Id
    private long id;

    @ApiModelProperty(value = "名称")
    @Field(type = FieldType.Text, analyzer = "ik_max_word", searchAnalyzer = "ik_smart")
    private String name;

    @ApiModelProperty(value = "别名")
    @Field(type = FieldType.Text, analyzer = "ik_max_word", searchAnalyzer = "ik_smart")
    private String displayName;
}

2.动态创建索引的实体类:

createIndex 默认为true,再启动项目的时候会自动创建索引,在这设为false,改为后续的手动创建索引。
indexName 索引名称,动态创建索引,所以索引的名称为传递过来的名称。esConfig为索引名称类,再执行过程中会将索引名称传递到esConfig中,进一步将实体SubstanceSearch的名称赋值

//indexName 索引名称,动态创建索引,所以索引的名称为传递过来的名称。esConfig为索引名称类,再执行过程中会将索引名称传递到esConfig中,进一步将实体SubstanceSearch的名称赋值
@Data
@FieldNameConstants
@AllArgsConstructor
@NoArgsConstructor
@Document(indexName = "#{esConfig.getApiCallIndexName()}",createIndex = false)
public class SubstanceSearch {
    @Id
    private long id;

    @ApiModelProperty(value = "名称")
    @Field(type = FieldType.Text, analyzer = "ik_max_word", searchAnalyzer = "ik_smart")
    private String name;

    @ApiModelProperty(value = "别名")
    @Field(type = FieldType.Text, analyzer = "ik_max_word", searchAnalyzer = "ik_smart")
    private String displayName;

3.索引名称类:

import org.springframework.stereotype.Component;

@Component(value = "esConfig")
public class ElasticSearchConfiguration {

    public static String apiCallIndexNamePrefix;

    public String getApiCallIndexName() {
        return apiCallIndexNamePrefix;
    }
}

4.动态创建索引

    @Autowired
    private ElasticsearchRestTemplate restTemplate;
    /**
     * 创建索引
     **/
    @GetMapping("/createIndex")
    public RestResult createIndex() throws Exception {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmm");
        //生成索引名称
        String dateString = "index_substance" + formatter.format(new Date());
        //传递索引名称
        ElasticSearchConfiguration.apiCallIndexNamePrefix = dateString;
        //判断索引库中是否存在该索引
        if (!restTemplate.indexOps(IndexCoordinates.of(dateString)).exists()) {
            Document mapping = restTemplate.indexOps(IndexCoordinates.of(dateString)).createMapping(SubstanceSearch.class);
            restTemplate.indexOps(IndexCoordinates.of(dateString)).create();
            restTemplate.indexOps(IndexCoordinates.of(dateString)).putMapping(mapping);
        }

        return RestResultHelper.success();
    }

5.查询

自动补全查询

import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;


        @Autowired
    private ElasticsearchRestTemplate restTemplate;
    /**
     * 自动补全方法
     **/
    @GetMapping("/suggest")
    public RestResult<List<String>> suggest(String prefix) throws Exception {

        List<String> results = new ArrayList<>();
        //索引名称
        ElasticSearchConfiguration.apiCallIndexNamePrefix = "index_substance_20221010";
        //根据查询内容获取匹配的前10条数据
        CompletionSuggestionBuilder completionSuggestionBuilder = new CompletionSuggestionBuilder(SubstanceSearch.Fields.completion)
                .prefix(prefix)
                .skipDuplicates(true).size(10);
        SuggestBuilder suggestBuilder = new SuggestBuilder()
                .addSuggestion("name_suggest", completionSuggestionBuilder);

        SearchResponse response = restTemplate.suggest(suggestBuilder, IndexCoordinates.of(ElasticSearchConfiguration.apiCallIndexNamePrefix));
        Suggest suggest = response.getSuggest();
        Suggest.Suggestion suggestion = suggest.getSuggestion("name_suggest");
        List<CompletionSuggestion.Entry> entries = suggestion.getEntries();
        entries.forEach(entry -> {
            List<CompletionSuggestion.Entry.Option> options = entry.getOptions();
            options.forEach(option -> {
                results.add(option.getText().toString());
            });
        });

        return RestResultHelper.success(results);
    }
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值