Search in sources :

Example 26 with MultiFieldQueryParser

use of org.apache.lucene.queryparser.classic.MultiFieldQueryParser 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 27 with MultiFieldQueryParser

use of org.apache.lucene.queryparser.classic.MultiFieldQueryParser 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 28 with MultiFieldQueryParser

use of org.apache.lucene.queryparser.classic.MultiFieldQueryParser in project carbondata by apache.

the class LuceneCoarseGrainDataMap method prune.

/**
 * Prune the datamap with filter expression. It returns the list of
 * blocklets where these filters can exist.
 */
@Override
public List<Blocklet> prune(FilterResolverIntf filterExp, SegmentProperties segmentProperties, List<PartitionSpec> partitions) throws IOException {
    // convert filter expr into lucene list query
    List<String> fields = new ArrayList<String>();
    // only for test , query all data
    String strQuery = "*:*";
    String[] sFields = new String[fields.size()];
    fields.toArray(sFields);
    // get analyzer
    if (analyzer == null) {
        analyzer = new StandardAnalyzer();
    }
    // use MultiFieldQueryParser to parser query
    QueryParser queryParser = new MultiFieldQueryParser(sFields, analyzer);
    Query query;
    try {
        query = queryParser.parse(strQuery);
    } catch (ParseException e) {
        String errorMessage = String.format("failed to filter block with query %s, detail is %s", strQuery, e.getMessage());
        LOGGER.error(errorMessage);
        return null;
    }
    // execute index search
    TopDocs result;
    try {
        result = indexSearcher.search(query, MAX_RESULT_NUMBER);
    } catch (IOException e) {
        String errorMessage = String.format("failed to search lucene data, detail is %s", e.getMessage());
        LOGGER.error(errorMessage);
        throw new IOException(errorMessage);
    }
    // temporary data, delete duplicated data
    // Map<BlockId, Map<BlockletId, Map<PageId, Set<RowId>>>>
    Map<String, Set<Number>> mapBlocks = new HashMap<String, Set<Number>>();
    for (ScoreDoc scoreDoc : result.scoreDocs) {
        // get a document
        Document doc = indexSearcher.doc(scoreDoc.doc);
        // get all fields
        List<IndexableField> fieldsInDoc = doc.getFields();
        // get this block id Map<BlockId, Set<BlockletId>>>>
        String blockId = fieldsInDoc.get(BLOCKID_ID).stringValue();
        Set<Number> setBlocklets = mapBlocks.get(blockId);
        if (setBlocklets == null) {
            setBlocklets = new HashSet<Number>();
            mapBlocks.put(blockId, setBlocklets);
        }
        // get the blocklet id Set<BlockletId>
        Number blockletId = fieldsInDoc.get(BLOCKLETID_ID).numericValue();
        if (!setBlocklets.contains(blockletId.intValue())) {
            setBlocklets.add(blockletId.intValue());
        }
    }
    // result blocklets
    List<Blocklet> blocklets = new ArrayList<Blocklet>();
    // transform all blocks into result type blocklets Map<BlockId, Set<BlockletId>>
    for (Map.Entry<String, Set<Number>> mapBlock : mapBlocks.entrySet()) {
        String blockId = mapBlock.getKey();
        Set<Number> setBlocklets = mapBlock.getValue();
        // for blocklets in this block Set<BlockletId>
        for (Number blockletId : setBlocklets) {
            // add a CoarseGrainBlocklet
            blocklets.add(new Blocklet(blockId, blockletId.toString()));
        }
    }
    return blocklets;
}
Also used : HashSet(java.util.HashSet) Set(java.util.Set) Query(org.apache.lucene.search.Query) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) Document(org.apache.lucene.document.Document) ScoreDoc(org.apache.lucene.search.ScoreDoc) TopDocs(org.apache.lucene.search.TopDocs) MultiFieldQueryParser(org.apache.lucene.queryparser.classic.MultiFieldQueryParser) IOException(java.io.IOException) IndexableField(org.apache.lucene.index.IndexableField) MultiFieldQueryParser(org.apache.lucene.queryparser.classic.MultiFieldQueryParser) QueryParser(org.apache.lucene.queryparser.classic.QueryParser) Blocklet(org.apache.carbondata.core.indexstore.Blocklet) StandardAnalyzer(org.apache.lucene.analysis.standard.StandardAnalyzer) ParseException(org.apache.lucene.queryparser.classic.ParseException) HashMap(java.util.HashMap) Map(java.util.Map) CoarseGrainDataMap(org.apache.carbondata.core.datamap.dev.cgdatamap.CoarseGrainDataMap)

