I would like to make a LIKE Query with Hibernate Search. If I type in the correct word, I get the results displayed. What if a user types in a wrong word something like: "beik" instead of "bike". I would like to make a query similar to this one: "SELECT * FROM vehicles WHERE name LIKE %beik%;".
I saw in the documentation there exist something like "approximation" ? Is this what I need? And if yes, how to implement it. Do I have to modify my persistence layer?
I have the following service to run a query:
Code:
String q = StringEscapeUtils.escapeXml( queryString );
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
FullTextSession fullTextSession = org.hibernate.search.Search.getFullTextSession( session );
Transaction tx = fullTextSession.beginTransaction();
String[] searchString = { q, q, q, categoryId };
String[] fields = new String[]{ "title", "keywords", "description", "categoryId" };
BooleanClause.Occur[] flagWithoutCatID = { BooleanClause.Occur.SHOULD,
BooleanClause.Occur.SHOULD,
BooleanClause.Occur.SHOULD,
BooleanClause.Occur.SHOULD };
// category must match
BooleanClause.Occur[] flagCatID = { BooleanClause.Occur.SHOULD,
BooleanClause.Occur.SHOULD,
BooleanClause.Occur.SHOULD,
BooleanClause.Occur.MUST };
BooleanClause.Occur[] flags;
if( categoryId.equals( "0" ) ) {
flags = flagWithoutCatID;
} else {
flags = flagCatID;
}
Query query = null;
try {
query = MultiFieldQueryParser.parse( searchString, fields, flags, new StandardAnalyzer() );
//query = MultiFieldQueryParser.parse( searchString, fields, flags, fullTextSession.getSearchFactory().getAnalyzer( PhoneticFilterFactory.class ) );
//query = parser.parse( q );
} catch( ParseException e ) {
logger.info( "Error message: "+e.getMessage() );
logger.info( "Error cause: "+e.getCause() );
}
// don't show items which are flagged as abuse
Criteria criteria = session.createCriteria( Item.class );
criteria.add( Restrictions.eq( "isAbuse", false ) );
org.hibernate.Query hibQuery = fullTextSession.createFullTextQuery( query, Item.class ).setCriteriaQuery( criteria );
size = hibQuery.list().size();
hibQuery.setFirstResult( startAt );
hibQuery.setMaxResults( showAmount );
List<Item> itemList = hibQuery.list();
for( Item item : itemList ) {
fullTextSession.index( item );
}
tx.commit(); //index is written at commit time
return itemList;
Running this code, gives me the correct results, but I would like to use the ...LIKE... approach.