Example usage for org.apache.lucene.search IndexSearcher setQueryCache

List of usage examples for org.apache.lucene.search IndexSearcher setQueryCache

Introduction

In this page you can find the example usage for org.apache.lucene.search IndexSearcher setQueryCache.

Prototype

public void setQueryCache(QueryCache queryCache) 

Source Link

Document

Set the QueryCache to use when scores are not needed.

Usage

From source file:org.elasticsearch.indices.cache.query.IndicesQueryCacheTests.java

License:Apache License

public void testStatsOnEviction() throws IOException {
    Directory dir1 = newDirectory();// w  w  w . j a  v  a 2  s.  com
    IndexWriter w1 = new IndexWriter(dir1, newIndexWriterConfig());
    w1.addDocument(new Document());
    DirectoryReader r1 = DirectoryReader.open(w1, false);
    w1.close();
    ShardId shard1 = new ShardId(new Index("index"), 0);
    r1 = ElasticsearchDirectoryReader.wrap(r1, shard1);
    IndexSearcher s1 = new IndexSearcher(r1);
    s1.setQueryCachingPolicy(QueryCachingPolicy.ALWAYS_CACHE);

    Directory dir2 = newDirectory();
    IndexWriter w2 = new IndexWriter(dir2, newIndexWriterConfig());
    w2.addDocument(new Document());
    DirectoryReader r2 = DirectoryReader.open(w2, false);
    w2.close();
    ShardId shard2 = new ShardId(new Index("index"), 1);
    r2 = ElasticsearchDirectoryReader.wrap(r2, shard2);
    IndexSearcher s2 = new IndexSearcher(r2);
    s2.setQueryCachingPolicy(QueryCachingPolicy.ALWAYS_CACHE);

    Settings settings = Settings.builder().put(IndicesQueryCache.INDICES_CACHE_QUERY_COUNT, 10).build();
    IndicesQueryCache cache = new IndicesQueryCache(settings);
    s1.setQueryCache(cache);
    s2.setQueryCache(cache);

    assertEquals(1, s1.count(new DummyQuery(0)));

    for (int i = 1; i <= 20; ++i) {
        assertEquals(1, s2.count(new DummyQuery(i)));
    }

    QueryCacheStats stats1 = cache.getStats(shard1);
    assertEquals(0L, stats1.getCacheSize());
    assertEquals(1L, stats1.getCacheCount());

    // this used to fail because we were evicting an empty cache on
    // the segment from r1
    IOUtils.close(r1, dir1);
    cache.onClose(shard1);

    IOUtils.close(r2, dir2);
    cache.onClose(shard2);

    cache.close(); // this triggers some assertions
}

From source file:org.elasticsearch.indices.IndicesQueryCacheTests.java

License:Apache License

