Search in sources :

Example 16 with FullTextSession

use of org.hibernate.search.FullTextSession in project rubia-forums by flashboss.

the class ForumsSearchModuleImpl method findPosts.

@SuppressWarnings("unchecked")
public ResultPage<Post> findPosts(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());
            String sortByStr = criteria.getSortBy();
            SortBy sortBy = null;
            if (sortByStr != null)
                sortBy = valueOf(sortByStr);
            fullTextQuery.setSort(getSort(sortBy, sortOrder));
            fullTextQuery.setFirstResult(criteria.getPageSize() * criteria.getPageNumber());
            fullTextQuery.setMaxResults(criteria.getPageSize());
            ResultPage<Post> resultPage = new ResultPage<Post>();
            resultPage.setPage(fullTextQuery.list());
            resultPage.setResultSize(fullTextQuery.getResultSize());
            return resultPage;
        } catch (ParseException e) {
            return null;
        } catch (Exception e) {
            throw new ModuleException(e.getMessage(), e);
        }
    } else {
        throw new IllegalArgumentException("criteria cannot be null");
    }
}
Also used : TermQuery(org.apache.lucene.search.TermQuery) WildcardQuery(org.apache.lucene.search.WildcardQuery) FullTextSession(org.hibernate.search.FullTextSession) Search.getFullTextSession(org.hibernate.search.Search.getFullTextSession) MultiFieldQueryParser(org.apache.lucene.queryparser.classic.MultiFieldQueryParser) SortBy(it.vige.rubia.search.SortBy) Post(it.vige.rubia.model.Post) Builder(org.apache.lucene.search.BooleanQuery.Builder) SortOrder(it.vige.rubia.search.SortOrder) Term(org.apache.lucene.index.Term) ParseException(org.apache.lucene.queryparser.classic.ParseException) ModuleException(it.vige.rubia.ModuleException) EntityManager(javax.persistence.EntityManager) Searching(it.vige.rubia.search.Searching) ResultPage(it.vige.rubia.search.ResultPage) StandardAnalyzer(org.apache.lucene.analysis.standard.StandardAnalyzer) ParseException(org.apache.lucene.queryparser.classic.ParseException) FullTextQuery(org.hibernate.search.FullTextQuery) ModuleException(it.vige.rubia.ModuleException)

Example 17 with FullTextSession

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");
    }
}
Also used : LinkedHashSet(java.util.LinkedHashSet) WildcardQuery(org.apache.lucene.search.WildcardQuery) FullTextSession(org.hibernate.search.FullTextSession) Search.getFullTextSession(org.hibernate.search.Search.getFullTextSession) FullTextQuery(org.hibernate.search.FullTextQuery) WildcardQuery(org.apache.lucene.search.WildcardQuery) Query(javax.persistence.Query) TermQuery(org.apache.lucene.search.TermQuery) SortBy(it.vige.rubia.search.SortBy) Builder(org.apache.lucene.search.BooleanQuery.Builder) ResultPage(it.vige.rubia.search.ResultPage) Topic(it.vige.rubia.model.Topic) ModuleException(it.vige.rubia.ModuleException) TermQuery(org.apache.lucene.search.TermQuery) MultiFieldQueryParser(org.apache.lucene.queryparser.classic.MultiFieldQueryParser) SortOrder(it.vige.rubia.search.SortOrder) Term(org.apache.lucene.index.Term) ParseException(org.apache.lucene.queryparser.classic.ParseException) ModuleException(it.vige.rubia.ModuleException) EntityManager(javax.persistence.EntityManager) Searching(it.vige.rubia.search.Searching) StandardAnalyzer(org.apache.lucene.analysis.standard.StandardAnalyzer) ParseException(org.apache.lucene.queryparser.classic.ParseException) FullTextQuery(org.hibernate.search.FullTextQuery)

Example 18 with FullTextSession

use of org.hibernate.search.FullTextSession in project ice by JBEI.

the class HibernateSearch method executeSearch.

