Creating Indices name Dynamically in Elasticsearch using Spring-Data Elasticsearch

风流意气都作罢 提交于 2019-11-28 12:09:48

What I am doing on my application is that I use ElasticSearchTemplate to create my dynamic index name and then I point an alias to the new index I have created and then drop the old one.

esTemplate.createIndex(newIndexName, loadfromFromFile(settingsFileName));
esTemplate.putMapping(newIndexName, "MYTYPE", loadfromFromFile(mappingFileName));

I'm not using the mapping and settings from my class since I need it to be dynamic.

    protected String loadFromFile(String fileName) throws IllegalStateException {
       StringBuilder buffer = new StringBuilder(2048);
       try {
           InputStream is = getClass().getResourceAsStream(fileName);
           LineNumberReader reader = new LineNumberReader(new InputStreamReader(is));
           while (reader.ready()) {
               buffer.append(reader.readLine());
               buffer.append(' ');
           }
       } catch (Exception e) {
           throw new IllegalStateException("couldn't load file " + fileName, e);
       }
       return buffer.toString();
   }
Vijay Gupta

What I am doing in my project , we are storing index name and type name in DB whenever it gets changed .

Now i m getting index and type Dynamically in this manner:

First Solution

  • 1)In configuration file ,create a Bean returning a value for someProperty . Here I injected the somePropertyValue with @Value annotation from DB or property file :-

    @Value("${config.somePropertyValue}")
    private String somePropertyValue;
    
    @Bean
    public String somePropertyValue(){
        return somePropertyValue;
    }
    
  • 2)After this , it is possible to inject the somePropertyValue into the @Document annotation like this :-

    @Document(index = "#{@somePropertyValue}")
    public class Foobar {
        //...
    }
    

Second Solution

  • 1) create getter setter in bean :-

    @Component
    public class config{
         @Value("${config.somePropertyValue}")
         private String somePropertyValue;
    
         public String getSomePropertyValue() {
           return somePropertyValue;
         }
        public void setSomePropertyValue(String somePropertyValue) {
           this.somePropertyValue = somePropertyValue;
        }
    }
    
  • 2)After this , it is possible to inject the somePropertyValue into the @Document annotation like this :-

    @Document(index = "#{config.somePropertyValue}")
    public class Foobar {
        //...
    }
    
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!