public void testBasics() throws IOException {
    Directory dir = newDirectory();/* ww  w . ja  v a  2 s  .  c om*/
    IndexWriter w = new IndexWriter(dir, newIndexWriterConfig());
    w.addDocument(new Document());
    DirectoryReader r = DirectoryReader.open(w);
    w.close();
    ShardId shard = new ShardId("index", "_na_", 0);
    r = ElasticsearchDirectoryReader.wrap(r, shard);
    IndexSearcher s = new IndexSearcher(r);
    s.setQueryCachingPolicy(QueryCachingPolicy.ALWAYS_CACHE);

    Settings settings = Settings.builder().put(IndicesQueryCache.INDICES_CACHE_QUERY_COUNT_SETTING.getKey(), 10)
            .put(IndicesQueryCache.INDICES_QUERIES_CACHE_ALL_SEGMENTS_SETTING.getKey(), true).build();
    IndicesQueryCache cache = new IndicesQueryCache(settings);
    s.setQueryCache(cache);

    QueryCacheStats stats = cache.getStats(shard);
    assertEquals(0L, stats.getCacheSize());
    assertEquals(0L, stats.getCacheCount());
    assertEquals(0L, stats.getHitCount());
    assertEquals(0L, stats.getMissCount());

    assertEquals(1, s.count(new DummyQuery(0)));

    stats = cache.getStats(shard);
    assertEquals(1L, stats.getCacheSize());
    assertEquals(1L, stats.getCacheCount());
    assertEquals(0L, stats.getHitCount());
    assertEquals(1L, stats.getMissCount());

    for (int i = 1; i < 20; ++i) {
        assertEquals(1, s.count(new DummyQuery(i)));
    }

    stats = cache.getStats(shard);
    assertEquals(10L, stats.getCacheSize());
    assertEquals(20L, stats.getCacheCount());
    assertEquals(0L, stats.getHitCount());
    assertEquals(20L, stats.getMissCount());

    s.count(new DummyQuery(10));

    stats = cache.getStats(shard);
    assertEquals(10L, stats.getCacheSize());
    assertEquals(20L, stats.getCacheCount());
    assertEquals(1L, stats.getHitCount());
    assertEquals(20L, stats.getMissCount());

    IOUtils.close(r, dir);

    // got emptied, but no changes to other metrics
    stats = cache.getStats(shard);
    assertEquals(0L, stats.getCacheSize());
    assertEquals(20L, stats.getCacheCount());
    assertEquals(1L, stats.getHitCount());
    assertEquals(20L, stats.getMissCount());

    cache.onClose(shard);

    // forgot everything
    stats = cache.getStats(shard);
    assertEquals(0L, stats.getCacheSize());
    assertEquals(0L, stats.getCacheCount());
    assertEquals(0L, stats.getHitCount());
    assertEquals(0L, stats.getMissCount());

    cache.close(); // this triggers some assertions
}

From source file:org.elasticsearch.indices.IndicesQueryCacheTests.java

License:Apache License

