I’m trying to implement Hibernate Seach in my Spring Boot Application. I have Product class which holds
“name” and “author” as strings. When I put the full name of a product, it returns the products with the same name with no problem but I want to implement it such way that when I write “19”, it should return the products which have “19” in their name, for example, “1984”, “19 Ways”, etc.
Can you show me the way of doing it? Thank you in advance.
In my product model, there are 2 Analyzers, one for indexing, one for the query.
@Indexed
@Entity
@Table(name = "product")
@AnalyzerDefs({
@AnalyzerDef(name = "edgeNgram",
tokenizer = @TokenizerDef(factory = WhitespaceTokenizerFactory.class),
filters = {
@TokenFilterDef(factory = ASCIIFoldingFilterFactory.class),
@TokenFilterDef(factory = LowerCaseFilterFactory.class),
@TokenFilterDef(
factory = EdgeNGramFilterFactory.class,
params = {
@Parameter(name = "minGramSize", value = "1"),
@Parameter(name = "maxGramSize", value = "10")
}
)
}),
@AnalyzerDef(name = "edgeNGram_query",
tokenizer = @TokenizerDef(factory = WhitespaceTokenizerFactory.class),
filters = {
@TokenFilterDef(factory = ASCIIFoldingFilterFactory.class),
@TokenFilterDef(factory = LowerCaseFilterFactory.class)
})
})
// Some code in here
@Field(analyzer = @Analyzer(definition = "edgeNgram"))
@Column(length = 45)
private String name;
@Field(analyzer = @Analyzer(definition = "edgeNgram"))
@Column(length = 45)
private String author;
My Repository Interface is:
- I have 2 different repositories, my hibernate implementation is at “ProductSearchRepository”
public interface ProductRepository extends PagingAndSortingRepository<Product, Integer>, ProductSearchRepository {
}
My repository implementation is:
public class ProductRepositoryImpl implements ProductSearchRepository {
@PersistenceContext
private EntityManager entityManager;
@Override
public List<Product> findProductByName(String name) {
FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(entityManager);
QueryBuilder queryBuilder = fullTextEntityManager.getSearchFactory().buildQueryBuilder().forEntity(Product.class)
.overridesForField( "name", "edgeNGram_query" )
.get();
Query query = queryBuilder
.keyword()
.onField("name")
.matching(name)
.createQuery();
javax.persistence.Query jpaQuery =
fullTextEntityManager.createFullTextQuery(query, Product.class);
return jpaQuery.getResultList();
}
}