Search code examples
elasticsearchspring-data-elasticsearch

Does spring-data-elasticsearch need to be specified the routing key when indexing documents through standard repository methods?


Let's assume I have a document

@Document(indexName = "example")
@Setting(shards = 4)
@Routing(value = "routingKey")
public class ExampleEntity {

    @Id
    private String id;

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

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

and the associated repository

@Repository
public interface ExampleRepository extends ElasticsearchRepository<ExampleEntity, String> {}

I noticed in the spring-data-elasticsearch documentation that when retrieving data we need to define custom implementations for repositories with native queries in order to make use of the routing key.

Currently native queries must be used to query the data, so there is no support from standard repository methods. Custom Implementations for Spring Data Repositories can be used instead.

However, I cannot find in the documentation if the same thing needs to be done when indexing, or the routing key is being used by default while using the standard repository methods (repository.save(document) or repository.saveAll(documentList)).

Can you please help me elucidate this mystery? Do the spring-data-elasticsearch repositories save and saveAll make use of the routing key or I should implement custom mechanism?


Solution

  • From the documentation "Custom routing values":

    If the routing specification of the annotation is a plain string and not a SpEL expression, it is interpreted as the name of a property of the entity, in the example it’s the routing property. The value of this property will then be used as the routing value for all requests that use the entity.

    As save() and saveAll() get entites as arguments, the routing will be applied to that indexing operations.

    Your quotation

    Currently native queries must be used to query the data,

    is from the section above and refers to the implementation of join-type relationships and not to custom routing values.