public void testTwoShards() throws IOException {
    Directory dir1 = newDirectory();/*ww  w.ja  v  a 2  s  .com*/
    IndexWriter w1 = new IndexWriter(dir1, newIndexWriterConfig());
    w1.addDocument(new Document());
    DirectoryReader r1 = DirectoryReader.open(w1);
    w1.close();
    ShardId shard1 = new ShardId("index", "_na_", 0);
    r1 = ElasticsearchDirectoryReader.wrap(r1, shard1);
    IndexSearcher s1 = new IndexSearcher(r1);
    s1.setQueryCachingPolicy(QueryCachingPolicy.ALWAYS_CACHE);

    Directory dir2 = newDirectory();
    IndexWriter w2 = new IndexWriter(dir2, newIndexWriterConfig());
    w2.addDocument(new Document());
    DirectoryReader r2 = DirectoryReader.open(w2);
    w2.close();
    ShardId shard2 = new ShardId("index", "_na_", 1);
    r2 = ElasticsearchDirectoryReader.wrap(r2, shard2);
    IndexSearcher s2 = new IndexSearcher(r2);
    s2.setQueryCachingPolicy(QueryCachingPolicy.ALWAYS_CACHE);

    Settings settings = Settings.builder().put(IndicesQueryCache.INDICES_CACHE_QUERY_COUNT_SETTING.getKey(), 10)
            .put(IndicesQueryCache.INDICES_QUERIES_CACHE_ALL_SEGMENTS_SETTING.getKey(), true).build();
    IndicesQueryCache cache = new IndicesQueryCache(settings);
    s1.setQueryCache(cache);
    s2.setQueryCache(cache);

    assertEquals(1, s1.count(new DummyQuery(0)));

    QueryCacheStats stats1 = cache.getStats(shard1);
    assertEquals(1L, stats1.getCacheSize());
    assertEquals(1L, stats1.getCacheCount());
    assertEquals(0L, stats1.getHitCount());
    assertEquals(1L, stats1.getMissCount());

    QueryCacheStats stats2 = cache.getStats(shard2);
    assertEquals(0L, stats2.getCacheSize());
    assertEquals(0L, stats2.getCacheCount());
    assertEquals(0L, stats2.getHitCount());
    assertEquals(0L, stats2.getMissCount());

    assertEquals(1, s2.count(new DummyQuery(0)));

    stats1 = cache.getStats(shard1);
    assertEquals(1L, stats1.getCacheSize());
    assertEquals(1L, stats1.getCacheCount());
    assertEquals(0L, stats1.getHitCount());
    assertEquals(1L, stats1.getMissCount());

    stats2 = cache.getStats(shard2);
    assertEquals(1L, stats2.getCacheSize());
    assertEquals(1L, stats2.getCacheCount());
    assertEquals(0L, stats2.getHitCount());
    assertEquals(1L, stats2.getMissCount());

    for (int i = 0; i < 20; ++i) {
        assertEquals(1, s2.count(new DummyQuery(i)));
    }

    stats1 = cache.getStats(shard1);
    assertEquals(0L, stats1.getCacheSize()); // evicted
    assertEquals(1L, stats1.getCacheCount());
    assertEquals(0L, stats1.getHitCount());
    assertEquals(1L, stats1.getMissCount());

    stats2 = cache.getStats(shard2);
    assertEquals(10L, stats2.getCacheSize());
    assertEquals(20L, stats2.getCacheCount());
    assertEquals(1L, stats2.getHitCount());
    assertEquals(20L, stats2.getMissCount());

    IOUtils.close(r1, dir1);

    // no changes
    stats1 = cache.getStats(shard1);
    assertEquals(0L, stats1.getCacheSize());
    assertEquals(1L, stats1.getCacheCount());
    assertEquals(0L, stats1.getHitCount());
    assertEquals(1L, stats1.getMissCount());

    stats2 = cache.getStats(shard2);
    assertEquals(10L, stats2.getCacheSize());
    assertEquals(20L, stats2.getCacheCount());
    assertEquals(1L, stats2.getHitCount());
    assertEquals(20L, stats2.getMissCount());

    cache.onClose(shard1);

    // forgot everything about shard1
    stats1 = cache.getStats(shard1);
    assertEquals(0L, stats1.getCacheSize());
    assertEquals(0L, stats1.getCacheCount());
    assertEquals(0L, stats1.getHitCount());
    assertEquals(0L, stats1.getMissCount());

    stats2 = cache.getStats(shard2);
    assertEquals(10L, stats2.getCacheSize());
    assertEquals(20L, stats2.getCacheCount());
    assertEquals(1L, stats2.getHitCount());
    assertEquals(20L, stats2.getMissCount());

    IOUtils.close(r2, dir2);
    cache.onClose(shard2);

    // forgot everything about shard2
    stats1 = cache.getStats(shard1);
    assertEquals(0L, stats1.getCacheSize());
    assertEquals(0L, stats1.getCacheCount());
    assertEquals(0L, stats1.getHitCount());
    assertEquals(0L, stats1.getMissCount());

    stats2 = cache.getStats(shard2);
    assertEquals(0L, stats2.getCacheSize());
    assertEquals(0L, stats2.getCacheCount());
    assertEquals(0L, stats2.getHitCount());
    assertEquals(0L, stats2.getMissCount());

    cache.close(); // this triggers some assertions
}

From source file:org.elasticsearch.indices.IndicesQueryCacheTests.java

License:Apache License

