org.apache.lucene.search.Searcher Java Examples

The following examples show how to use org.apache.lucene.search.Searcher. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: LuceneContent.java    From Lottery with GNU General Public License v2.0 6 votes vote down vote up
public static List<Integer> getResultList(Searcher searcher, TopDocs docs,
		int first, int max) throws CorruptIndexException, IOException {
	List<Integer> list = new ArrayList<Integer>(max);
	ScoreDoc[] hits = docs.scoreDocs;
	if (first < 0) {
		first = 0;
	}
	if (max < 0) {
		max = 0;
	}
	int last = first + max;
	int len = hits.length;
	if (last > len) {
		last = len;
	}
	for (int i = first; i < last; i++) {
		Document d = searcher.doc(hits[i].doc);
		list.add(Integer.valueOf(d.getField(ID).stringValue()));
	}
	return list;
}
 
Example #2
Source File: LuceneContentSvcImpl.java    From Lottery with GNU General Public License v2.0 6 votes vote down vote up
@Transactional(readOnly = true)
public Pagination searchPage(Directory dir, String queryString,String category,String workplace,
		Integer siteId, Integer channelId, Date startDate, Date endDate,
		int pageNo, int pageSize) throws CorruptIndexException,
		IOException, ParseException {
	Searcher searcher = new IndexSearcher(dir);
	try {
		Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_30);
		Query query = LuceneContent.createQuery(queryString,category,workplace, siteId,
				channelId, startDate, endDate, analyzer);
		TopDocs docs = searcher.search(query, pageNo * pageSize);
		Pagination p = LuceneContent.getResultPage(searcher, docs, pageNo,
				pageSize);
		List<?> ids = p.getList();
		List<Content> contents = new ArrayList<Content>(ids.size());
		for (Object id : ids) {
			contents.add(contentMng.findById((Integer) id));
		}
		p.setList(contents);
		return p;
	} finally {
		searcher.close();
	}
}
 
Example #3
Source File: LuceneResultSet.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Wrap a lucene seach result with node support
 * 
 * @param hits Hits
 * @param searcher Searcher
 * @param nodeService nodeService
 * @param tenantService tenant service
 * @param searchParameters SearchParameters
 * @param config - lucene config
 */
public LuceneResultSet(Hits hits, Searcher searcher, NodeService nodeService, TenantService tenantService, SearchParameters searchParameters,
        LuceneConfig config)
{
    super();
    this.hits = hits;
    this.searcher = searcher;
    this.nodeService = nodeService;
    this.tenantService = tenantService;
    this.searchParameters = searchParameters;
    this.config = config;
    prefetch = new BitSet(hits.length());
}
 
Example #4
Source File: SearchResultsImpl.java    From olat with Apache License 2.0 5 votes vote down vote up
private List<ResultDocument> initResultList(final Identity identity, final Roles roles, final Query query, final Analyzer analyzer, final Searcher searcher,
        final TopDocs docs, final int firstResult, final int maxReturns, final boolean doHighlight) throws IOException {
    final FieldSelector selector = new FieldSelector() {
        @Override
        public FieldSelectorResult accept(final String fieldName) {
            return (doHighlight || !AbstractOlatDocument.CONTENT_FIELD_NAME.equals(fieldName)) ? FieldSelectorResult.LOAD : FieldSelectorResult.NO_LOAD;
        }
    };

    maxHits = SearchServiceFactory.getService().getSearchModuleConfig().getMaxHits();
    totalHits = docs.totalHits;
    totalDocs = (docs.scoreDocs == null ? 0 : docs.scoreDocs.length);
    final int numOfDocs = Math.min(maxHits, docs.totalHits);
    final List<ResultDocument> res = new ArrayList<ResultDocument>(maxReturns + 1);
    for (int i = firstResult; i < numOfDocs && res.size() < maxReturns; i++) {
        final Document doc = searcher.doc(docs.scoreDocs[i].doc, selector);
        final String reservedTo = doc.get(AbstractOlatDocument.RESERVED_TO);
        if (StringHelper.containsNonWhitespace(reservedTo) && !"public".equals(reservedTo) && !reservedTo.contains(identity.getKey().toString())) {
            continue;// admin cannot see private documents
        }

        final ResultDocument rDoc = createResultDocument(doc, i, query, analyzer, doHighlight, identity, roles);
        if (rDoc != null) {
            res.add(rDoc);
        }

        if (!roles.isOLATAdmin() && i % 10 == 0) {
            // Do commit after certain number of documents because the transaction should not be too big
            DBFactory.getInstance().intermediateCommit();
        }
    }
    return res;
}
 
