user3486059 user3486059 - 3 days ago 5
MySQL Question

spring mvc Hibernate Search query

I am working with spring, using hibernate, maven and mysql, i'm trying to make a simple site for movies and actors. What i'd like is a search method, where you type a word, or part of a word/name and you will get some results, this is my query:

@Transactional
public List<Movie> searchForMovie(String searchText) {
FullTextSession fullTextSession = Search.getFullTextSession(getSession());

QueryBuilder qb = fullTextSession.getSearchFactory().buildQueryBuilder().forEntity(Movie.class).get();
org.apache.lucene.search.Query query = qb.keyword().onFields("year", "title").matching(searchText)
.createQuery();

org.hibernate.Query hibQuery = fullTextSession.createFullTextQuery(query, Movie.class);

List<Movie> results = hibQuery.list();
return results;
}


As you can see, I am using 'keyword', this means you would have to search for the whole word/name, not only part of it. For example, if I want to find the movie 'hunger games' I would have to type 'hunger' or 'games', what I want is it to be possible to only write 'hunge' and still get results. I cant seem to find a query that will do this, thoughts?

Answer

You can use hibernate wildcard queries for this.

? - represents a single character
* - represents any character sequence.

Please also note that for performance purposes, it is recommended that query do not start with ? or either *.

   QueryBuilder qb = fullTextSession.getSearchFactory()
                .buildQueryBuilder().forEntity(Movie.class).get();
        org.apache.lucene.search.Query query = qb
                .keyword().wildcard().onFields("year", "title")
                .matching(searchText + "*")
                .createQuery();

See hibernate docs for complete reference.
5.1.2.3 Wildcard Queries.
http://docs.jboss.org/hibernate/search/4.4/reference/en-US/html/search-query.html#search-query-querydsl

Comments