运行时设定index

配置文件

es.index.name=demo

配置bean

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

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

配置domain

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

dao

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

好处是运行时可以指定,但是无法动态查询不同index的

动态参数

    @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


codecraft
11.9k 声望2k 粉丝

当一个代码的工匠回首往事时,不因虚度年华而悔恨,也不因碌碌无为而羞愧,这样,当他老的时候,可以很自豪告诉世人,我曾经将代码注入生命去打造互联网的浪潮之巅,那是个很疯狂的时代,我在一波波的浪潮上留下...