Example 29 with MultiFieldQueryParser

use of org.apache.lucene.queryparser.classic.MultiFieldQueryParser in project orientdb by orientechnologies.

the class OLuceneIndexType method getQueryParser.

protected static Query getQueryParser(OIndexDefinition index, String key, Analyzer analyzer) throws ParseException {
    QueryParser queryParser;
    if ((key).startsWith("(")) {
        queryParser = new QueryParser("", analyzer);
    } else {
        String[] fields = null;
        if (index.isAutomatic()) {
            fields = index.getFields().toArray(new String[index.getFields().size()]);
        } else {
            int length = index.getTypes().length;
            fields = new String[length];
            for (int i = 0; i < length; i++) {
                fields[i] = "k" + i;
            }
        }
        queryParser = new MultiFieldQueryParser(fields, analyzer);
    }
    return queryParser.parse(key);
}
Also used : MultiFieldQueryParser(org.apache.lucene.queryparser.classic.MultiFieldQueryParser) QueryParser(org.apache.lucene.queryparser.classic.QueryParser) MultiFieldQueryParser(org.apache.lucene.queryparser.classic.MultiFieldQueryParser)

Example 30 with MultiFieldQueryParser

use of org.apache.lucene.queryparser.classic.MultiFieldQueryParser in project textdb by TextDB.

the class FuzzyTokenMatcherSourceOperator method createLuceneQueryObject.

public static Query createLuceneQueryObject(FuzzyTokenPredicate predicate) throws DataflowException {
    try {
        /*
             * By default the boolean query takes 1024 # of clauses as the max
             * limit. Since our input query has no limitaion on the number of
             * tokens, we have to put a check.
             */
        if (predicate.getThreshold() > 1024)
            BooleanQuery.setMaxClauseCount(predicate.getThreshold() + 1);
        BooleanQuery.Builder builder = new BooleanQuery.Builder();
        builder.setMinimumNumberShouldMatch(predicate.getThreshold());
        MultiFieldQueryParser qp = new MultiFieldQueryParser(predicate.getAttributeNames().stream().toArray(String[]::new), LuceneAnalyzerConstants.getLuceneAnalyzer(predicate.getLuceneAnalyzerStr()));
        for (String s : predicate.getQueryTokens()) {
            builder.add(qp.parse(s), Occur.SHOULD);
        }
        return builder.build();
    } catch (ParseException e) {
        throw new DataflowException(e);
    }
}
Also used : BooleanQuery(org.apache.lucene.search.BooleanQuery) MultiFieldQueryParser(org.apache.lucene.queryparser.classic.MultiFieldQueryParser) DataflowException(edu.uci.ics.texera.api.exception.DataflowException) ParseException(org.apache.lucene.queryparser.classic.ParseException)

Aggregations

MultiFieldQueryParser (org.apache.lucene.queryparser.classic.MultiFieldQueryParser)37 ParseException (org.apache.lucene.queryparser.classic.ParseException)24 Query (org.apache.lucene.search.Query)17 StandardAnalyzer (org.apache.lucene.analysis.standard.StandardAnalyzer)14 QueryParser (org.apache.lucene.queryparser.classic.QueryParser)14 Term (org.apache.lucene.index.Term)11 IndexSearcher (org.apache.lucene.search.IndexSearcher)11 TermQuery (org.apache.lucene.search.TermQuery)11 IOException (java.io.IOException)10 WildcardQuery (org.apache.lucene.search.WildcardQuery)10 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 Builder (org.apache.lucene.search.BooleanQuery.Builder)8 TopDocs (org.apache.lucene.search.TopDocs)8 FullTextQuery (org.hibernate.search.FullTextQuery)8 FullTextSession (org.hibernate.search.FullTextSession)8