public void testStatsOnEviction() throws IOException {
    Directory dir1 = newDirectory();/*from w ww  .  j av a2  s. c  om*/
    IndexWriter w1 = new IndexWriter(dir1, newIndexWriterConfig());
    w1.addDocument(new Document());
    DirectoryReader r1 = DirectoryReader.open(w1);
    w1.close();
    ShardId shard1 = new ShardId("index", "_na_", 0);
    r1 = ElasticsearchDirectoryReader.wrap(r1, shard1);
    IndexSearcher s1 = new IndexSearcher(r1);
    s1.setQueryCachingPolicy(QueryCachingPolicy.ALWAYS_CACHE);

    Directory dir2 = newDirectory();
    IndexWriter w2 = new IndexWriter(dir2, newIndexWriterConfig());
    w2.addDocument(new Document());
    DirectoryReader r2 = DirectoryReader.open(w2);
    w2.close();
    ShardId shard2 = new ShardId("index", "_na_", 1);
    r2 = ElasticsearchDirectoryReader.wrap(r2, shard2);
    IndexSearcher s2 = new IndexSearcher(r2);
    s2.setQueryCachingPolicy(QueryCachingPolicy.ALWAYS_CACHE);

    Settings settings = Settings.builder().put(IndicesQueryCache.INDICES_CACHE_QUERY_COUNT_SETTING.getKey(), 10)
            .put(IndicesQueryCache.INDICES_QUERIES_CACHE_ALL_SEGMENTS_SETTING.getKey(), true).build();
    IndicesQueryCache cache = new IndicesQueryCache(settings);
    s1.setQueryCache(cache);
    s2.setQueryCache(cache);

    assertEquals(1, s1.count(new DummyQuery(0)));

    for (int i = 1; i <= 20; ++i) {
        assertEquals(1, s2.count(new DummyQuery(i)));
    }

    QueryCacheStats stats1 = cache.getStats(shard1);
    assertEquals(0L, stats1.getCacheSize());
    assertEquals(1L, stats1.getCacheCount());

    // this used to fail because we were evicting an empty cache on
    // the segment from r1
    IOUtils.close(r1, dir1);
    cache.onClose(shard1);

    IOUtils.close(r2, dir2);
    cache.onClose(shard2);

    cache.close(); // this triggers some assertions
}

From source file:org.elasticsearch.percolator.CandidateQueryTests.java

License:Apache License

public void testDuel() throws Exception {
    List<Function<String, Query>> queryFunctions = new ArrayList<>();
    queryFunctions.add((id) -> new PrefixQuery(new Term("field", id)));
    queryFunctions.add((id) -> new WildcardQuery(new Term("field", id + "*")));
    queryFunctions.add((id) -> new CustomQuery(new Term("field", id)));
    queryFunctions.add((id) -> new SpanTermQuery(new Term("field", id)));
    queryFunctions.add((id) -> new TermQuery(new Term("field", id)));
    queryFunctions.add((id) -> {// w  w  w  . j ava  2s.  com
        BooleanQuery.Builder builder = new BooleanQuery.Builder();
        return builder.build();
    });
    queryFunctions.add((id) -> {
        BooleanQuery.Builder builder = new BooleanQuery.Builder();
        builder.add(new TermQuery(new Term("field", id)), BooleanClause.Occur.MUST);
        if (randomBoolean()) {
            builder.add(new MatchNoDocsQuery("no reason"), BooleanClause.Occur.MUST_NOT);
        }
        if (randomBoolean()) {
            builder.add(new CustomQuery(new Term("field", id)), BooleanClause.Occur.MUST);
        }
        return builder.build();
    });
    queryFunctions.add((id) -> {
        BooleanQuery.Builder builder = new BooleanQuery.Builder();
        builder.add(new TermQuery(new Term("field", id)), BooleanClause.Occur.SHOULD);
        if (randomBoolean()) {
            builder.add(new MatchNoDocsQuery("no reason"), BooleanClause.Occur.MUST_NOT);
        }
        if (randomBoolean()) {
            builder.add(new CustomQuery(new Term("field", id)), BooleanClause.Occur.SHOULD);
        }
        return builder.build();
    });
    queryFunctions.add((id) -> {
        BooleanQuery.Builder builder = new BooleanQuery.Builder();
        builder.add(new MatchAllDocsQuery(), BooleanClause.Occur.MUST);
        builder.add(new MatchAllDocsQuery(), BooleanClause.Occur.MUST);
        if (randomBoolean()) {
            builder.add(new MatchNoDocsQuery("no reason"), BooleanClause.Occur.MUST_NOT);
        }
        return builder.build();
    });
    queryFunctions.add((id) -> {
        BooleanQuery.Builder builder = new BooleanQuery.Builder();
        builder.add(new MatchAllDocsQuery(), BooleanClause.Occur.SHOULD);
        builder.add(new MatchAllDocsQuery(), BooleanClause.Occur.SHOULD);
        if (randomBoolean()) {
            builder.add(new MatchNoDocsQuery("no reason"), BooleanClause.Occur.MUST_NOT);
        }
        return builder.build();
    });
    queryFunctions.add((id) -> {
        BooleanQuery.Builder builder = new BooleanQuery.Builder();
        builder.setMinimumNumberShouldMatch(randomIntBetween(0, 4));
        builder.add(new TermQuery(new Term("field", id)), BooleanClause.Occur.SHOULD);
        builder.add(new CustomQuery(new Term("field", id)), BooleanClause.Occur.SHOULD);
        return builder.build();
    });
    queryFunctions.add((id) -> new MatchAllDocsQuery());
    queryFunctions.add((id) -> new MatchNoDocsQuery("no reason at all"));

    int numDocs = randomIntBetween(queryFunctions.size(), queryFunctions.size() * 3);
    List<ParseContext.Document> documents = new ArrayList<>();
    for (int i = 0; i < numDocs; i++) {
        String id = Integer.toString(i);
        Query query = queryFunctions.get(i % queryFunctions.size()).apply(id);
        addQuery(query, documents);
    }

    indexWriter.addDocuments(documents);
    indexWriter.close();
    directoryReader = DirectoryReader.open(directory);
    IndexSearcher shardSearcher = newSearcher(directoryReader);
    // Disable query cache, because ControlQuery cannot be cached...
    shardSearcher.setQueryCache(null);

    for (int i = 0; i < numDocs; i++) {
        String id = Integer.toString(i);
        Iterable<? extends IndexableField> doc = Collections
                .singleton(new StringField("field", id, Field.Store.NO));
        MemoryIndex memoryIndex = MemoryIndex.fromDocument(doc, new WhitespaceAnalyzer());
        duelRun(queryStore, memoryIndex, shardSearcher);
    }

    Iterable<? extends IndexableField> doc = Collections
            .singleton(new StringField("field", "value", Field.Store.NO));
    MemoryIndex memoryIndex = MemoryIndex.fromDocument(doc, new WhitespaceAnalyzer());
    duelRun(queryStore, memoryIndex, shardSearcher);
    // Empty percolator doc:
    memoryIndex = new MemoryIndex();
    duelRun(queryStore, memoryIndex, shardSearcher);
}

