Hibernate Search | ngram analyzer with minGramSize 1

Updated answer for Hibernate Search 6

With Hibernate Search 6, you can define a second analyzer, identical to your “ngram” analyzer except that it does not have an ngram filter, and assign it as the searchAnalyzer for your field:

public class Hospital {
        // ...

        @FullTextField(analyzer = "ngram",
                searchAnalyzer = "my_analyzer_without_ngrams")
        private String name = "";

        // ...
}

Then Hibernate Search will automatically use the “ngram” analyzer when indexing, but “my_analyzer_without_ngrams” when searching, which will lead to the expected behavior.

Additionally, if you are implementing some kind of auto-completion (foo*), and not in-word search (*foo*), you may want to use EdgeNGramFilterFactory instead of NGramFilterFactory: it will only generate ngrams that are prefixes of the indexed tokens.


Original answer for Hibernate Search 5

You can set up a second analyzer, identical to your “ngram” analyzer except that it does not have an ngram filter, and then override the analyzer used for queries:

QueryBuilder hospitalQb = fullTextEntityManager.getSearchFactory().buildQueryBuilder().forEntity(Hospital.class)
    .overridesForField( "name", "my_analyzer_without_ngrams" )
    .get();
// Then it's business as usual

Additionally, if you are implementing some kind of auto-completion (foo*), and not in-word search (*foo*), you may want to use EdgeNGramFilterFactory instead of NGramFilterFactory: it will only generate ngrams that are prefixes of the indexed tokens.

Leave a Comment