动态索引与SpringData ElasticSearch

6

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

例如,数据模型:

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

    @Id
    public String id;

    // ...
}

还有代码库:

public interface AssetRepository extends ElasticsearchCrudRepository<Asset, String> {

    Asset getAssetById(String assetId);
}

我知道我可以用参数替换myIndex,但这个参数将在实例化/启动期间解析。我们为多个客户/租户提供相同的资产结构,它们都有自己的索引。我需要的是像这样的东西:

public interface AssetRepository extends ElasticsearchCrudRepository<Asset, String> {

    Asset getAssetByIdFromIndex(String assetId, String index);
}

或者这个

repoInstance.forIndex("myOtherIndex").getAssetById("123");

我知道这个功能不能直接使用,但有没有编程上的“hack”方法可以解决呢?

这个答案或者这个答案应该会有所帮助。 - Val
我认为两者都不适用(之前已经找到并研究过)。它们都是关于不硬编码索引名称的,但我需要能够调用许多不同的索引。我只能通过客户端参数(而不是在编译或启动时)知道索引名称。 - Daniel
好的,那我们找另一个解决方案吧 :) - Val
2个回答

2
即使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,这可能会混乱您的索引。
这里有一个工作示例

1
在上面的链接中收到“页面未找到”的错误。 - Nimble Fungus
此解决方案不是线程安全的。 - Bilal Demir

0

org.springframework.data.elasticsearch.repository.ElasticSearchRepository有一个方法

FacetedPage<T> search(SearchQuery searchQuery);

SearchQuery 可以使用多个索引进行搜索。

希望这能解答您的问题。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接