Ric*_*iti 1 java lucene hibernate-search
当我尝试仅使用一个关键字进行搜索时,使用Hibernate Search 4.5.0.Final的应用程序运行正常。但是,如果我尝试使用两个关键字,那么Hibernate Search不会使用第二个关键字,HS只会考虑第一个。
例如,如果我尝试搜索“ James”,则搜索工作正常,并且应用程序返回索引中包含的所有“ James”。但是,如果我尝试搜索“ James Hetfield”,结果还是所有“ James”,而不是名称为“ James Hetfield”的唯一结果。我需要将“ James Hetfield”视为“ James AND Hetfield”。
编辑:我犯了一个错误。搜索使用两个关键字,但是使用“ OR”而不是“ AND”。
我的代码:
public List<Person> search(String keywords) throws DAOException {
try {
FullTextEntityManager fullTextEm = Search.getFullTextEntityManager(this.entityManager);
QueryBuilder qb = fullTextEm.getSearchFactory().buildQueryBuilder().forEntity(Person.class).get();
Query query = qb.keyword().onFields("name", "email", "username", "phone").matching(keywords).createQuery();
FullTextQuery fullTextQuery = fullTextEm.createFullTextQuery(query);
fullTextQuery.setProjection("name", "email", "username", "phone");
Sort sortField = new Sort(new SortField("name_order", SortField.STRING));
fullTextQuery.setSort(sortField);
return fullTextQuery.getResultList();
}
catch (Exception e) {
logger.error("Error searching index: " + keywords, e);
throw new DAOException(e);
}
}
Run Code Online (Sandbox Code Playgroud)
找到了解决方案。我已经拆分了String并使用了BooleanQuery。感谢@thomas。这是我的代码:
分裂:
String[] arrKeywords = keywords.split(" ");
this.search(Arrays.asList(arrKeywords));
Run Code Online (Sandbox Code Playgroud)
然后,搜索:
public List<Person> search(String keywordsList) throws DAOException {
try {
FullTextEntityManager fullTextEm = Search.getFullTextEntityManager(this.entityManager);
QueryBuilder qb = fullTextEm.getSearchFactory().buildQueryBuilder().forEntity(Person.class).get();
List<Query> queryList = new LinkedList<Query>();
Query query = null;
for (String keyword : keywordsList) {
query = qb.keyword().onFields("name", "email", "username", "phone").matching(keyword).createQuery();
queryList.add(query);
}
BooleanQuery finalQuery = new BooleanQuery();
for (Query q : queryList) {
finalQuery.add(q, Occur.MUST);
}
FullTextQuery fullTextQuery = fullTextEm.createFullTextQuery(query);
fullTextQuery.setProjection("name", "email", "username", "phone");
Sort sortField = new Sort(new SortField("name_order", SortField.STRING));
fullTextQuery.setSort(sortField);
return fullTextQuery.getResultList();
}
catch (Exception e) {
logger.error("Error searching index: " + keywords, e);
throw new DAOException(e);
}
}
Run Code Online (Sandbox Code Playgroud)