Issue
I am working spring data elastic search. Based on different header in the request, I create @RequestScope object IndexConfig to hold different set of indexes. It seems to be working. But I don't understand how singleton bean DocumentA/DocumentB can handle dynamic index? Do I need to set them @RequestScope as well?
@Component
@Data
@RequestScope
public class IndexConfig {
private String AIndexName;
private String BIndexName;
}
@Component
public class RequestFilter implements Filter {
@Autowired
private IndexConfig indexConfig ;
public void doFilter(ServletRequest req,....) {
if(httpRequest.getHeader("one"){
indexConfig.setAIndexName("A1);
indexConfig.setBIndexName("B1);
}else if(httpRequest.getHeader("two"){
indexConfig.setAIndexName("A2);
indexConfig.setBIndexName("B2);
}
..
}
}
@Document(indexName = "#{@indexConfig.getAIndexName()}", createIndex = false)
public class DocumentA {}
@Document(indexName = "#{@indexConfig.getBIndexName()}", createIndex = false)
public class DocumentB {}
Solution
What makes you think that DocumentA
or Document
B` are singletons? Thes e are the entities that you store and retrieve.
You create an instance of DocumentA
and store it by either using methods of ElasticsearchOperations
or using a respository function. And when retrieving data from Spring Data Elasticsearch, you get new instance(s) back, populated with the data that is read from Elasticsearch.
Answered By - P.J.Meisch
Answer Checked By - Dawn Plyler (JavaFixing Volunteer)