Search in sources :

Example 11 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 12 with MultiFieldQueryParser

use of org.apache.lucene.queryparser.classic.MultiFieldQueryParser in project openmrs-core by openmrs.

the class LuceneQuery method newMultipleFieldQueryParser.

protected MultiFieldQueryParser newMultipleFieldQueryParser(Collection<String> fields) {
    Analyzer analyzer;
    if (getType().isAssignableFrom(PatientIdentifier.class) || getType().isAssignableFrom(PersonName.class) || getType().isAssignableFrom(PersonAttribute.class)) {
        analyzer = getFullTextSession().getSearchFactory().getAnalyzer(LuceneAnalyzers.EXACT_ANALYZER);
    } else {
        analyzer = getFullTextSession().getSearchFactory().getAnalyzer(getType());
    }
    MultiFieldQueryParser queryParser = new MultiFieldQueryParser(fields.toArray(new String[fields.size()]), analyzer);
    setDefaultOperator(queryParser);
    return queryParser;
}
Also used : MultiFieldQueryParser(org.apache.lucene.queryparser.classic.MultiFieldQueryParser) Analyzer(org.apache.lucene.analysis.Analyzer) PersonAttribute(org.openmrs.PersonAttribute)

Example 13 with MultiFieldQueryParser

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

the class SearchServiceImpl method createQuery.

protected BooleanQuery createQuery(String queryString, List<String> condQueries) throws ParseException {
    BooleanQuery query = new BooleanQuery();
    if (StringHelper.containsNonWhitespace(queryString)) {
        String[] fieldsArr = getFieldsToSearchIn();
        QueryParser queryParser = new MultiFieldQueryParser(SearchService.OO_LUCENE_VERSION, fieldsArr, analyzer);
        // some add. fields are not tokenized and not lowered case
        queryParser.setLowercaseExpandedTerms(false);
        Query multiFieldQuery = queryParser.parse(queryString.toLowerCase());
        query.add(multiFieldQuery, Occur.MUST);
    }
    if (condQueries != null && !condQueries.isEmpty()) {
        for (String condQueryString : condQueries) {
            QueryParser condQueryParser = new QueryParser(SearchService.OO_LUCENE_VERSION, condQueryString, analyzer);
            condQueryParser.setLowercaseExpandedTerms(false);
            Query condQuery = condQueryParser.parse(condQueryString);
            query.add(condQuery, Occur.MUST);
        }
    }
    return query;
}
Also used : BooleanQuery(org.apache.lucene.search.BooleanQuery) MultiFieldQueryParser(org.apache.lucene.queryparser.classic.MultiFieldQueryParser) QueryParser(org.apache.lucene.queryparser.classic.QueryParser) MultiFieldQueryParser(org.apache.lucene.queryparser.classic.MultiFieldQueryParser) Query(org.apache.lucene.search.Query) BooleanQuery(org.apache.lucene.search.BooleanQuery)

Example 14 with MultiFieldQueryParser

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

the class LuceneVsLuceneTest method testLuceneVsLucene.

@Test
public void testLuceneVsLucene() throws IOException, ParseException {
    for (ODocument oDocument : db.browseClass("Song")) {
        String title = oDocument.field("title");
        if (title != null) {
            Document d = new Document();
            d.add(new TextField("title", title, Field.Store.YES));
            d.add(new TextField("Song.title", title, Field.Store.YES));
            indexWriter.addDocument(d);
        }
    }
    indexWriter.commit();
    indexWriter.close();
    IndexReader reader = DirectoryReader.open(getDirectory());
    assertThat(reader.numDocs()).isEqualTo(Long.valueOf(db.countClass("Song")).intValue());
    IndexSearcher searcher = new IndexSearcher(reader);
    Query query = new MultiFieldQueryParser(new String[] { "title" }, analyzer).parse("down the");
    final TopDocs docs = searcher.search(query, Integer.MAX_VALUE);
    ScoreDoc[] hits = docs.scoreDocs;
    List<ODocument> oDocs = db.query(new OSQLSynchQuery<ODocument>("select *,$score from Song where title LUCENE \"down the\""));
    Assert.assertEquals(oDocs.size(), hits.length);
    int i = 0;
    for (ScoreDoc hit : hits) {
        Assert.assertEquals(oDocs.get(i).field("$score"), hit.score);
        i++;
    }
    reader.close();
}
Also used : IndexSearcher(org.apache.lucene.search.IndexSearcher) Query(org.apache.lucene.search.Query) OSQLSynchQuery(com.orientechnologies.orient.core.sql.query.OSQLSynchQuery) MultiFieldQueryParser(org.apache.lucene.queryparser.classic.MultiFieldQueryParser) Document(org.apache.lucene.document.Document) ODocument(com.orientechnologies.orient.core.record.impl.ODocument) ScoreDoc(org.apache.lucene.search.ScoreDoc) TopDocs(org.apache.lucene.search.TopDocs) IndexReader(org.apache.lucene.index.IndexReader) TextField(org.apache.lucene.document.TextField) ODocument(com.orientechnologies.orient.core.record.impl.ODocument) Test(org.junit.Test)

Example 15 with MultiFieldQueryParser

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

the class LuceneSearch method query.

/* (non-Javadoc)
   * @see org.apache.zeppelin.search.Search#query(java.lang.String)
   */
@Override
public List<Map<String, String>> query(String queryStr) {
    if (null == indexDirectory) {
        throw new IllegalStateException("Something went wrong on instance creation time, index dir is null");
    }
    List<Map<String, String>> result = Collections.emptyList();
    try (IndexReader indexReader = DirectoryReader.open(indexDirectory)) {
        IndexSearcher indexSearcher = new IndexSearcher(indexReader);
        Analyzer analyzer = new StandardAnalyzer();
        MultiFieldQueryParser parser = new MultiFieldQueryParser(new String[] { SEARCH_FIELD_TEXT, SEARCH_FIELD_TITLE }, analyzer);
        Query query = parser.parse(queryStr);
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Searching for: {}", query.toString(SEARCH_FIELD_TEXT));
        }
        SimpleHTMLFormatter htmlFormatter = new SimpleHTMLFormatter();
        Highlighter highlighter = new Highlighter(htmlFormatter, new QueryScorer(query));
        result = doSearch(indexSearcher, query, analyzer, highlighter);
    } catch (IOException e) {
        LOGGER.error("Failed to open index dir {}, make sure indexing finished OK", indexDirectory, e);
    } catch (ParseException e) {
        LOGGER.error("Failed to parse query {}", queryStr, e);
    }
    return result;
}
Also used : IndexSearcher(org.apache.lucene.search.IndexSearcher) MultiFieldQueryParser(org.apache.lucene.queryparser.classic.MultiFieldQueryParser) Query(org.apache.lucene.search.Query) WildcardQuery(org.apache.lucene.search.WildcardQuery) QueryScorer(org.apache.lucene.search.highlight.QueryScorer) IOException(java.io.IOException) Analyzer(org.apache.lucene.analysis.Analyzer) StandardAnalyzer(org.apache.lucene.analysis.standard.StandardAnalyzer) StandardAnalyzer(org.apache.lucene.analysis.standard.StandardAnalyzer) IndexReader(org.apache.lucene.index.IndexReader) ParseException(org.apache.lucene.queryparser.classic.ParseException) SimpleHTMLFormatter(org.apache.lucene.search.highlight.SimpleHTMLFormatter) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap) Highlighter(org.apache.lucene.search.highlight.Highlighter)

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