gpt4 book ai didi

elasticsearch - 使用 SpringData ElasticSearch 动态索引

转载 作者:行者123 更新时间:2023-12-04 23:19:06 29 4
gpt4 key购买 nike

如何在运行时参数化 SpringData ElasticSearch 索引?

例如,数据模型:

@Document(indexName = "myIndex")
public class Asset {

@Id
public String id;

// ...
}

和存储库:
public interface AssetRepository extends ElasticsearchCrudRepository<Asset, String> {

Asset getAssetById(String assetId);
}

我知道我可以替换 myIndex带有参数,但该参数将在实例化/启动期间解析。我们为多个客户/租户提供相同的 Assets 结构,它们有自己的索引。我需要的是这样的:
public interface AssetRepository extends ElasticsearchCrudRepository<Asset, String> {

Asset getAssetByIdFromIndex(String assetId, String index);
}

或这个
repoInstance.forIndex("myOtherIndex").getAssetById("123");

我知道这不是开箱即用的,但是有没有办法以编程方式“破解”它?

最佳答案

即使 bean 在启动时被初始化,你仍然可以通过 spring 表达式语言来实现它:

@Bean
Name name() {
return new Name();
}

@Document(indexName="#{name.name()}")
public class Asset{}

您可以更改 bean 的属性以更改要保存/搜索的索引:
    assetRepo.save(new Asset(...));
name.setName("newName");
assetRepo.save(new Asset(...));

需要注意的是不要在多个线程中共享这个bean,这可能会弄乱你的索引。

这是 a working example .

关于elasticsearch - 使用 SpringData ElasticSearch 动态索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35593944/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com