Use an index name defined by the entity to store data in Spring Data Elasticsearch 4.0

When using Spring Data Elasticsearch (I am referencing the current version 4.0.2) , normally the name of the index where the documents are stored is taken from the @Document annotation of the entity class – here it’s books:

public class Book {
  // ...

Recently in a discussion of a Pull Request in Spring Data Elasticsearch, someone told that she needed a possibility to extract the name from the entity itself, as entities might go to different indices.

In this post I will show how this can be done by using Spring Data Repository customization by providing a custom implementation for the save method. A complete solution would need to customize saveAll and other methods as well, but I will restrict this here to just one method.

The Hotel entity

For this post I will use an entity describing a hotel, with the idea that hotels from different countries should be stored in different Elasticsearch indices. The index name in the annotation is a wildcard name so that when searching for hotels all indices are considered.

package com.sothawo.springdataelastictest;

import org.springframework.lang.Nullable;

 * @author P.J. Meisch (
@Document(indexName = "hotel-*", createIndex = false)
public class Hotel {
    private String id;

    @Field(type = FieldType.Text)
    private String name;

    @Field(type = FieldType.Keyword)
    private String countryCode;

    // getter/setter ...

The custom repository

We need to define a custom repository interface that defines the methods we want to implement. Since we want to customize the save method that ElasticsearchRepository has by extending CrudRepository, we need to use the very same method signature including the generics:

package com.sothawo.springdataelastictest;

 * @author P.J. Meisch (
public interface CustomHotelRepository<T> {
    <S extends T> S save(S entity);

The next class to provide is an implementation of this interface. It is important that the implementation class is named like the interface with a Impl suffix:

 1package com.sothawo.springdataelastictest;
 3import org.slf4j.Logger;
 4import org.slf4j.LoggerFactory;
 9import org.springframework.lang.NonNull;
10import org.springframework.lang.Nullable;
12import java.util.concurrent.ConcurrentHashMap;
15 * @author P.J. Meisch (
16 */
18public class CustomHotelRepositoryImpl implements CustomHotelRepository<Hotel> {
20    private static final Logger LOG = LoggerFactory.getLogger(CustomHotelRepositoryImpl.class);
22    private final ElasticsearchOperations operations;
24    private final ConcurrentHashMap<String, IndexCoordinates> knownIndexCoordinates = new ConcurrentHashMap<>();
25    @Nullable
26    private Document mapping;
28    @SuppressWarnings("unused")
29    public CustomHotelRepositoryImpl(ElasticsearchOperations operations) {
30        this.operations = operations;
31    }
33    @Override
34    public <S extends Hotel> S save(S hotel) {
36        IndexCoordinates indexCoordinates = getIndexCoordinates(hotel);
37"saving {} to {}", hotel, indexCoordinates);
39        S saved =, indexCoordinates);
41        operations.indexOps(indexCoordinates).refresh();
43        return saved;
44    }
46    @NonNull
47    private <S extends Hotel> IndexCoordinates getIndexCoordinates(S hotel) {
49        String indexName = "hotel-" + hotel.getCountryCode();
50        return knownIndexCoordinates.computeIfAbsent(indexName, i -> {
52                IndexCoordinates indexCoordinates = IndexCoordinates.of(i);
53                IndexOperations indexOps = operations.indexOps(indexCoordinates);
55                if (!indexOps.exists()) {
56                    indexOps.create();
58                    if (mapping == null) {
59                        mapping = indexOps.createMapping(Hotel.class);
60                    }
62                    indexOps.putMapping(mapping);
63                }
64                return indexCoordinates;
65            }
66        );
67    }

This implementation is a Spring Bean (no need for adding @Component) and so can use dependency injection. Let me explain the code.

Line 22: the ElasticsearchOperations object we will use to store the entity in the desired index, this is autowired by constructor injection in lines 29-31

Line 24: As we want to make sure that the index we write to exists and has the correct mapping, we keep track of which indices we already know. This is used in the getIndexCoordinates method explained later.

Line 34 to 44: This is the actual implementation of the save operation. First we call getIndexCoordinates which will make sure the index exists. We pass the indexCoordinates into the save method of the ElasticsearchOperations instance. If we would use, the name from the @Document annotation would be used. But when passing an IndexCoordinates as second parameter, the index name from this is used to store the entity. In line 41 there is a call to refresh, this is the behaviour of the original method, so we do the same here. If you do not need the immediate refresh, omit this line.

Line 47 to 76: As Spring Data Elasticsearch does not yet support index templates (this will come with version 4.1) this method ensures, that when the first time that an entity is saved to an index, this index is created if necessary and writes the mappings to the new created index.

The HotelRepository to use in the application

We now need to combine our custom repository with the ElasticsearchRepository from Spring Data Elasticsearch:

package com.sothawo.springdataelastictest;


 * @author P.J. Meisch (
public interface HotelRepository extends ElasticsearchRepository<Hotel, String>, CustomHotelRepository<Hotel> {
    SearchHits<Hotel> searchAllBy();

Here we combine the two interfaces and define an additional method that returns all hotels in a SearchHits object.

Use the repository in the code

The only thing that’s left is to use this repository, for example in a REST controller:

package com.sothawo.springdataelastictest;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

 * @author P.J. Meisch (
public class HotelController {

    private final HotelRepository repository;

    public HotelController(HotelRepository repository) {
        this.repository = repository;

    public SearchHits<Hotel> all() {
        return repository.searchAllBy();

    public Hotel save(@RequestBody Hotel hotel) {

This is a standard controller which has a HotelRepository instance injected (which Spring Data Elasticsearch will create for us). This looks exactly how it would without our customization. The difference is that the call to save() ends up in our custom implementation.


This post shows how easy it is to provide custom implementations for the methods that are normally provided by Spring Data Repositories (not just in Spring Data Elasticsearch) if custom logic is needed.