From source file:org.elasticsearch.percolator.CandidateQueryTests.java

License:Apache License

public void testDuelSpecificQueries() throws Exception {
    List<ParseContext.Document> documents = new ArrayList<>();

    CommonTermsQuery commonTermsQuery = new CommonTermsQuery(BooleanClause.Occur.SHOULD,
            BooleanClause.Occur.SHOULD, 128);
    commonTermsQuery.add(new Term("field", "quick"));
    commonTermsQuery.add(new Term("field", "brown"));
    commonTermsQuery.add(new Term("field", "fox"));
    addQuery(commonTermsQuery, documents);

    BlendedTermQuery blendedTermQuery = BlendedTermQuery.booleanBlendedQuery(
            new Term[] { new Term("field", "quick"), new Term("field", "brown"), new Term("field", "fox") },
            false);/*from   w  w w .  ja  va 2s  . co m*/
    addQuery(blendedTermQuery, documents);

    SpanNearQuery spanNearQuery = new SpanNearQuery.Builder("field", true)
            .addClause(new SpanTermQuery(new Term("field", "quick")))
            .addClause(new SpanTermQuery(new Term("field", "brown")))
            .addClause(new SpanTermQuery(new Term("field", "fox"))).build();
    addQuery(spanNearQuery, documents);

    SpanNearQuery spanNearQuery2 = new SpanNearQuery.Builder("field", true)
            .addClause(new SpanTermQuery(new Term("field", "the")))
            .addClause(new SpanTermQuery(new Term("field", "lazy")))
            .addClause(new SpanTermQuery(new Term("field", "doc"))).build();
    SpanOrQuery spanOrQuery = new SpanOrQuery(spanNearQuery, spanNearQuery2);
    addQuery(spanOrQuery, documents);

    SpanNotQuery spanNotQuery = new SpanNotQuery(spanNearQuery, spanNearQuery);
    addQuery(spanNotQuery, documents);

    long lowerLong = randomIntBetween(0, 256);
    long upperLong = lowerLong + randomIntBetween(0, 32);
    addQuery(LongPoint.newRangeQuery("long_field", lowerLong, upperLong), documents);

    indexWriter.addDocuments(documents);
    indexWriter.close();
    directoryReader = DirectoryReader.open(directory);
    IndexSearcher shardSearcher = newSearcher(directoryReader);
    // Disable query cache, because ControlQuery cannot be cached...
    shardSearcher.setQueryCache(null);

    Document document = new Document();
    document.add(new TextField("field", "the quick brown fox jumps over the lazy dog", Field.Store.NO));
    long randomLong = randomIntBetween((int) lowerLong, (int) upperLong);
    document.add(new LongPoint("long_field", randomLong));
    MemoryIndex memoryIndex = MemoryIndex.fromDocument(document, new WhitespaceAnalyzer());
    duelRun(queryStore, memoryIndex, shardSearcher);
}

