use of org.hibernate.search.FullTextSession in project ice by JBEI.
the class HibernateSearch method filterBlastResults.
/**
* Intended to be called after running a blast search to filter the results. Blast search runs
* on a fasta file which contains all the sequences. Hibernate search has a security filter for permissions
* and is therefore used to filter out the blast results, as well as to filter based on the entry
* attributes not handled by blast; such as "has sequence" and "bio-safety level"
*
* @param userId identifier for account of user performing search
* @param start paging start
* @param count maximum number of results to return
* @param blastResults raw results of the blast search
* @return wrapper around list of filtered results
*/
public SearchResults filterBlastResults(String userId, int start, int count, SearchQuery searchQuery, final HashMap<String, SearchResult> blastResults) {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
FullTextSession fullTextSession = Search.getFullTextSession(session);
QueryBuilder qb = fullTextSession.getSearchFactory().buildQueryBuilder().forEntity(Entry.class).get();
Query query = qb.keyword().onField("visibility").matching(Visibility.OK.getValue()).createQuery();
// todo : there is a limit of 1024 boolean clauses so return only return top blast results
BooleanQuery.Builder builder = new BooleanQuery.Builder();
builder.add(query, BooleanClause.Occur.FILTER);
// wrap Lucene query in a org.hibernate.Query
Class<?>[] classes = SearchFieldFactory.classesForTypes(searchQuery.getEntryTypes());
FullTextQuery fullTextQuery = fullTextSession.createFullTextQuery(builder.build(), classes);
// enable security filter if an admin
checkEnableSecurityFilter(userId, fullTextQuery);
// enable has attachment/sequence/sample (if needed)
checkEnableHasAttribute(fullTextQuery, searchQuery.getParameters());
// bio-safety level
if (searchQuery.getBioSafetyOption() != null) {
TermContext levelContext = qb.keyword();
Query biosafetyQuery = levelContext.onField("bioSafetyLevel").ignoreFieldBridge().matching(searchQuery.getBioSafetyOption().getValue()).createQuery();
builder.add(biosafetyQuery, BooleanClause.Occur.MUST);
}
// execute search
fullTextQuery.setProjection("id");
// list contains an object array with one Long object
List<?> luceneResult = fullTextQuery.list();
HashSet<String> resultSet = new HashSet<>();
// page
for (Object object : luceneResult) {
Long result = (Long) ((Object[]) object)[0];
resultSet.add(result.toString());
}
blastResults.keySet().removeIf(key -> !resultSet.contains(key));
SearchResult[] searchResults = new SearchResult[count];
int limit = Math.min((start + count), blastResults.size());
LinkedList<SearchResult> list = new LinkedList<>(Arrays.asList(blastResults.values().toArray(searchResults)).subList(start, limit));
SearchResults results = new SearchResults();
results.setResultCount(blastResults.size());
results.setResults(list);
return results;
}
use of org.hibernate.search.FullTextSession in project weicoder by wdcode.
the class HibernateSearch method search.
/**
* 使用索引查询
* @param session Hibernate Session
* @param entityClass 实体类
* @param property 属性名
* @param value 属性值
* @param firstResult 重第几条开始查询
* @param maxResults 一共查回多少条
* @param <E> 泛型
* @return 数据列表
*/
@SuppressWarnings("unchecked")
public <E> List<E> search(Session session, Class<E> entityClass, final String property, final Object value, final int firstResult, final int maxResults) {
// 通过Hibernate的Session获取FullTextSession对象
FullTextSession fullTextSession = Search.getFullTextSession(session);
// 获取特定类的特定QueryBuilder对象
QueryBuilder queryBuilder = fullTextSession.getSearchFactory().buildQueryBuilder().forEntity(entityClass).get();
// 得到search query
org.apache.lucene.search.Query query = queryBuilder.keyword().onField(property).matching(value).createQuery();
// 这里使用FullTextQuery和org.hibernate.Query来分装org.apache.lucene.search.Query都是可以的,
// 但FullTextQuery的功能比org.hibernate.Query的功能要强大一点,究竟什么时候要用org.hibernate.Query而不能用
// org.apache.lucene.search.Query这个我暂时还没有发现!
FullTextQuery fullTextQuery = fullTextSession.createFullTextQuery(query, entityClass);
// 开始结果大于等于0
if (firstResult >= 0) {
fullTextQuery.setFirstResult(firstResult);
}
// 最大结果大于零
if (maxResults > 0) {
fullTextQuery.setMaxResults(maxResults);
}
// 返回结果
return fullTextQuery.list();
}
use of org.hibernate.search.FullTextSession in project trainning by fernandotomasio.
the class HibernatePessoaDAO method search.
@Override
public List<Pessoa> search(String term) throws DAOException {
Session session = sessionFactory.getCurrentSession();
FullTextSession fullTextSession = Search.getFullTextSession(session);
// Transaction tx = fullTextSession.beginTransaction();
// create native Lucene query unsing the query DSL
// alternatively you can write the Lucene query using the Lucene query parser
// or the Lucene programmatic API. The Hibernate Search DSL is recommended though
QueryBuilder qb = fullTextSession.getSearchFactory().buildQueryBuilder().forEntity(Pessoa.class).get();
org.apache.lucene.search.Query query = qb.phrase().onField("nome").sentence(term).createQuery();
// wrap Lucene query in a org.hibernate.Query
org.hibernate.Query hibQuery = fullTextSession.createFullTextQuery(query, Pessoa.class);
// execute search
@SuppressWarnings("unchecked") List<Pessoa> result = hibQuery.list();
// tx.commit();
return result;
// Session session = sessionFactory.getCurrentSession();
//
// try {
// Criteria criteria = session.createCriteria(Pessoa.class);
//
// if (term != null) {
// Disjunction or = Restrictions.disjunction();
// or.add(Restrictions.ilike("cpf", "%" + term + "%"))
// .add(Restrictions.ilike("identidade", "%" + term + "%"))
// .add(Restrictions.ilike("nome", "%" + term + "%"));
//
//
// criteria.add(or);
// }
//
// List<Pessoa> pessoas = criteria.list();
//
//
// return pessoas;
//
// } catch (HibernateException e) {
// Logger.getLogger(HibernatePessoaDAO.class.getName()).log(
// Level.SEVERE, null, e);
// throw new DAOException(MessageHelper.getMessage("pesssoas.find.list.error"));
// } finally {
// session.close();
//
// }
}
use of org.hibernate.search.FullTextSession in project rubia-forums by flashboss.
the class ForumsSearchModuleImpl method findTopics.
@SuppressWarnings("unchecked")
public ResultPage<Topic> findTopics(SearchCriteria criteria) throws ModuleException {
if (criteria != null) {
try {
EntityManager session = getSession();
FullTextSession fullTextSession = getFullTextSession((Session) session.getDelegate());
Builder builder = new Builder();
String keywords = criteria.getKeywords();
if (keywords != null && keywords.length() != 0) {
String[] fields = null;
Searching searching = Searching.valueOf(criteria.getSearching());
switch(searching) {
case TITLE_MSG:
fields = new String[] { "message.text", "topic.subject" };
break;
case MSG:
fields = new String[] { "message.text" };
break;
}
MultiFieldQueryParser parser = new MultiFieldQueryParser(fields, new StandardAnalyzer());
builder.add(parser.parse(keywords), MUST);
}
String forumId = criteria.getForum();
if (forumId != null && forumId.length() != 0) {
builder.add(new TermQuery(new Term("topic.forum.id", forumId)), MUST);
}
String categoryId = criteria.getCategory();
if (categoryId != null && categoryId.length() != 0) {
builder.add(new TermQuery(new Term("topic.forum.category.id", categoryId)), MUST);
}
String userName = criteria.getAuthor();
if (userName != null && userName.length() != 0) {
builder.add(new WildcardQuery(new Term("poster.userId", userName)), MUST);
}
String timePeriod = criteria.getTimePeriod();
if (timePeriod != null && timePeriod.length() != 0) {
addPostTimeQuery(builder, TimePeriod.valueOf(timePeriod));
}
FullTextQuery fullTextQuery = fullTextSession.createFullTextQuery(builder.build(), Post.class);
SortOrder sortOrder = SortOrder.valueOf(criteria.getSortOrder());
SortBy sortBy = valueOf(criteria.getSortBy());
fullTextQuery.setSort(getSort(sortBy, sortOrder));
fullTextQuery.setProjection("topic.id");
LinkedHashSet<Integer> topicIds = new LinkedHashSet<Integer>();
LinkedHashSet<Integer> topicToDispIds = new LinkedHashSet<Integer>();
int start = criteria.getPageSize() * criteria.getPageNumber();
int end = start + criteria.getPageSize();
int index = 0;
for (Object o : fullTextQuery.list()) {
Integer id = (Integer) ((Object[]) o)[0];
if (topicIds.add(id)) {
if (index >= start && index < end) {
topicToDispIds.add(id);
}
index++;
}
}
List<Topic> topics = null;
if (topicToDispIds.size() > 0) {
Query q = session.createQuery("from Topic as t join fetch t.poster where t.id IN ( :topicIds )");
q.setParameter("topicIds", topicToDispIds);
List<Topic> results = q.getResultList();
topics = new LinkedList<Topic>();
for (Integer id : topicToDispIds) {
for (Topic topic : results) {
if (id.equals(topic.getId())) {
topics.add(topic);
break;
}
}
}
}
ResultPage<Topic> resultPage = new ResultPage<Topic>();
resultPage.setPage(topics);
resultPage.setResultSize(topicIds.size());
return resultPage;
} catch (ParseException e) {
return null;
} catch (Exception e) {
throw new ModuleException(e.getMessage(), e);
}
} else {
throw new IllegalArgumentException("criteria cannot be null");
}
}
use of org.hibernate.search.FullTextSession in project rubia-forums by flashboss.
the class ForumsSearchModuleImpl method findTopics.
@SuppressWarnings("unchecked")
public ResultPage<Topic> findTopics(SearchCriteria criteria) throws ModuleException {
if (criteria != null) {
try {
EntityManager session = getSession();
FullTextSession fullTextSession = getFullTextSession((Session) session.getDelegate());
Builder builder = new Builder();
String keywords = criteria.getKeywords();
if (keywords != null && keywords.length() != 0) {
String[] fields = null;
Searching searching = Searching.valueOf(criteria.getSearching());
switch(searching) {
case TITLE_MSG:
fields = new String[] { "message.text", "topic.subject" };
break;
case MSG:
fields = new String[] { "message.text" };
break;
}
MultiFieldQueryParser parser = new MultiFieldQueryParser(fields, new StandardAnalyzer());
builder.add(parser.parse(keywords), MUST);
}
String forumId = criteria.getForum();
if (forumId != null && forumId.length() != 0) {
builder.add(new TermQuery(new Term("topic.forum.id", forumId)), MUST);
}
String categoryId = criteria.getCategory();
if (categoryId != null && categoryId.length() != 0) {
builder.add(new TermQuery(new Term("topic.forum.category.id", categoryId)), MUST);
}
String userName = criteria.getAuthor();
if (userName != null && userName.length() != 0) {
builder.add(new WildcardQuery(new Term("poster.userId", userName)), MUST);
}
String timePeriod = criteria.getTimePeriod();
if (timePeriod != null && timePeriod.length() != 0) {
addPostTimeQuery(builder, TimePeriod.valueOf(timePeriod));
}
FullTextQuery fullTextQuery = fullTextSession.createFullTextQuery(builder.build(), Post.class);
SortOrder sortOrder = SortOrder.valueOf(criteria.getSortOrder());
SortBy sortBy = valueOf(criteria.getSortBy());
fullTextQuery.setSort(getSort(sortBy, sortOrder));
fullTextQuery.setProjection("topic.id");
LinkedHashSet<Integer> topicIds = new LinkedHashSet<Integer>();
LinkedHashSet<Integer> topicToDispIds = new LinkedHashSet<Integer>();
int start = criteria.getPageSize() * criteria.getPageNumber();
int end = start + criteria.getPageSize();
int index = 0;
for (Object o : fullTextQuery.list()) {
Integer id = (Integer) ((Object[]) o)[0];
if (topicIds.add(id)) {
if (index >= start && index < end) {
topicToDispIds.add(id);
}
index++;
}
}
List<Topic> topics = null;
if (topicToDispIds.size() > 0) {
Query q = session.createQuery("from Topic as t join fetch t.poster where t.id IN ( :topicIds )");
q.setParameter("topicIds", topicToDispIds);
List<Topic> results = q.getResultList();
topics = new LinkedList<Topic>();
for (Integer id : topicToDispIds) {
for (Topic topic : results) {
if (id.equals(topic.getId())) {
topics.add(topic);
break;
}
}
}
}
ResultPage<Topic> resultPage = new ResultPage<Topic>();
resultPage.setPage(topics);
resultPage.setResultSize(topicIds.size());
return resultPage;
} catch (ParseException e) {
return null;
} catch (Exception e) {
throw new ModuleException(e.getMessage(), e);
}
} else {
throw new IllegalArgumentException("criteria cannot be null");
}
}
Aggregations