@SuppressWarnings("unchecked")
public SearchResults executeSearch(String userId, HashMap<String, QueryType> terms, SearchQuery searchQuery, HashMap<String, SearchResult> blastResults) {
    Session session = HibernateUtil.getSessionFactory().getCurrentSession();
    int resultCount;
    FullTextSession fullTextSession = Search.getFullTextSession(session);
    BooleanQuery.Builder builder = new BooleanQuery.Builder();
    // get classes for search
    HashSet<String> fields = new HashSet<>(SearchFieldFactory.entryFields(searchQuery.getEntryTypes()));
    Class<?>[] classes = SearchFieldFactory.classesForTypes(searchQuery.getEntryTypes());
    // generate queries for terms filtering stop words
    for (Map.Entry<String, QueryType> entry : terms.entrySet()) {
        String term = cleanQuery(entry.getKey());
        if (term.trim().isEmpty() || StandardAnalyzer.STOP_WORDS_SET.contains(term.toLowerCase()))
            continue;
        BioSafetyOption safetyOption = searchQuery.getBioSafetyOption();
        generateQueriesForType(fullTextSession, fields, builder, term, entry.getValue(), safetyOption);
    }
    // check for blast search results filter
    createBlastFilterQuery(fullTextSession, blastResults, builder);
    // wrap Lucene query in a org.hibernate.Query
    FullTextQuery fullTextQuery = fullTextSession.createFullTextQuery(builder.build(), classes);
    // get max score
    fullTextQuery.setFirstResult(0);
    fullTextQuery.setMaxResults(1);
    fullTextQuery.setProjection(FullTextQuery.SCORE);
    List<?> result = fullTextQuery.list();
    float maxScore = -1f;
    if (result.size() == 1) {
        maxScore = (Float) ((Object[]) (result.get(0)))[0];
    }
    // end get max score
    // get sorting values
    Sort sort = getSort(searchQuery.getParameters().isSortAscending(), searchQuery.getParameters().getSortField());
    fullTextQuery.setSort(sort);
    // projection (specified properties must be stored in the index @Field(store=Store.YES))
    fullTextQuery.setProjection(FullTextQuery.SCORE, FullTextQuery.ID, "owner");
    // enable security filter if needed
    checkEnableSecurityFilter(userId.toLowerCase(), fullTextQuery);
    // check sample
    checkEnableHasAttribute(fullTextQuery, searchQuery.getParameters());
    // set paging params
    fullTextQuery.setFirstResult(searchQuery.getParameters().getStart());
    fullTextQuery.setMaxResults(searchQuery.getParameters().getRetrieveCount());
    resultCount = fullTextQuery.getResultSize();
    // execute search
    result = fullTextQuery.list();
    Logger.info(userId + ": " + resultCount + " results for \"" + searchQuery.getQueryString() + "\"");
    LinkedList<SearchResult> searchResults = new LinkedList<>();
    for (Object[] objects : (Iterable<Object[]>) result) {
        float score = (Float) objects[0];
        Long entryId = (Long) objects[1];
        SearchResult searchResult;
        if (blastResults != null) {
            searchResult = blastResults.get(Long.toString(entryId));
            if (// this should not really happen since we already filter
            searchResult == null)
                continue;
        } else {
            searchResult = new SearchResult();
            searchResult.setScore(score);
            PartData info = ModelToInfoFactory.createTableView(entryId, null);
            info.setOwner((String) objects[2]);
            searchResult.setEntryInfo(info);
        }
        searchResult.setMaxScore(maxScore);
        searchResults.add(searchResult);
    }
    SearchResults results = new SearchResults();
    results.setResultCount(resultCount);
    results.setResults(searchResults);
    return results;
}
Also used : FullTextSession(org.hibernate.search.FullTextSession) QueryBuilder(org.hibernate.search.query.dsl.QueryBuilder) BioSafetyOption(org.jbei.ice.lib.shared.BioSafetyOption) SearchResults(org.jbei.ice.lib.dto.search.SearchResults) SearchResult(org.jbei.ice.lib.dto.search.SearchResult) PartData(org.jbei.ice.lib.dto.entry.PartData) FullTextQuery(org.hibernate.search.FullTextQuery) QueryType(org.jbei.ice.lib.search.QueryType) FullTextSession(org.hibernate.search.FullTextSession) Session(org.hibernate.Session)

Example 19 with FullTextSession

use of org.hibernate.search.FullTextSession in project ice by JBEI.

the class HibernateSearch method executeSearchNoTerms.