Example #5
Source File: SearchResultsImpl.java    From olat with Apache License 2.0 5 votes vote down vote up
private List<ResultDocument> initResultList(final Identity identity, final Roles roles, final Query query, final Analyzer analyzer, final Searcher searcher,
        final TopDocs docs, final int firstResult, final int maxReturns, final boolean doHighlight) throws IOException {
    final FieldSelector selector = new FieldSelector() {
        @Override
        public FieldSelectorResult accept(final String fieldName) {
            return (doHighlight || !AbstractOlatDocument.CONTENT_FIELD_NAME.equals(fieldName)) ? FieldSelectorResult.LOAD : FieldSelectorResult.NO_LOAD;
        }
    };

    maxHits = SearchServiceFactory.getService().getSearchModuleConfig().getMaxHits();
    totalHits = docs.totalHits;
    totalDocs = (docs.scoreDocs == null ? 0 : docs.scoreDocs.length);
    final int numOfDocs = Math.min(maxHits, docs.totalHits);
    final List<ResultDocument> res = new ArrayList<ResultDocument>(maxReturns + 1);
    for (int i = firstResult; i < numOfDocs && res.size() < maxReturns; i++) {
        final Document doc = searcher.doc(docs.scoreDocs[i].doc, selector);
        final String reservedTo = doc.get(AbstractOlatDocument.RESERVED_TO);
        if (StringHelper.containsNonWhitespace(reservedTo) && !"public".equals(reservedTo) && !reservedTo.contains(identity.getKey().toString())) {
            continue;// admin cannot see private documents
        }

        final ResultDocument rDoc = createResultDocument(doc, i, query, analyzer, doHighlight, identity, roles);
        if (rDoc != null) {
            res.add(rDoc);
        }

        if (!roles.isOLATAdmin() && i % 10 == 0) {
            // Do commit after certain number of documents because the transaction should not be too big
            DBFactory.getInstance().intermediateCommit();
        }
    }
    return res;
}
 
Example #6
Source File: LuceneContent.java    From Lottery with GNU General Public License v2.0 5 votes vote down vote up
public static Pagination getResultPage(Searcher searcher, TopDocs docs,
		int pageNo, int pageSize) throws CorruptIndexException, IOException {
	List<Integer> list = new ArrayList<Integer>(pageSize);
	ScoreDoc[] hits = docs.scoreDocs;
	int endIndex = pageNo * pageSize;
	int len = hits.length;
	if (endIndex > len) {
		endIndex = len;
	}
	for (int i = (pageNo - 1) * pageSize; i < endIndex; i++) {
		Document d = searcher.doc(hits[i].doc);
		list.add(Integer.valueOf(d.getField(ID).stringValue()));
	}
	return new Pagination(pageNo, pageSize, docs.totalHits, list);
}
 
Example #7
Source File: LuceneContentSvcImpl.java    From Lottery with GNU General Public License v2.0 5 votes vote down vote up
@Transactional(readOnly = true)
public List<Content> searchList(Directory dir, String queryString,String category,String workplace,
		Integer siteId, Integer channelId, Date startDate, Date endDate,
		int first, int max) throws CorruptIndexException, IOException,
		ParseException {
	Searcher searcher = new IndexSearcher(dir);
	try {
		Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_30);
		Query query = LuceneContent.createQuery(queryString,category,workplace, siteId,
				channelId, startDate, endDate, analyzer);
		if (first < 0) {
			first = 0;
		}
		if (max < 0) {
			max = 0;
		}
		TopDocs docs = searcher.search(query, first + max);
		List<Integer> ids = LuceneContent.getResultList(searcher, docs,
				first, max);
		List<Content> contents = new ArrayList<Content>(ids.size());
		for (Object id : ids) {
			contents.add(contentMng.findById((Integer) id));
		}
		return contents;
	} finally {
		searcher.close();
	}
}
 
