title: spring data elasticsearch dynamic multi tenant index mismatch?
body: <p>I am experimenting with spring data elasticsearch by implementing a cluster which will host multi-tenant indexes, one index per tenant.</p>
  
  <p>I am able to create and set settings dynamically for each needed index, like</p>
  
  <pre><code>public class SpringDataES {
  
      @Autowired
      private ElasticsearchTemplate es;
  
      @Autowired
      private TenantIndexNamingService tenantIndexNamingService;
  
      private void createIndex(String indexName) {
          Settings indexSettings = Settings.builder()
                          .put("number_of_shards", 1)
                          .build();
          CreateIndexRequest indexRequest = new CreateIndexRequest(indexName, indexSettings);
          es.getClient().admin().indices().create(indexRequest).actionGet();
          es.refresh(indexName);
      }
  
      private void preapareIndex(String indexName){
          if (!es.indexExists(indexName)) {
              createIndex(indexName);
          }
          updateMappings(indexName);
      }
  </code></pre>
  
  <p>The model is created like this</p>
  
  <pre><code>@Document(indexName = "#{tenantIndexNamingService.getIndexName()}", type = "movies")
  public class Movie {
  
    @Id
    @JsonIgnore
    private String id;
    private String movieTitle;
    @CompletionField(maxInputLength = 100)
    private Completion movieTitleSuggest;
    private String director;
    private Date releaseDate;
  </code></pre>
  
  <p>where the index name is passed dynamically via the SpEl </p>
  
  <p><code>#{tenantIndexNamingService.getIndexName()}</code></p>
  
  <p>that is served by</p>
  
  <pre><code>@Service
  public class TenantIndexNamingService {
    private static final String INDEX_PREFIX = "test_index_";
  
    private String indexName = INDEX_PREFIX;
  
    public TenantIndexNamingService() {
    }
  
    public String getIndexName() {
      return  indexName;
    }
  
    public void setIndexName(int tenantId) {
      this.indexName = INDEX_PREFIX + tenantId;
    }
  
    public void setIndexName(String indexName) {
      this.indexName = indexName;
    }
  }
  </code></pre>
  
  <p>So, whenever I have to execute a CRUD action, first I am pointing to the right index and then to execute the desired action</p>
  
  <pre><code>tenantIndexNamingService.setIndexName(tenantId);
  movieService.save(new Movie("Dead Poets Society", getCompletion("Dead Poets Society"), "Peter Weir", new Date()));
  </code></pre>
  
  <p>My assumption is that the following dynamically index assignment, will not work correctly  in a multi-threaded web application:</p>
  
  <pre><code>@Document(indexName = "#{tenantIndexNamingService.getIndexName()}"
  </code></pre>
  
  <p>This is because TenantIndexNamingService is singleton.</p>
  
  <p>So my question is how achieve the right behavior in a thread save manner?</p>