Search in sources :

Example 1 with MatchesIterator

use of org.apache.lucene.search.MatchesIterator in project OpenGrok by OpenGrok.

the class SearchHelper method maybeRedirectToMatchOffset.

private void maybeRedirectToMatchOffset(int docID, List<String> contextFields) throws IOException {
    /*
         * Only PLAIN files might redirect to a file offset, since an offset
         * must be subsequently converted to a line number and that is tractable
         * only from plain text.
         */
    Document doc = searcher.doc(docID);
    String genre = doc.get(QueryBuilder.T);
    if (!AbstractAnalyzer.Genre.PLAIN.typeName().equals(genre)) {
        return;
    }
    List<LeafReaderContext> leaves = reader.leaves();
    int subIndex = ReaderUtil.subIndex(docID, leaves);
    LeafReaderContext leaf = leaves.get(subIndex);
    Query rewritten = query.rewrite(reader);
    Weight weight = rewritten.createWeight(searcher, ScoreMode.COMPLETE_NO_SCORES, 1);
    // Adjust docID
    Matches matches = weight.matches(leaf, docID - leaf.docBase);
    if (matches != null && matches != MatchesUtils.MATCH_WITH_NO_TERMS) {
        int matchCount = 0;
        int offset = -1;
        for (String field : contextFields) {
            MatchesIterator matchesIterator = matches.getMatches(field);
            while (matchesIterator.next()) {
                if (matchesIterator.startOffset() >= 0) {
                    // Abort if there is more than a single match offset.
                    if (++matchCount > 1) {
                        return;
                    }
                    offset = matchesIterator.startOffset();
                }
            }
        }
        if (offset >= 0) {
            redirect = contextPath + Prefix.XREF_P + Util.uriEncodePath(doc.get(QueryBuilder.PATH)) + '?' + QueryParameters.MATCH_OFFSET_PARAM_EQ + offset;
        }
    }
}
Also used : MatchesIterator(org.apache.lucene.search.MatchesIterator) Query(org.apache.lucene.search.Query) TermQuery(org.apache.lucene.search.TermQuery) Matches(org.apache.lucene.search.Matches) LeafReaderContext(org.apache.lucene.index.LeafReaderContext) Document(org.apache.lucene.document.Document) Weight(org.apache.lucene.search.Weight)

Aggregations

Document (org.apache.lucene.document.Document)1 LeafReaderContext (org.apache.lucene.index.LeafReaderContext)1 Matches (org.apache.lucene.search.Matches)1 MatchesIterator (org.apache.lucene.search.MatchesIterator)1 Query (org.apache.lucene.search.Query)1 TermQuery (org.apache.lucene.search.TermQuery)1 Weight (org.apache.lucene.search.Weight)1