Example #8
Source File: MemoryIndex.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
public <T> void query(
        @NonNull Collection<? super T> result,
        @NonNull Convertor<? super Document, T> convertor,
        @NullAllowed FieldSelector selector,
        @NullAllowed AtomicBoolean cancel,
        @NonNull Query... queries) throws IOException, InterruptedException {
    Parameters.notNull("queries", queries);   //NOI18N
    Parameters.notNull("convertor", convertor); //NOI18N
    Parameters.notNull("result", result);       //NOI18N   
    
    if (selector == null) {
        selector = AllFieldsSelector.INSTANCE;
    }
    
    lock.readLock().lock();
    try {
        final IndexReader in = getReader();
        if (in == null) {
            return;
        }
        final BitSet bs = new BitSet(in.maxDoc());
        final Collector c = new BitSetCollector(bs);
        final Searcher searcher = new IndexSearcher(in);
        try {
            for (Query q : queries) {
                if (cancel != null && cancel.get()) {
                    throw new InterruptedException ();
                }
                searcher.search(q, c);
            }
        } finally {
            searcher.close();
        }        
        for (int docNum = bs.nextSetBit(0); docNum >= 0; docNum = bs.nextSetBit(docNum+1)) {
            if (cancel != null && cancel.get()) {
                throw new InterruptedException ();
            }
            final Document doc = in.document(docNum, selector);
            final T value = convertor.convert(doc);
            if (value != null) {
                result.add (value);
            }
        }
    } finally {
        lock.readLock().unlock();
    }
}
 
Example #9
Source File: MemoryIndex.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
public <S, T> void queryDocTerms(
        @NonNull Map<? super T, Set<S>> result,
        @NonNull Convertor<? super Document, T> convertor,
        @NonNull Convertor<? super Term, S> termConvertor,
        @NullAllowed FieldSelector selector,
        @NullAllowed AtomicBoolean cancel,
        @NonNull Query... queries) throws IOException, InterruptedException {
    Parameters.notNull("result", result);   //NOI18N
    Parameters.notNull("convertor", convertor);   //NOI18N
    Parameters.notNull("termConvertor", termConvertor); //NOI18N
    Parameters.notNull("queries", queries);   //NOI18N
    
    
    if (selector == null) {
        selector = AllFieldsSelector.INSTANCE;
    }

    lock.readLock().lock();
    try {
        final IndexReader in = getReader();
        if (in == null) {
            return;
        }
        final BitSet bs = new BitSet(in.maxDoc());
        final Collector c = new BitSetCollector(bs);
        final Searcher searcher = new IndexSearcher(in);
        final TermCollector termCollector = new TermCollector(c);
        try {
            for (Query q : queries) {
                if (cancel != null && cancel.get()) {
                    throw new InterruptedException ();
                }
                if (q instanceof TermCollector.TermCollecting) {
                    ((TermCollector.TermCollecting)q).attach(termCollector);
                } else {
                    throw new IllegalArgumentException (
                            String.format("Query: %s does not implement TermCollecting",    //NOI18N
                            q.getClass().getName()));
                }
                searcher.search(q, termCollector);
            }
        } finally {
            searcher.close();
        }

        for (int docNum = bs.nextSetBit(0); docNum >= 0; docNum = bs.nextSetBit(docNum+1)) {
            if (cancel != null && cancel.get()) {
                throw new InterruptedException ();
            }
            final Document doc = in.document(docNum, selector);
            final T value = convertor.convert(doc);
            if (value != null) {
                final Set<Term> terms = termCollector.get(docNum);
                if (terms != null) {
                    result.put (value, convertTerms(termConvertor, terms));
                }
            }
        }
    } finally {
        lock.readLock().unlock();
    }
}
 
