Sachin
Sachin

Reputation: 1715

How to manage multiple user indexes in spring data elasticsearch

In spring data elasticsearch one model class/entity represents or maps to an index and type.

eg :-

@Document(indexName = "myindex",type="mytype")
public class DocumentModel {
    ......
} 

I have a use case in which I should index data in different es indexes with same structure. If that's the case how can I represent all of those indices with this model class ?

Upvotes: 2

Views: 1223

Answers (1)

Val
Val

Reputation: 217474

Spring Data ES supports using SpEL expressions in the index name of the @Document annotation, like this:

@Document(indexName = "myindex-#{userId}", type="mytype")
public class DocumentModel {
    ......
} 

Hence, you have access to the whole context offered by SpEL in order to create your index names.

UPDATE

If you're using elasticsearchTemplate, there is a simpler variant, you can do it like this:

IndexQuery indexQuery = new IndexQueryBuilder()
     .withId(docModel.getId())
     .withObject(docModel)
     .withIndex("myindex"+docModel.getUserId()).build();

the call to withIndex("...") will override whatever index name you have in the @Document annotation

Upvotes: 6

Related Questions