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

Dmitry Bogdanovich :

I have two applications which use the same Elasticsearch instance as a search engine. Both applications share the same code base and have only minor differences.

Applications run against different databases, and hence, the different ES indices should be used.

I try to parameterize index name using SpEL like this:

@Indexed(index="${es.index.users}")
public UserEntity {}

However, it doesn't work.

The second option I've tried was setting a different prefix for different applications via hibernate.search.default.indexBase=<app_name>. However, it works only for the Lucene engine but not for ES.

Is there a way to pass the index name into @Indexed annotation on the runtime? If not, is there another way to pass the index which should be used?

yrodiere :

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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=144052&siteId=1