Example #10
Source File: SearchService.java    From subsonic with GNU General Public License v3.0 4 votes vote down vote up
public SearchResult search(SearchCriteria criteria, List<MusicFolder> musicFolders, IndexType indexType) {
    SearchResult result = new SearchResult();
    int offset = criteria.getOffset();
    int count = criteria.getCount();
    result.setOffset(offset);

    IndexReader reader = null;
    try {
        reader = createIndexReader(indexType);
        Searcher searcher = new IndexSearcher(reader);
        Analyzer analyzer = new SubsonicAnalyzer();

        MultiFieldQueryParser queryParser = new MultiFieldQueryParser(LUCENE_VERSION, indexType.getFields(), analyzer, indexType.getBoosts());

        BooleanQuery query = new BooleanQuery();
        query.add(queryParser.parse(analyzeQuery(criteria.getQuery())), BooleanClause.Occur.MUST);

        List<SpanTermQuery> musicFolderQueries = new ArrayList<SpanTermQuery>();
        for (MusicFolder musicFolder : musicFolders) {
            if (indexType == ALBUM_ID3 || indexType == ARTIST_ID3) {
                musicFolderQueries.add(new SpanTermQuery(new Term(FIELD_FOLDER_ID, NumericUtils.intToPrefixCoded(musicFolder.getId()))));
            } else {
                musicFolderQueries.add(new SpanTermQuery(new Term(FIELD_FOLDER, musicFolder.getPath().getPath())));
            }
        }
        query.add(new SpanOrQuery(musicFolderQueries.toArray(new SpanQuery[musicFolderQueries.size()])), BooleanClause.Occur.MUST);

        TopDocs topDocs = searcher.search(query, null, offset + count);
        result.setTotalHits(topDocs.totalHits);

        int start = Math.min(offset, topDocs.totalHits);
        int end = Math.min(start + count, topDocs.totalHits);
        for (int i = start; i < end; i++) {
            Document doc = searcher.doc(topDocs.scoreDocs[i].doc);
            switch (indexType) {
                case SONG:
                case ARTIST:
                case ALBUM:
                    MediaFile mediaFile = mediaFileService.getMediaFile(Integer.valueOf(doc.get(FIELD_ID)));
                    addIfNotNull(mediaFile, result.getMediaFiles());
                    break;
                case ARTIST_ID3:
                    Artist artist = artistDao.getArtist(Integer.valueOf(doc.get(FIELD_ID)));
                    addIfNotNull(artist, result.getArtists());
                    break;
                case ALBUM_ID3:
                    Album album = albumDao.getAlbum(Integer.valueOf(doc.get(FIELD_ID)));
                    addIfNotNull(album, result.getAlbums());
                    break;
                default:
                    break;
            }
        }

    } catch (Throwable x) {
        LOG.error("Failed to execute Lucene search.", x);
    } finally {
        FileUtil.closeQuietly(reader);
    }
    return result;
}
 
Example #11
Source File: SearchResultsImpl.java    From olat with Apache License 2.0 2 votes vote down vote up
/**
 * Constructure for certain search-results. Does not include any search-call to search-service. Search call must be made before to create a Hits object.
 * 
 * @param hits
 *            Search hits return from search.
 * @param query
 *            Search query-string.
 * @param analyzer
 *            Search analyser, must be the same like at creation of index.
 * @param identity
 *            Filter results for this identity (user).
 * @param roles
 *            Filter results for this roles (role of user).
 * @param doHighlighting
 *            Flag to enable highlighting search
 * @throws IOException
 */
public SearchResultsImpl(final Indexer mainIndexer, final Searcher searcher, final TopDocs docs, final Query query, final Analyzer analyzer, final Identity identity,
        final Roles roles, final int firstResult, final int maxReturns, final boolean doHighlighting) throws IOException {
    this.mainIndexer = mainIndexer;
    resultList = initResultList(identity, roles, query, analyzer, searcher, docs, firstResult, maxReturns, doHighlighting);
}
 
Example #12
Source File: SearchResultsImpl.java    From olat with Apache License 2.0 2 votes vote down vote up
/**
 * Constructure for certain search-results. Does not include any search-call to search-service. Search call must be made before to create a Hits object.
 * 
 * @param hits
 *            Search hits return from search.
 * @param query
 *            Search query-string.
 * @param analyzer
 *            Search analyser, must be the same like at creation of index.
 * @param identity
 *            Filter results for this identity (user).
 * @param roles
 *            Filter results for this roles (role of user).
 * @param doHighlighting
 *            Flag to enable highlighting search
 * @throws IOException
 */
public SearchResultsImpl(final MainIndexer mainIndexer, final Searcher searcher, final TopDocs docs, final Query query, final Analyzer analyzer,
        final Identity identity, final Roles roles, final int firstResult, final int maxReturns, final boolean doHighlighting) throws IOException {
    this.mainIndexer = mainIndexer;
    resultList = initResultList(identity, roles, query, analyzer, searcher, docs, firstResult, maxReturns, doHighlighting);
}