public SearchResults executeSearchNoTerms(String userId, HashMap<String, SearchResult> blastResults, SearchQuery searchQuery) {
    ArrayList<EntryType> entryTypes = searchQuery.getEntryTypes();
    if (entryTypes == null || entryTypes.isEmpty()) {
        entryTypes = new ArrayList<>(Arrays.asList(EntryType.values()));
    }
    Session session = HibernateUtil.getSessionFactory().getCurrentSession();
    int resultCount;
    FullTextSession fullTextSession = Search.getFullTextSession(session);
    BooleanQuery.Builder builder = new BooleanQuery.Builder();
    QueryBuilder qb = fullTextSession.getSearchFactory().buildQueryBuilder().forEntity(Entry.class).get();
    ArrayList<Query> except = new ArrayList<>();
    for (EntryType type : EntryType.values()) {
        if (entryTypes.contains(type))
            continue;
        except.add(qb.keyword().onField("recordType").matching(type.getName()).createQuery());
    }
    // add terms for record types
    Query[] queries = new Query[] {};
    Query recordTypeQuery = qb.all().except(except.toArray(queries)).createQuery();
    builder.add(recordTypeQuery, BooleanClause.Occur.FILTER);
    // visibility
    Query visibilityQuery = qb.keyword().onField("visibility").matching(Visibility.OK.getValue()).createQuery();
    builder.add(visibilityQuery, BooleanClause.Occur.FILTER);
    // bio safety level
    BioSafetyOption option = searchQuery.getBioSafetyOption();
    if (option != null) {
        TermContext bslContext = qb.keyword();
        Query biosafetyQuery = bslContext.onField("bioSafetyLevel").ignoreFieldBridge().matching(option.getIntValue()).createQuery();
        builder.add(biosafetyQuery, BooleanClause.Occur.FILTER);
    }
    // check filter filters
    if (searchQuery.getFieldFilters() != null && !searchQuery.getFieldFilters().isEmpty()) {
        for (FieldFilter fieldFilter : searchQuery.getFieldFilters()) {
            String searchField = SearchFieldFactory.searchFieldForEntryField(fieldFilter.getField());
            if (StringUtils.isEmpty(searchField))
                continue;
            Query filterQuery = qb.keyword().onField(searchField).matching(fieldFilter.getFilter()).createQuery();
            builder.add(filterQuery, BooleanClause.Occur.MUST);
        }
    }
    // check if there is a blast results
    createBlastFilterQuery(fullTextSession, blastResults, builder);
    // wrap Lucene query in a org.hibernate.Query
    FullTextQuery fullTextQuery = fullTextSession.createFullTextQuery(builder.build(), Entry.class);
    // get sorting values
    Sort sort = getSort(searchQuery.getParameters().isSortAscending(), searchQuery.getParameters().getSortField());
    fullTextQuery.setSort(sort);
    fullTextQuery.setProjection(ProjectionConstants.ID, "owner");
    // enable security filter if needed
    checkEnableSecurityFilter(userId, fullTextQuery);
    // enable has attachment/sequence/sample (if needed)
    checkEnableHasAttribute(fullTextQuery, searchQuery.getParameters());
    // set paging params
    fullTextQuery.setFirstResult(searchQuery.getParameters().getStart());
    fullTextQuery.setMaxResults(searchQuery.getParameters().getRetrieveCount());
    resultCount = fullTextQuery.getResultSize();
    List<?> result = fullTextQuery.list();
    LinkedList<SearchResult> searchResults = new LinkedList<>();
    // since we are using projection, result is an arraylist of objects
    for (Object object : result) {
        Object[] objects = (Object[]) object;
        long entryId = (Long) objects[0];
        SearchResult searchResult;
        if (blastResults != null) {
            searchResult = blastResults.get(Long.toString(entryId));
            if (// this should not really happen since we already filter
            searchResult == null)
                continue;
        } else {
            searchResult = new SearchResult();
            searchResult.setScore(1f);
            PartData info = ModelToInfoFactory.createTableView(entryId, null);
            info.setOwner((String) objects[1]);
            searchResult.setEntryInfo(info);
        }
        searchResult.setMaxScore(1f);
        searchResults.add(searchResult);
    }
    SearchResults results = new SearchResults();
    results.setResultCount(resultCount);
    results.setResults(searchResults);
    Logger.info(userId + ": obtained " + resultCount + " results for empty query");
    return results;
}
Also used : FullTextSession(org.hibernate.search.FullTextSession) SearchQuery(org.jbei.ice.lib.dto.search.SearchQuery) FullTextQuery(org.hibernate.search.FullTextQuery) QueryBuilder(org.hibernate.search.query.dsl.QueryBuilder) BioSafetyOption(org.jbei.ice.lib.shared.BioSafetyOption) QueryBuilder(org.hibernate.search.query.dsl.QueryBuilder) SearchResults(org.jbei.ice.lib.dto.search.SearchResults) TermContext(org.hibernate.search.query.dsl.TermContext) Entry(org.jbei.ice.storage.model.Entry) SearchResult(org.jbei.ice.lib.dto.search.SearchResult) FieldFilter(org.jbei.ice.lib.dto.search.FieldFilter) EntryType(org.jbei.ice.lib.dto.entry.EntryType) PartData(org.jbei.ice.lib.dto.entry.PartData) FullTextQuery(org.hibernate.search.FullTextQuery) FullTextSession(org.hibernate.search.FullTextSession) Session(org.hibernate.Session)

Aggregations

FullTextSession (org.hibernate.search.FullTextSession)19 FullTextQuery (org.hibernate.search.FullTextQuery)13 ModuleException (it.vige.rubia.ModuleException)8 ResultPage (it.vige.rubia.search.ResultPage)8 Searching (it.vige.rubia.search.Searching)8 SortBy (it.vige.rubia.search.SortBy)8 SortOrder (it.vige.rubia.search.SortOrder)8 EntityManager (javax.persistence.EntityManager)8 StandardAnalyzer (org.apache.lucene.analysis.standard.StandardAnalyzer)8 Term (org.apache.lucene.index.Term)8 MultiFieldQueryParser (org.apache.lucene.queryparser.classic.MultiFieldQueryParser)8 ParseException (org.apache.lucene.queryparser.classic.ParseException)8 Builder (org.apache.lucene.search.BooleanQuery.Builder)8 TermQuery (org.apache.lucene.search.TermQuery)8 WildcardQuery (org.apache.lucene.search.WildcardQuery)8 Search.getFullTextSession (org.hibernate.search.Search.getFullTextSession)8 Session (org.hibernate.Session)7 QueryBuilder (org.hibernate.search.query.dsl.QueryBuilder)6 Post (it.vige.rubia.model.Post)4 Topic (it.vige.rubia.model.Topic)4