简体   繁体   中英

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?

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

Just change your .matching line to the following:

.matching("*"+searchText+"*")

Use wildcards to get your results in any combination you deem fit.

Hope that works for you.

You can use fuzzySearch of Hibernate Search on keyword. Your code will be like this :

QueryBuilder qb = fullTextSession.getSearchFactory()
           .buildQueryBuilder().forEntity(Movie.class).get();

         org.apache.lucene.search.Query query = qb
           .keyword().fuzzy().withEditDistanceUpTo(1).withPrefixLength(1).onFields("year","title")
           .matching(searchText)
           .createQuery();

See hibernate docs for complete reference.

5.1.2.2 Fuzzy Queries. http://docs.jboss.org/hibernate/search/4.4/reference/en-US/html/search-query.html#search-query-querydsl

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