bui quang huy
bui quang huy

Reputation: 153

Hibernate search only return exact value

My program only return exactly value equal with search string:

trans = session.beginTransaction();
FullTextSession fullTextSession = Search.getFullTextSession(session);
fullTextSession.createIndexer().startAndWait();
QueryBuilder qB = fullTextSession.getSearchFactory().buildQueryBuilder()
.forEntity(Customer.class).get();

org.apache.lucene.search.Query luceneQuery = qB.keyword()
.onFields("lastName").matching(searchString).createQuery();

Query fullTextQuery = fullTextSession.createFullTextQuery(luceneQuery);
list = fullTextQuery.list();

Ex: when search string is 'user' i will get list, but when search string is 'User' or 'Use', i will get null.

Upvotes: 1

Views: 940

Answers (1)

Bilal BBB
Bilal BBB

Reputation: 1164

I don't know how do you index your fields, it seems that you don't use a proper Analyzer. Read the documentation about it.

Try to use a custom Analyzer using hibernate search annotations and Solr Analyzers, Tokenizers and Filters.

This is example can help you to start :

@Entity
@Indexed
@AnalyzerDef(name = "customanalyzer",
  tokenizer = @TokenizerDef(factory = StandardTokenizerFactory.class),
  filters = {
    @TokenFilterDef(factory = LowerCaseFilterFactory.class),
    @TokenFilterDef(factory = SnowballPorterFilterFactory.class, params = {
      @Parameter(name = "language", value = "English")
    })
  })
public class Book {

  @Id
  @GeneratedValue
  @DocumentId
  private Integer id;

  @Field
  @Analyzer(definition = "customanalyzer")
  private String title;

  @Field
  @Analyzer(definition = "customanalyzer")
  private String subtitle;

  @IndexedEmbedded
  @ManyToMany
  private Set<Author> authors = new HashSet<Author>();

  @Field(index = Index.YES, analyze = Analyze.NO, store = Store.YES)
  @DateBridge(resolution = Resolution.DAY)
  private Date publicationDate;

  public Book() {
  }

  // standard getters/setters follow here
  ...
}

Using the Analyzer of this example, you would be able to find 'User' and 'user' ...

To be able to find 'user' when your keyword is 'Use' you ca :

  1. Use another Analyzer like 'EdgeNGramFilterFactory'.

  2. or use wildcard queries like this :

    Query luceneQuery = qb.keyword().wildcard().onField("lastName").matching("use*").createQuery();

The documentation is simple, the best way to learn Hibernate Search is to read it.

Upvotes: 2

Related Questions