简体   繁体   中英

Hibernate search with Criteria restriction returning incorrect count

The result list is perfect but the getResultSize() is incorrect.

I've knocked up some code to illustrate.

Criteria criteria2 = this.getSession().createCriteria(Film.class);                      

Criterion genre = Restrictions.eq("genreAlias.genreName", details.getSearch().getGenreName());
criteria2.createAlias("genres", "genreAlias", CriteriaSpecification.INNER_JOIN);
criteria2.add(genre);    

criteria2.setMaxResults(details.getMaxRows())
.setFirstResult(details.getStartResult());

FullTextEntityManager fullTextEntityManager = org.hibernate.search.jpa.Search.createFullTextEntityManager(entityManager);

org.apache.lucene.queryParser.QueryParser parser2 = new QueryParser("title", new StopAnalyzer() );

org.apache.lucene.search.Query luceneQuery2 = parser2.parse( "title:"+details.getSearch()");

FullTextQuery fullTextQuery = fullTextEntityManager.createFullTextQuery( luceneQuery2, Film.class);
fullTextQuery.setCriteriaQuery(criteria2);

fullTextQuery.getResultList()); // Returns the correctly filtered list
fullTextQuery.getResultSize()); // Returns the retsult size without the genre resrtiction

From http://docs.jboss.org/hibernate/search/3.3/api/org/hibernate/search/jpa/FullTextQuery.html

int getResultSize()

Returns the number of hits for this search Caution: The number of results might be slightly different from getResultList().size() because getResultList() may be not in sync with the database at the time of query.

You should try to use some of the more specialized queries like this one:

    Query query = new FuzzyQuery(new Term("title", q));
    FullTextQuery fullTextQuery = fullTextSession.createFullTextQuery(query, Film.class);
    int filmCount = fullTextQuery.getResultSize();

and this is how you do pagination requests (I'm guessing you have improperly implemented your paggination):

FullTextQuery hits = Search.getFullTextSession(getSession()).createFullTextQuery(query,      Film.class)
.setFirstResult((pageNumber - 1) * perPageItems).setMaxResults(perPageItems);

The above works for me every time. You should keep in mind that the result of getResultSize() more of estimate. I use pagination a lot and I have experienced the number changing between pages. So you should say "about xxxx" results.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM