/** * Tries to extract a segment reader from the given index reader. * If no SegmentReader can be extracted an {@link IllegalStateException} is thrown. */ protected static SegmentReader segmentReader(LeafReader reader) { if (reader instanceof SegmentReader) { return (SegmentReader) reader; } else if (reader instanceof FilterLeafReader) { final FilterLeafReader fReader = (FilterLeafReader) reader; return segmentReader(FilterLeafReader.unwrap(fReader)); } // hard fail - we can't get a SegmentReader throw new IllegalStateException("Can not extract segment reader from given index reader [" + reader + "]"); }
public static ElasticsearchLeafReader getElasticsearchLeafReader(LeafReader reader) { if (reader instanceof FilterLeafReader) { if (reader instanceof ElasticsearchLeafReader) { return (ElasticsearchLeafReader) reader; } else { // We need to use FilterLeafReader#getDelegate and not FilterLeafReader#unwrap, because // If there are multiple levels of filtered leaf readers then with the unwrap() method it immediately // returns the most inner leaf reader and thus skipping of over any other filtered leaf reader that // may be instance of ElasticsearchLeafReader. This can cause us to miss the shardId. return getElasticsearchLeafReader(((FilterLeafReader) reader).getDelegate()); } } return null; }
/** * Expert: creates a searcher from the provided {@link IndexReader} using the provided {@link * SearcherFactory}. NOTE: this decRefs incoming reader on throwing an exception. */ @SuppressWarnings("resource") public static IndexSearcher getSearcher(SearcherFactory searcherFactory, IndexReader reader) throws IOException { boolean success = false; final IndexSearcher searcher; try { searcher = searcherFactory.newSearcher(reader, null); // Modification for Gerrit: Allow searcherFactory to transitively wrap the // provided reader. IndexReader unwrapped = searcher.getIndexReader(); while (true) { if (unwrapped == reader) { break; } else if (unwrapped instanceof FilterDirectoryReader) { unwrapped = ((FilterDirectoryReader) unwrapped).getDelegate(); } else if (unwrapped instanceof FilterLeafReader) { unwrapped = ((FilterLeafReader) unwrapped).getDelegate(); } else { break; } } if (unwrapped != reader) { throw new IllegalStateException( "SearcherFactory must wrap the provided reader (got " + searcher.getIndexReader() + " but expected " + reader + ")"); } success = true; } finally { if (!success) { reader.decRef(); } } return searcher; }