Hibernate Search: how to configure index for JPA entity dynamically? Hibernate Search: how to configure index for JPA entity dynamically? elasticsearch elasticsearch

Hibernate Search: how to configure index for JPA entity dynamically?


At the moment, the only solution would be to use the programmatic mapping API. This will allow you to execute code to set the index names. If you need to retrieve the index names from configuration files, that will be on you...

First, remove the @Indexed annotations from your indexed entities.

Then, implement a mapping factory:

package com.myCompany;// ... imports ...public class MyAppSearchMappingFactory {    @Factory    public SearchMapping getSearchMapping() {        SearchMapping mapping = new SearchMapping();        for ( Map.Entry<Class<?>, String> entry : getIndexNames() ) {             mapping.entity( entry.getKey() ).indexed().indexName( entry.getValue() );        }        return mapping;    }    private Map<Class<?>, String> getIndexNames() {         // Fetch the index names somehow. Maybe just use a different implementation of this class in each application?    }}

Then reference it in the Hibernate ORM properties (persistence.xml, hibernate.properties, or some framework-specific file, depending on what you use):

hibernate.search.model_mapping com.myCompany.MyAppSearchMappingFactory;

And you should be all set.