ps0604
ps0604

Reputation: 1071

Hibernate Search: Define dynamically searchable classes

The code below works fine, however I need to extend it to support from two classes (UserEnt and BookEnt) to 40 classes. To improve performance, I will allow the user to select the classes to search, meaning that the classes in the method createFullTextQuery should be declared dynamically depending on the selection. Is this possible? Otherwise I will have to declare the 40 classes in createFullTextQuery.

    // LUCENE SEARCH
    String[] fields = {"firstName", "lastName", "name"};
    QueryParser parser = new MultiFieldQueryParser( Version.LUCENE_34,
     fields, new StandardAnalyzer(Version.LUCENE_34)); 

    org.apache.lucene.search.Query luceneQuery = null; 
    try { 
     luceneQuery = parser.parse(s); 
    } 
    catch (ParseException e) { 
        throw new RuntimeException("Unable to parse query: " + s, e); 
    }

    // HIBERNATE SEARCH WRAP

    FullTextEntityManager ftEm = Search.getFullTextEntityManager(em); 
    javax.persistence.Query query = ftEm.createFullTextQuery(luceneQuery, 
                                            UserEnt.class, BookEnt.class);

    List <?> results = query.getResultList();

    System.out.println("Records found:"+results.size());

Upvotes: 0

Views: 63

Answers (1)

Sanne
Sanne

Reputation: 6107

The method createFullTextQuery(..) takes a first mandatory parameter, and then an optional varargs parameter to list all types you want to search for.

You could simply omit listing the types there, to have it target all known indexed entities.

FullTextEntityManager ftEm = Search.getFullTextEntityManager(em); 
javax.persistence.Query query = ftEm.createFullTextQuery(luceneQuery);

Explicitly listing the types is a form of filtering, but you could also roll your own custom FullTextFilter to restrict the results on some other criteria, and still target all known types to not need to list them.

Upvotes: 1

Related Questions