Es dynamic index query

  elasticsearch

Run-time setting index

Configuration file

es.index.name=demo

Configure bean

    @Value("${es.index.name}")
    String indexName;

    @Bean
    public String indexName(){
        return indexName;
    }

Configure domain

@Document(indexName="#{@indexName}", type = "log")

dao

public interface DemoDao extends ElasticsearchRepository<Demo,String>{
    Page<Demo> findByApp(String app, Pageable pageable);
}

The advantage is that the runtime can specify, but cannot dynamically query different index’s

dynamic parameter

    @Autowired
    ElasticsearchTemplate elasticsearchTemplate;
    
    public void demo(String index,String type,String app,Pageable page){
        MatchQueryBuilder matchQueryBuilder = new MatchQueryBuilder("app",app);
        SearchQuery query = new NativeSearchQueryBuilder()
                .withIndices(index)
                .withTypes(type)
                .withQuery(matchQueryBuilder)
                .withPageable(page)
                .build();
        Page<Demo> data = elasticsearchTemplate.queryForPage(query,Demo.class);
    }
    

doc