I have a indexed search with Hibernate Search but I can not get Hibernate Search sort the search result by the order of a particular column , such as the column name.
But there is a quirk . When the search is done using some term, the result is then sorted perfectly alphabetically. However, if I do not put any search term (I want it to return all results), then Hibernate Search no longer commands anything.
See the codes for the two searches:
Using a filter (works)
Below is my method that searches by filtering through a term. This search works perfectly and sorts by name (alphabetically) .
public List<Colaborador> filtrar(String termo) throws DAOException {
try {
FullTextEntityManager fullTextEm = Search.getFullTextEntityManager(this.entityManager);
QueryBuilder qb = fullTextEm.getSearchFactory().buildQueryBuilder().forEntity(Colaborador.class).get();
Query query = qb.keyword().onFields("nome", "email", "usuario").matching(termo).createQuery();
FullTextQuery fullTextQuery = fullTextEm.createFullTextQuery(query);
// Ordenação ocorre corretamente aqui!
Sort sortField = new Sort(new SortField("nome", SortField.STRING));
fullTextQuery.setSort(sortField);
return fullTextQuery.getResultList();
}
catch (Exception e) {
logger.error("Erro ao filtrar colaboradores com termo: " + termo, e);
throw new DAOException(e);
}
}
Bringing all the records (sorting does not work)
Below is a method very similar to what I posted above, however the method below just does not correctly order the records that are returned by Hibernate Search. Notice that it is the same entity ( Colaborador.class
) and even then the order by name does not work correctly.
public List<Colaborador> listarColaboradores() throws DAOException {
FullTextEntityManager fullTextEm = Search.getFullTextEntityManager(this.entityManager);
QueryBuilder qb = fullTextEm.getSearchFactory().buildQueryBuilder().forEntity(Colaborador.class).get();
FullTextQuery fullTextQuery = fullTextEm.createFullTextQuery(qb.all().createQuery());
// A mágica deveria ser feita aqui!
Sort sortField = new Sort(new SortField("nome", SortField.STRING));
fullTextQuery.setSort(sortField);
return fullTextQuery.getResultList();
}
Has anyone ever gone through this? Do you know what might be happening?