From source file:org.elasticsearch.percolator.PercolateQueryBuilder.java

License:Apache License

@Override
protected Query doToQuery(QueryShardContext context) throws IOException {
    if (indexedDocumentIndex != null || indexedDocumentType != null || indexedDocumentId != null) {
        throw new IllegalStateException("query builder must be rewritten first");
    }/*from w  w w . j  a v a 2s .  c  o m*/

    if (document == null) {
        throw new IllegalStateException("no document to percolate");
    }

    MapperService mapperService = context.getMapperService();
    DocumentMapperForType docMapperForType = mapperService.documentMapperWithAutoCreate(documentType);
    DocumentMapper docMapper = docMapperForType.getDocumentMapper();

    ParsedDocument doc = docMapper.parse(source(context.index().getName(), documentType, "_temp_id", document));

    FieldNameAnalyzer fieldNameAnalyzer = (FieldNameAnalyzer) docMapper.mappers().indexAnalyzer();
    // Need to this custom impl because FieldNameAnalyzer is strict and the percolator sometimes isn't when
    // 'index.percolator.map_unmapped_fields_as_string' is enabled:
    Analyzer analyzer = new DelegatingAnalyzerWrapper(Analyzer.PER_FIELD_REUSE_STRATEGY) {
        @Override
        protected Analyzer getWrappedAnalyzer(String fieldName) {
            Analyzer analyzer = fieldNameAnalyzer.analyzers().get(fieldName);
            if (analyzer != null) {
                return analyzer;
            } else {
                return context.getAnalysisService().defaultIndexAnalyzer();
            }
        }
    };
    final IndexSearcher docSearcher;
    if (doc.docs().size() > 1) {
        assert docMapper.hasNestedObjects();
        docSearcher = createMultiDocumentSearcher(analyzer, doc);
    } else {
        MemoryIndex memoryIndex = MemoryIndex.fromDocument(doc.rootDoc(), analyzer, true, false);
        docSearcher = memoryIndex.createSearcher();
        docSearcher.setQueryCache(null);
    }

    Version indexVersionCreated = context.getIndexSettings().getIndexVersionCreated();
    boolean mapUnmappedFieldsAsString = context.getIndexSettings()
            .getValue(PercolatorFieldMapper.INDEX_MAP_UNMAPPED_FIELDS_AS_STRING_SETTING);
    if (indexVersionCreated.onOrAfter(Version.V_5_0_0_alpha1)) {
        MappedFieldType fieldType = context.fieldMapper(field);
        if (fieldType == null) {
            throw new QueryShardException(context, "field [" + field + "] does not exist");
        }

        if (!(fieldType instanceof PercolatorFieldMapper.FieldType)) {
            throw new QueryShardException(context, "expected field [" + field
                    + "] to be of type [percolator], but is of type [" + fieldType.typeName() + "]");
        }
        PercolatorFieldMapper.FieldType pft = (PercolatorFieldMapper.FieldType) fieldType;
        PercolateQuery.QueryStore queryStore = createStore(pft, context, mapUnmappedFieldsAsString);
        return pft.percolateQuery(documentType, queryStore, document, docSearcher);
    } else {
        Query percolateTypeQuery = new TermQuery(
                new Term(TypeFieldMapper.NAME, MapperService.PERCOLATOR_LEGACY_TYPE_NAME));
        PercolateQuery.QueryStore queryStore = createLegacyStore(context, mapUnmappedFieldsAsString);
        return new PercolateQuery(documentType, queryStore, document, percolateTypeQuery, docSearcher,
                new MatchNoDocsQuery("pre 5.0.0-alpha1 index, no verified matches"));
    }
}

