问题
I'm trying to implement a search based on hibernate-search. I managed to combine search-fields based on some condition, but in this case, I can not search with wildcards.
List<String> spalten = new ArrayList<String>();
FullTextEntityManager fullTextEntityManager = org.hibernate.search.jpa.Search
.getFullTextEntityManager(em);
QueryBuilder qb = fullTextEntityManager.getSearchFactory()
.buildQueryBuilder().forEntity(BeitragVO.class).get();
List<BeitragVO> results;
// add fields for search
List<String> fields= new ArrayList<String>();
if (student) {
logger.info("hit student");
spalten.add("user.surname");
spalten.add("user.givenname");
}
if (company) {
logger.info("hit company");
spalten.add("company.name");
}
for (String string : fields) {
logger.info(string);
}
logger.info("Searchterm:" + searchterm);
org.apache.lucene.search.Query luceneQuery = qb.keyword()
.onFields(fields.toArray(new String[fields.size()]))
.matching(searchterm).createQuery();
logger.info("Query: " + luceneQuery.toString());
javax.persistence.Query jpaQuery = fullTextEntityManager
.createFullTextQuery(luceneQuery, ArticleVO.class);
results= jpaQuery.getResultList();
Under my search input, I got six checkboxes, the user can check or not. If the user checks student, the search only applies for the table for students. This works totally fine!
Problem: Search input: Alexan (for Alexander)
No result is found!
I tried something like this, for wildcard search:
TermContext tc = qb.keyword();
WildcardContext wcc = tc.wildcard();
if (student) {
TermMatchingContext tmc = wcc.onField("user.surname");
tmc = tmc.andField("user.givenname");
luceneQuery = tmc.matching(searchterm).createQuery();
}
This is correct syntax and I get the correct query (user.surname:alexander user.givenname: alexander). But still an empty resultlist.
I really like the attempt without wildcards. Is there a way to add wildcard-search on this attempt?
回答1:
With the wildcard '*' it should work. Effectively you need to build something like:
qb.keyword()
.wildcard()
.onField( "user.givenname" )
.matching( "Alex*" )
.createQuery();
Apparently, you need to decompose the DSL to add some conditional logic, but it should work. Are you sure that 'searchterm' in your example has the wildcard added?
An alternative to decomposing the DSL could be to create multiple independent queries and combine them via a BooleanQuery
. I think that would be more readable.
The issue/bug/feature got fixed! You can see it here:
https://hibernate.atlassian.net/browse/HSEARCH-1811
回答2:
only Alexan will be assumed as exact match, try with Alexan*
来源:https://stackoverflow.com/questions/28528012/how-to-search-with-wildcards-in-multiple-fields