Search code examples
elasticsearchspring-dataspring-data-elasticsearch

ReactiveCrudRepository supply with index name


I am using spring-data with reactive support for Elasticsearch:

@Repository
public interface UserDocumentRepository extends ReactiveCrudRepository<UserDocument, UUID> {

}

For now, my UserDocument is annotated with @Document(indexName = "user-*") It is working properly for searching (as I am using ES supplied from Kafka-connect, my service will not create new documents).

My problem is that I have multiple environments dev/test when I need to parametrize index name for each cluster (using the same elastic search, with different index names).

So for dev, I need dev-user-* and for the test, I need test-user-*. I can use ReactiveElasticsearchTemplate where you can supply indexName, but how to do it with ReactiveCrudRepository?


Solution

  • You can use a SpEL expression in your @Document annotation. Check this question and my answer there about the syntax.

    Edit:

    Just a couple of examples how to build the index name dynamically:

    If you have a configuration from the application.properties named env-name:

    @Document(indexName = "#{@environment.getProperty('env-name')}-index-*")
    

    I you have a bean named environmentProvider with a getEnv() method:

    @Document(indexName = "#{@environmentProvider.getEnv()}-index-*")