List of usage examples for org.apache.lucene.search IndexSearcher rewrite
public Query rewrite(Query original) throws IOException
From source file:org.jamwiki.search.LuceneSearchEngine.java
License:LGPL
/** * Find all documents that contain a specific search term, ordered by relevance. * This method supports all Lucene search query syntax. * * @param virtualWiki The virtual wiki for the topic. * @param text The search term being searched for. * @return A collection of SearchResultEntry objects for all documents that * contain the search term.//from w w w . java2 s. co m */ public Collection findResults(String virtualWiki, String text) { StandardAnalyzer analyzer = new StandardAnalyzer(); Collection results = new Vector(); logger.fine("search text: " + text); IndexSearcher searcher = null; try { BooleanQuery query = new BooleanQuery(); QueryParser qp; qp = new QueryParser(ITYPE_TOPIC, analyzer); query.add(qp.parse(text), Occur.SHOULD); qp = new QueryParser(ITYPE_CONTENT, analyzer); query.add(qp.parse(text), Occur.SHOULD); searcher = new IndexSearcher(FSDirectory.getDirectory(getSearchIndexPath(virtualWiki))); // rewrite the query to expand it - required for wildcards to work with highlighter Query rewrittenQuery = searcher.rewrite(query); // actually perform the search Hits hits = searcher.search(rewrittenQuery); Highlighter highlighter = new Highlighter( new SimpleHTMLFormatter("<span class=\"highlight\">", "</span>"), new SimpleHTMLEncoder(), new QueryScorer(rewrittenQuery)); for (int i = 0; i < hits.length(); i++) { String summary = retrieveResultSummary(hits.doc(i), highlighter, analyzer); SearchResultEntry result = new SearchResultEntry(); result.setRanking(hits.score(i)); result.setTopic(hits.doc(i).get(ITYPE_TOPIC_PLAIN)); result.setSummary(summary); results.add(result); } } catch (Exception e) { logger.severe("Exception while searching for " + text, e); } finally { if (searcher != null) { try { searcher.close(); } catch (Exception e) { } } } return results; }
From source file:org.jhlabs.scany.engine.search.LuceneSearcher.java
License:Open Source License
public static RecordList search(SearchModel searchModel, RecordExtractor recordExtractor) throws QueryBuilderException, RecordKeyException, IOException, ParseException { IndexSearcher indexSearcher = null; try {// w w w . j ava 2 s. co m Directory directory = searchModel.getRelation().openDirectory(); indexSearcher = new IndexSearcher(directory); Analyzer analyzer; if (searchModel.getRelation().getPerFieldAnalyzer() != null) analyzer = searchModel.getRelation().getPerFieldAnalyzer(); else analyzer = searchModel.getRelation().getAnalyzer(); LuceneQueryBuilder queryBuilder = new LuceneQueryBuilder(); queryBuilder.addQuery(searchModel.getFilterAttributeList()); queryBuilder.addQuery(searchModel.getParsedQueryText(), searchModel.getQueryAttributeList(), analyzer); Query query = queryBuilder.build(); query = indexSearcher.rewrite(query); List<SortAttribute> sortAttributeList = searchModel.getSortAttributeList(); Sort sort = null; if (sortAttributeList != null && sortAttributeList.size() > 0) sort = SearchModelUtils.makeSort(searchModel.getSortAttributeList()); ScoreDoc[] docs = null; if (sort == null) { TopDocs topDocs = indexSearcher.search(query, searchModel.getHitsPerPage()); docs = topDocs.scoreDocs; searchModel.setTotalRecords(topDocs.totalHits); } else { TopFieldDocs topFieldDocs = indexSearcher.search(query, searchModel.getHitsPerPage(), sort); docs = topFieldDocs.scoreDocs; searchModel.setTotalRecords(topFieldDocs.totalHits); } recordExtractor.extract(indexSearcher.getIndexReader(), docs); return recordExtractor.getRecordList(); } finally { try { if (indexSearcher != null) indexSearcher.close(); } catch (Exception e2) { e2.printStackTrace(); } } }
From source file:org.moxie.proxy.LuceneExecutor.java
License:Apache License
/** * Searches the specified repositories for the given text or query * /*from w w w. j ava2s . c om*/ * @param text * if the text is null or empty, null is returned * @param page * the page number to retrieve. page is 1-indexed. * @param pageSize * the number of elements to return for this page * @param repositories * a list of repositories to search. if no repositories are * specified null is returned. * @return a list of SearchResults in order from highest to the lowest score * */ public List<SearchResult> search(String text, int page, int pageSize, String... repositories) { if (StringUtils.isEmpty(text)) { return null; } if (repositories == null || repositories.length == 0) { return null; } Set<SearchResult> results = new LinkedHashSet<SearchResult>(); StandardAnalyzer analyzer = new StandardAnalyzer(LUCENE_VERSION); try { // default search checks groupId and artifactId BooleanQuery query = new BooleanQuery(); QueryParser qp; qp = new QueryParser(LUCENE_VERSION, FIELD_GROUPID, analyzer); qp.setAllowLeadingWildcard(true); query.add(qp.parse(text), Occur.SHOULD); qp = new QueryParser(LUCENE_VERSION, FIELD_ARTIFACTID, analyzer); qp.setAllowLeadingWildcard(true); query.add(qp.parse(text), Occur.SHOULD); IndexSearcher searcher; if (repositories.length == 1) { // single repository search searcher = getIndexSearcher(repositories[0]); } else { // multiple repository search List<IndexReader> readers = new ArrayList<IndexReader>(); for (String repository : repositories) { IndexSearcher repositoryIndex = getIndexSearcher(repository); readers.add(repositoryIndex.getIndexReader()); } IndexReader[] rdrs = readers.toArray(new IndexReader[readers.size()]); MultiSourceReader reader = new MultiSourceReader(rdrs); searcher = new IndexSearcher(reader); } Query rewrittenQuery = searcher.rewrite(query); Sort sort = new Sort(new SortField(FIELD_DATE, SortField.STRING, true)); TopFieldDocs topDocs = searcher.search(rewrittenQuery, 10000, sort); int offset = Math.max(0, (page - 1) * pageSize); ScoreDoc[] hits = topDocs.scoreDocs; int totalHits = topDocs.totalHits; if (pageSize <= 0) { pageSize = totalHits; } if (totalHits > offset) { for (int i = offset, len = Math.min(offset + pageSize, hits.length); i < len; i++) { int docId = hits[i].doc; Document doc = searcher.doc(docId); SearchResult result = createSearchResult(doc, i + 1, totalHits); if (repositories.length == 1) { // single repository search result.repository = repositories[0]; } else { // multi-repository search MultiSourceReader reader = (MultiSourceReader) searcher.getIndexReader(); int index = reader.getSourceIndex(docId); result.repository = repositories[index]; } results.add(result); } } } catch (Exception e) { logger.log(Level.SEVERE, MessageFormat.format("Exception while searching for {0}", text), e); } return new ArrayList<SearchResult>(results); }
From source file:org.opencms.search.CmsSearchIndex.java
License:Open Source License
/** * Performs a search on the index within the given fields.<p> * /*from ww w . j a va2 s. co m*/ * The result is returned as List with entries of type I_CmsSearchResult.<p> * @param cms the current user's Cms object * @param params the parameters to use for the search * @return the List of results found or an empty list * @throws CmsSearchException if something goes wrong */ public synchronized CmsSearchResultList search(CmsObject cms, CmsSearchParameters params) throws CmsSearchException { long timeTotal = -System.currentTimeMillis(); long timeLucene; long timeResultProcessing; if (LOG.isDebugEnabled()) { LOG.debug(Messages.get().getBundle().key(Messages.LOG_SEARCH_PARAMS_2, params, getName())); } // the hits found during the search TopDocs hits; // storage for the results found CmsSearchResultList searchResults = new CmsSearchResultList(); int previousPriority = Thread.currentThread().getPriority(); try { // copy the user OpenCms context CmsObject searchCms = OpenCms.initCmsObject(cms); if (getPriority() > 0) { // change thread priority in order to reduce search impact on overall system performance Thread.currentThread().setPriority(getPriority()); } // change the project searchCms.getRequestContext().setCurrentProject(searchCms.readProject(getProject())); timeLucene = -System.currentTimeMillis(); // several search options are searched using filters BooleanFilter filter = new BooleanFilter(); // append root path filter filter = appendPathFilter(searchCms, filter, params.getRoots()); // append category filter filter = appendCategoryFilter(searchCms, filter, params.getCategories()); // append resource type filter filter = appendResourceTypeFilter(searchCms, filter, params.getResourceTypes()); // append date last modified filter filter = appendDateLastModifiedFilter(filter, params.getMinDateLastModified(), params.getMaxDateLastModified()); // append date created filter filter = appendDateCreatedFilter(filter, params.getMinDateCreated(), params.getMaxDateCreated()); // the search query to use, will be constructed in the next lines Query query = null; // store separate fields query for excerpt highlighting Query fieldsQuery = null; // get an index searcher that is certainly up to date indexSearcherUpdate(); IndexSearcher searcher = getSearcher(); if (!params.isIgnoreQuery()) { // since OpenCms 8 the query can be empty in which case only filters are used for the result if (params.getParsedQuery() != null) { // the query was already build, re-use it QueryParser p = new QueryParser(LUCENE_VERSION, CmsSearchField.FIELD_CONTENT, getAnalyzer()); fieldsQuery = p.parse(params.getParsedQuery()); } else if (params.getFieldQueries() != null) { // each field has an individual query BooleanQuery mustOccur = null; BooleanQuery shouldOccur = null; for (CmsSearchParameters.CmsSearchFieldQuery fq : params.getFieldQueries()) { // add one sub-query for each defined field QueryParser p = new QueryParser(LUCENE_VERSION, fq.getFieldName(), getAnalyzer()); // first generate the combined keyword query Query keywordQuery = null; if (fq.getSearchTerms().size() == 1) { // this is just a single size keyword list keywordQuery = p.parse(fq.getSearchTerms().get(0)); } else { // multiple size keyword list BooleanQuery keywordListQuery = new BooleanQuery(); for (String keyword : fq.getSearchTerms()) { keywordListQuery.add(p.parse(keyword), fq.getTermOccur()); } keywordQuery = keywordListQuery; } if (BooleanClause.Occur.SHOULD.equals(fq.getOccur())) { if (shouldOccur == null) { shouldOccur = new BooleanQuery(); } shouldOccur.add(keywordQuery, fq.getOccur()); } else { if (mustOccur == null) { mustOccur = new BooleanQuery(); } mustOccur.add(keywordQuery, fq.getOccur()); } } BooleanQuery booleanFieldsQuery = new BooleanQuery(); if (mustOccur != null) { booleanFieldsQuery.add(mustOccur, BooleanClause.Occur.MUST); } if (shouldOccur != null) { booleanFieldsQuery.add(shouldOccur, BooleanClause.Occur.MUST); } fieldsQuery = searcher.rewrite(booleanFieldsQuery); } else if ((params.getFields() != null) && (params.getFields().size() > 0)) { // no individual field queries have been defined, so use one query for all fields BooleanQuery booleanFieldsQuery = new BooleanQuery(); // this is a "regular" query over one or more fields // add one sub-query for each of the selected fields, e.g. "content", "title" etc. for (int i = 0; i < params.getFields().size(); i++) { QueryParser p = new QueryParser(LUCENE_VERSION, params.getFields().get(i), getAnalyzer()); booleanFieldsQuery.add(p.parse(params.getQuery()), BooleanClause.Occur.SHOULD); } fieldsQuery = searcher.rewrite(booleanFieldsQuery); } else { // if no fields are provided, just use the "content" field by default QueryParser p = new QueryParser(LUCENE_VERSION, CmsSearchField.FIELD_CONTENT, getAnalyzer()); fieldsQuery = searcher.rewrite(p.parse(params.getQuery())); } // finally set the main query to the fields query // please note that we still need both variables in case the query is a MatchAllDocsQuery - see below query = fieldsQuery; } if (LOG.isDebugEnabled()) { LOG.debug(Messages.get().getBundle().key(Messages.LOG_BASE_QUERY_1, query)); } if (query == null) { // if no text query is set, then we match all documents query = new MatchAllDocsQuery(); } else { // store the parsed query for page browsing params.setParsedQuery(query.toString(CmsSearchField.FIELD_CONTENT)); } // collect the categories CmsSearchCategoryCollector categoryCollector; if (params.isCalculateCategories()) { // USE THIS OPTION WITH CAUTION // this may slow down searched by an order of magnitude categoryCollector = new CmsSearchCategoryCollector(searcher); // perform a first search to collect the categories searcher.search(query, filter, categoryCollector); // store the result searchResults.setCategories(categoryCollector.getCategoryCountResult()); } // perform the search operation if ((params.getSort() == null) || (params.getSort() == CmsSearchParameters.SORT_DEFAULT)) { // apparently scoring is always enabled by Lucene if no sort order is provided hits = searcher.search(query, filter, m_maxHits); } else { // if a sort order is provided, we must check if scoring must be calculated by the searcher prepareSortScoring(searcher, params.getSort()); hits = searcher.search(query, filter, m_maxHits, params.getSort()); } timeLucene += System.currentTimeMillis(); timeResultProcessing = -System.currentTimeMillis(); Document doc; CmsSearchResult searchResult; if (hits != null) { int hitCount = hits.totalHits > hits.scoreDocs.length ? hits.scoreDocs.length : hits.totalHits; int page = params.getSearchPage(); int start = -1, end = -1; if ((params.getMatchesPerPage() > 0) && (page > 0) && (hitCount > 0)) { // calculate the final size of the search result start = params.getMatchesPerPage() * (page - 1); end = start + params.getMatchesPerPage(); // ensure that both i and n are inside the range of foundDocuments.size() start = (start > hitCount) ? hitCount : start; end = (end > hitCount) ? hitCount : end; } else { // return all found documents in the search result start = 0; end = hitCount; } int visibleHitCount = hitCount; for (int i = 0, cnt = 0; (i < hitCount) && (cnt < end); i++) { try { doc = searcher.doc(hits.scoreDocs[i].doc); if ((isInTimeRange(doc, params)) && (hasReadPermission(searchCms, doc))) { // user has read permission if (cnt >= start) { // do not use the resource to obtain the raw content, read it from the lucene document! String excerpt = null; if (isCreatingExcerpt() && (fieldsQuery != null)) { I_CmsTermHighlighter highlighter = OpenCms.getSearchManager().getHighlighter(); excerpt = highlighter.getExcerpt(doc, this, params, fieldsQuery, getAnalyzer()); } searchResult = new CmsSearchResult( Math.round((hits.scoreDocs[i].score / hits.getMaxScore()) * 100f), doc, excerpt); searchResults.add(searchResult); } cnt++; } else { visibleHitCount--; } } catch (Exception e) { // should not happen, but if it does we want to go on with the next result nevertheless if (LOG.isWarnEnabled()) { LOG.warn(Messages.get().getBundle().key(Messages.LOG_RESULT_ITERATION_FAILED_0), e); } } } // save the total count of search results searchResults.setHitCount(visibleHitCount); } else { searchResults.setHitCount(0); } timeResultProcessing += System.currentTimeMillis(); } catch (RuntimeException e) { throw new CmsSearchException(Messages.get().container(Messages.ERR_SEARCH_PARAMS_1, params), e); } catch (Exception e) { throw new CmsSearchException(Messages.get().container(Messages.ERR_SEARCH_PARAMS_1, params), e); } finally { // re-set thread to previous priority Thread.currentThread().setPriority(previousPriority); } if (LOG.isDebugEnabled()) { timeTotal += System.currentTimeMillis(); Object[] logParams = new Object[] { new Integer(hits == null ? 0 : hits.totalHits), new Long(timeTotal), new Long(timeLucene), new Long(timeResultProcessing) }; LOG.debug(Messages.get().getBundle().key(Messages.LOG_STAT_RESULTS_TIME_4, logParams)); } return searchResults; }
From source file:org.opencms.search.galleries.CmsGallerySearchIndex.java
License:Open Source License
/** * Performs a search on the gallery index.<p> * /*from w ww. jav a 2 s . co m*/ * @param cms the current users OpenCms context * @param params the parameters to use for the search * * @return the List of results found * * @throws CmsSearchException if something goes wrong */ public synchronized CmsGallerySearchResultList searchGallery(CmsObject cms, CmsGallerySearchParameters params) throws CmsSearchException { // the hits found during the search TopDocs hits; // storage for the results found CmsGallerySearchResultList searchResults = new CmsGallerySearchResultList(); try { // copy the user OpenCms context CmsObject searchCms = OpenCms.initCmsObject(cms); // make sure to keep the request time when evaluating resource expiration searchCms.getRequestContext().setRequestTime(cms.getRequestContext().getRequestTime()); // change the project searchCms.getRequestContext().setCurrentProject(searchCms.readProject(getProject())); // several search options are searched using filters BooleanFilter filter = new BooleanFilter(); // append root path filter List<String> folders = new ArrayList<String>(); if (params.getFolders() != null) { folders.addAll(params.getFolders()); } if (params.getGalleries() != null) { folders.addAll(params.getGalleries()); } filter = appendPathFilter(searchCms, filter, folders); String subsite = null; if (params.getReferencePath() != null) { subsite = OpenCms.getADEManager().getSubSiteRoot(cms, cms.getRequestContext().addSiteRoot(params.getReferencePath())); if (subsite != null) { subsite = cms.getRequestContext().removeSiteRoot(subsite); } } List<String> scopeFolders = getSearchRootsForScope(params.getScope(), subsite); filter = appendPathFilter(searchCms, filter, scopeFolders); // append category filter filter = appendCategoryFilter(searchCms, filter, params.getCategories()); // append container type filter filter = appendContainerTypeFilter(searchCms, filter, params.getContainerTypes()); // append resource type filter filter = appendResourceTypeFilter(searchCms, filter, params.getResourceTypes()); // append locale filter filter = appendLocaleFilter(searchCms, filter, params.getLocale()); // append date last modified filter filter = appendDateLastModifiedFilter(filter, params.getDateLastModifiedRange().getStartTime(), params.getDateLastModifiedRange().getEndTime()); // append date created filter filter = appendDateCreatedFilter(filter, params.getDateCreatedRange().getStartTime(), params.getDateCreatedRange().getEndTime()); // the search query to use, will be constructed in the next lines Query query = null; // store separate fields query for excerpt highlighting Query fieldsQuery = null; // get an index searcher that is certainly up to date indexSearcherUpdate(); IndexSearcher searcher = getSearcher(); Locale locale = params.getLocale() == null ? null : CmsLocaleManager.getLocale(params.getLocale()); if (params.getSearchWords() != null) { // this search contains a full text search component BooleanQuery booleanFieldsQuery = new BooleanQuery(); OpenCms.getLocaleManager(); // extend the field names with the locale information List<String> fields = params.getFields(); fields = getLocaleExtendedFields(params.getFields(), locale); // add one sub-query for each of the selected fields, e.g. "content", "title" etc. for (String field : fields) { QueryParser p = new QueryParser(CmsSearchIndex.LUCENE_VERSION, field, getAnalyzer()); booleanFieldsQuery.add(p.parse(params.getSearchWords()), BooleanClause.Occur.SHOULD); } fieldsQuery = searcher.rewrite(booleanFieldsQuery); } // finally set the main query to the fields query // please note that we still need both variables in case the query is a MatchAllDocsQuery - see below query = fieldsQuery; if (query == null) { // if no text query is set, then we match all documents query = new MatchAllDocsQuery(); } // perform the search operation searcher.setDefaultFieldSortScoring(true, true); hits = searcher.search(query, filter, getMaxHits(), params.getSort()); if (hits != null) { int hitCount = hits.totalHits > hits.scoreDocs.length ? hits.scoreDocs.length : hits.totalHits; int page = params.getResultPage(); int start = -1, end = -1; if ((params.getMatchesPerPage() > 0) && (page > 0) && (hitCount > 0)) { // calculate the final size of the search result start = params.getMatchesPerPage() * (page - 1); end = start + params.getMatchesPerPage(); // ensure that both i and n are inside the range of foundDocuments.size() start = (start > hitCount) ? hitCount : start; end = (end > hitCount) ? hitCount : end; } else { // return all found documents in the search result start = 0; end = hitCount; } Document doc; CmsGallerySearchResult searchResult; CmsSearchParameters searchParams = params.getCmsSearchParams(); int visibleHitCount = hitCount; for (int i = 0, cnt = 0; (i < hitCount) && (cnt < end); i++) { try { doc = searcher.doc(hits.scoreDocs[i].doc); if (hasReadPermission(searchCms, doc)) { // user has read permission if (cnt >= start) { // do not use the resource to obtain the raw content, read it from the lucene document! String excerpt = null; if (isCreatingExcerpt() && (fieldsQuery != null)) { I_CmsTermHighlighter highlighter = OpenCms.getSearchManager().getHighlighter(); excerpt = highlighter.getExcerpt(doc, this, searchParams, fieldsQuery, getAnalyzer()); } searchResult = new CmsGallerySearchResult( Math.round((hits.scoreDocs[i].score / hits.getMaxScore()) * 100f), doc, excerpt, locale); searchResults.add(searchResult); } cnt++; } else { visibleHitCount--; } } catch (Exception e) { // should not happen, but if it does we want to go on with the next result nevertheless if (LOG.isWarnEnabled()) { LOG.warn(Messages.get().getBundle().key(Messages.LOG_RESULT_ITERATION_FAILED_0), e); } } } // save the total count of search results searchResults.setHitCount(visibleHitCount); } else { searchResults.setHitCount(0); } } catch (RuntimeException e) { throw new CmsSearchException(Messages.get().container(Messages.ERR_SEARCH_PARAMS_1, params), e); } catch (Exception e) { throw new CmsSearchException(Messages.get().container(Messages.ERR_SEARCH_PARAMS_1, params), e); } return searchResults; }
From source file:org.riotfamily.search.ResultHighlighter.java
License:Apache License
public HighlightingContext createContext(IndexSearcher indexSearcher, Query query) throws IOException { Scorer scorer = new QueryScorer(indexSearcher.rewrite(query)); if (formatter == null) { formatter = new SimpleHTMLFormatter("<" + highlightPreTag + ">", "</" + highlightPostTag + ">"); }// www . jav a2s .c om if (fragmenter == null) { fragmenter = new SimpleFragmenter(fragmentSize); } Highlighter highlighter = new Highlighter(formatter, encoder, scorer); highlighter.setTextFragmenter(fragmenter); return new HighlightingContext(highlighter); }
From source file:org.sindice.siren.search.TestSirenWildcardQuery.java
License:Open Source License
/** * Tests if the ConstantScore filter rewrite return an exception *//* w w w . ja v a2 s. c o m*/ @Test(expected = UnsupportedOperationException.class) public void testFilterRewrite() throws IOException { final Directory indexStore = this.getIndexStore("field", new String[] { "nowildcard", "nowildcardx" }); final IndexSearcher searcher = new IndexSearcher(indexStore, true); final SirenMultiTermQuery wq = new SirenWildcardQuery(new Term("field", "nowildcard")); this.assertMatches(searcher, wq, 1); try { wq.setRewriteMethod(SirenMultiTermQuery.CONSTANT_SCORE_FILTER_REWRITE); wq.setBoost(0.2F); final Query q = searcher.rewrite(wq); assertTrue(q instanceof SirenConstantScoreQuery); assertEquals(q.getBoost(), wq.getBoost()); } finally { searcher.close(); indexStore.close(); } }
From source file:org.sindice.siren.search.TestSirenWildcardQuery.java
License:Open Source License
/** * Tests if a WildcardQuery that has no wildcard in the term is rewritten to a single * TermQuery. The boost should be preserved, and the rewrite should return * a ConstantScoreQuery if the WildcardQuery had a ConstantScore rewriteMethod. *//*from w w w.j a v a2 s .co m*/ public void testTermWithoutWildcard2() throws IOException { final Directory indexStore = this.getIndexStore("field", new String[] { "nowildcard", "nowildcardx" }); final IndexSearcher searcher = new IndexSearcher(indexStore, true); final MultiTermQuery wq = new WildcardQuery(new Term("field", "nowildcard")); this.assertMatches(searcher, wq, 1); wq.setRewriteMethod(MultiTermQuery.SCORING_BOOLEAN_QUERY_REWRITE); wq.setBoost(0.1F); final Query q = searcher.rewrite(wq); assertTrue(q instanceof TermQuery); assertEquals(q.getBoost(), wq.getBoost()); searcher.close(); indexStore.close(); }
From source file:org.sindice.siren.search.TestSirenWildcardQuery.java
License:Open Source License
/** * Tests if a SirenWildcardQuery that has no wildcard in the term is rewritten to a single * TermQuery. The boost should be preserved, and the rewrite should return * a SirenConstantScoreQuery if the SirenWildcardQuery had a ConstantScore rewriteMethod. *//*from w w w . j a v a 2 s . co m*/ public void testTermWithoutWildcard() throws IOException { final Directory indexStore = this.getIndexStore("field", new String[] { "nowildcard", "nowildcardx" }); final IndexSearcher searcher = new IndexSearcher(indexStore, true); final SirenMultiTermQuery wq = new SirenWildcardQuery(new Term("field", "nowildcard")); this.assertMatches(searcher, wq, 1); wq.setRewriteMethod(SirenMultiTermQuery.SCORING_BOOLEAN_QUERY_REWRITE); wq.setBoost(0.1F); Query q = searcher.rewrite(wq); assertTrue(q instanceof SirenTermQuery); assertEquals(q.getBoost(), wq.getBoost()); wq.setRewriteMethod(SirenMultiTermQuery.CONSTANT_SCORE_AUTO_REWRITE_DEFAULT); wq.setBoost(0.3F); q = searcher.rewrite(wq); assertTrue(q instanceof SirenConstantScoreQuery); assertEquals(q.getBoost(), wq.getBoost()); wq.setRewriteMethod(SirenMultiTermQuery.CONSTANT_SCORE_BOOLEAN_QUERY_REWRITE); wq.setBoost(0.4F); q = searcher.rewrite(wq); assertTrue(q instanceof SirenConstantScoreQuery); assertEquals(q.getBoost(), wq.getBoost()); searcher.close(); indexStore.close(); }
From source file:org.sindice.siren.search.TestSirenWildcardQuery.java
License:Open Source License
/** * Tests if a SirenWildcardQuery with an empty term is rewritten to an empty * SirenBooleanQuery//from w w w . j a v a 2 s. co m */ public void testEmptyTerm() throws IOException { final Directory indexStore = this.getIndexStore("field", new String[] { "nowildcard", "nowildcardx" }); final IndexSearcher searcher = new IndexSearcher(indexStore, true); final SirenMultiTermQuery wq = new SirenWildcardQuery(new Term("field", "")); wq.setRewriteMethod(SirenMultiTermQuery.SCORING_BOOLEAN_QUERY_REWRITE); this.assertMatches(searcher, wq, 0); final Query q = searcher.rewrite(wq); assertTrue(q instanceof SirenBooleanQuery); assertEquals(0, ((SirenBooleanQuery) q).clauses().size()); searcher.close(); indexStore.close(); }