From source file:org.elasticsearch.percolator.PercolateQueryBuilder.java

License:Apache License

static IndexSearcher createMultiDocumentSearcher(Analyzer analyzer, ParsedDocument doc) {
    RAMDirectory ramDirectory = new RAMDirectory();
    try (IndexWriter indexWriter = new IndexWriter(ramDirectory, new IndexWriterConfig(analyzer))) {
        indexWriter.addDocuments(doc.docs());
        indexWriter.commit();/*  w  w w. ja  v a2s  . c o  m*/
        DirectoryReader directoryReader = DirectoryReader.open(ramDirectory);
        assert directoryReader.leaves().size() == 1 : "Expected single leaf, but got ["
                + directoryReader.leaves().size() + "]";
        final IndexSearcher slowSearcher = new IndexSearcher(directoryReader) {

            @Override
            public Weight createNormalizedWeight(Query query, boolean needsScores) throws IOException {
                BooleanQuery.Builder bq = new BooleanQuery.Builder();
                bq.add(query, BooleanClause.Occur.MUST);
                bq.add(Queries.newNestedFilter(), BooleanClause.Occur.MUST_NOT);
                return super.createNormalizedWeight(bq.build(), needsScores);
            }

        };
        slowSearcher.setQueryCache(null);
        return slowSearcher;
    } catch (IOException e) {
        throw new ElasticsearchException("Failed to create index for percolator with nested document ", e);
    }
}

From source file:org.elasticsearch.xpack.core.security.authz.accesscontrol.SecurityIndexSearcherWrapper.java

License:Open Source License

@Override
protected IndexSearcher wrap(IndexSearcher searcher) throws EngineException {
    if (licenseState.isSecurityEnabled() == false
            || licenseState.isDocumentAndFieldLevelSecurityAllowed() == false) {
        return searcher;
    }//from  w ww.  j a v  a2s.c o  m

    final DirectoryReader directoryReader = (DirectoryReader) searcher.getIndexReader();
    if (directoryReader instanceof DocumentSubsetDirectoryReader) {
        // The reasons why we return a custom searcher:
        // 1) in the case the role query is sparse then large part of the main query can be skipped
        // 2) If the role query doesn't match with any docs in a segment, that a segment can be skipped
        IndexSearcher indexSearcher = new IndexSearcherWrapper((DocumentSubsetDirectoryReader) directoryReader);
        indexSearcher.setQueryCache(indexSearcher.getQueryCache());
        indexSearcher.setQueryCachingPolicy(indexSearcher.getQueryCachingPolicy());
        indexSearcher.setSimilarity(indexSearcher.getSimilarity(true));
        return indexSearcher;
    }
    return searcher;
}

From source file:org.modeshape.jcr.index.lucene.Searcher.java

License:Apache License

protected <T> T search(Searchable<T> searchable, boolean refreshReader) {
    if (refreshReader) {
        refreshSearchManager();//from ww  w.jav a 2  s.c  o m
    }
    IndexSearcher searcher = null;
    try {
        searcher = searchManager.acquire();
        searcher.setQueryCache(queryCache);
        return searchable.search(searcher);
    } catch (IOException e) {
        throw new LuceneIndexException(e);
    } finally {
        if (searcher != null) {
            try {
                searchManager.release(searcher);
            } catch (IOException e) {
                LOGGER.debug(e, "Cannot release Lucene searcher");
            }
        }
    }
}