Search in sources :

Example 1 with IndexFieldData

use of org.opensearch.index.fielddata.IndexFieldData in project OpenSearch by opensearch-project.

the class IndexShardTests method testReaderWrapperWorksWithGlobalOrdinals.

public void testReaderWrapperWorksWithGlobalOrdinals() throws IOException {
    CheckedFunction<DirectoryReader, DirectoryReader, IOException> wrapper = reader -> new FieldMaskingReader("foo", reader);
    Settings settings = Settings.builder().put(IndexMetadata.SETTING_VERSION_CREATED, Version.CURRENT).put(IndexMetadata.SETTING_NUMBER_OF_REPLICAS, 0).put(IndexMetadata.SETTING_NUMBER_OF_SHARDS, 1).build();
    IndexMetadata metadata = IndexMetadata.builder("test").putMapping("_doc", "{ \"properties\": { \"foo\":  { \"type\": \"text\", \"fielddata\": true }}}").settings(settings).primaryTerm(0, 1).build();
    IndexShard shard = newShard(new ShardId(metadata.getIndex(), 0), true, "n1", metadata, wrapper);
    recoverShardFromStore(shard);
    indexDoc(shard, "_doc", "0", "{\"foo\" : \"bar\"}");
    shard.refresh("created segment 1");
    indexDoc(shard, "_doc", "1", "{\"foobar\" : \"bar\"}");
    shard.refresh("created segment 2");
    // test global ordinals are evicted
    MappedFieldType foo = shard.mapperService().fieldType("foo");
    IndicesFieldDataCache indicesFieldDataCache = new IndicesFieldDataCache(shard.indexSettings.getNodeSettings(), new IndexFieldDataCache.Listener() {
    });
    IndexFieldDataService indexFieldDataService = new IndexFieldDataService(shard.indexSettings, indicesFieldDataCache, new NoneCircuitBreakerService(), shard.mapperService());
    IndexFieldData.Global ifd = indexFieldDataService.getForField(foo, "test", () -> {
        throw new UnsupportedOperationException("search lookup not available");
    });
    FieldDataStats before = shard.fieldData().stats("foo");
    assertThat(before.getMemorySizeInBytes(), equalTo(0L));
    FieldDataStats after = null;
    try (Engine.Searcher searcher = shard.acquireSearcher("test")) {
        assertThat("we have to have more than one segment", searcher.getDirectoryReader().leaves().size(), greaterThan(1));
        ifd.loadGlobal(searcher.getDirectoryReader());
        after = shard.fieldData().stats("foo");
        assertEquals(after.getEvictions(), before.getEvictions());
        // If a field doesn't exist an empty IndexFieldData is returned and that isn't cached:
        assertThat(after.getMemorySizeInBytes(), equalTo(0L));
    }
    assertEquals(shard.fieldData().stats("foo").getEvictions(), before.getEvictions());
    assertEquals(shard.fieldData().stats("foo").getMemorySizeInBytes(), after.getMemorySizeInBytes());
    shard.flush(new FlushRequest().force(true).waitIfOngoing(true));
    shard.refresh("test");
    assertEquals(shard.fieldData().stats("foo").getMemorySizeInBytes(), before.getMemorySizeInBytes());
    assertEquals(shard.fieldData().stats("foo").getEvictions(), before.getEvictions());
    closeShards(shard);
}
Also used : Matchers.hasToString(org.hamcrest.Matchers.hasToString) SeqNoStats(org.opensearch.index.seqno.SeqNoStats) SequenceNumbers(org.opensearch.index.seqno.SequenceNumbers) MockFSDirectoryFactory(org.opensearch.test.store.MockFSDirectoryFactory) Arrays(java.util.Arrays) CheckedFunction(org.opensearch.common.CheckedFunction) IndexScopedSettings(org.opensearch.common.settings.IndexScopedSettings) Term(org.apache.lucene.index.Term) Matchers.not(org.hamcrest.Matchers.not) AlreadyClosedException(org.apache.lucene.store.AlreadyClosedException) Version(org.opensearch.Version) Strings(org.opensearch.common.Strings) InternalEngine(org.opensearch.index.engine.InternalEngine) PlainActionFuture(org.opensearch.action.support.PlainActionFuture) IndexFieldDataCache(org.opensearch.index.fielddata.IndexFieldDataCache) RecoveryState(org.opensearch.indices.recovery.RecoveryState) Map(java.util.Map) Matchers.nullValue(org.hamcrest.Matchers.nullValue) ActionListener(org.opensearch.action.ActionListener) IOContext(org.apache.lucene.store.IOContext) Path(java.nio.file.Path) NodeEnvironment(org.opensearch.env.NodeEnvironment) TimeValue(org.opensearch.common.unit.TimeValue) Matchers.notNullValue(org.hamcrest.Matchers.notNullValue) Set(java.util.Set) Settings(org.opensearch.common.settings.Settings) ReplicationTracker(org.opensearch.index.seqno.ReplicationTracker) RegexMatcher.matches(org.opensearch.test.hamcrest.RegexMatcher.matches) Engine(org.opensearch.index.engine.Engine) Matchers.instanceOf(org.hamcrest.Matchers.instanceOf) FieldMaskingReader(org.opensearch.test.FieldMaskingReader) FileVisitResult(java.nio.file.FileVisitResult) CountDownLatch(java.util.concurrent.CountDownLatch) VersionType(org.opensearch.index.VersionType) Logger(org.apache.logging.log4j.Logger) EngineConfigFactory(org.opensearch.index.engine.EngineConfigFactory) Stream(java.util.stream.Stream) Randomness(org.opensearch.common.Randomness) BytesArray(org.opensearch.common.bytes.BytesArray) XContentType(org.opensearch.common.xcontent.XContentType) Matchers.greaterThan(org.hamcrest.Matchers.greaterThan) Matchers.is(org.hamcrest.Matchers.is) Matchers.containsString(org.hamcrest.Matchers.containsString) Matchers.in(org.hamcrest.Matchers.in) XContentFactory.jsonBuilder(org.opensearch.common.xcontent.XContentFactory.jsonBuilder) CodecService(org.opensearch.index.codec.CodecService) FlushRequest(org.opensearch.action.admin.indices.flush.FlushRequest) MapperParsingException(org.opensearch.index.mapper.MapperParsingException) ThreadPool(org.opensearch.threadpool.ThreadPool) TestShardRouting.newShardRouting(org.opensearch.cluster.routing.TestShardRouting.newShardRouting) Releasable(org.opensearch.common.lease.Releasable) Supplier(java.util.function.Supplier) ArrayList(java.util.ArrayList) RecoverySource(org.opensearch.cluster.routing.RecoverySource) DocIdSeqNoAndSource(org.opensearch.index.engine.DocIdSeqNoAndSource) UNASSIGNED_SEQ_NO(org.opensearch.index.seqno.SequenceNumbers.UNASSIGNED_SEQ_NO) VersionUtils(org.opensearch.test.VersionUtils) ShardRoutingState(org.opensearch.cluster.routing.ShardRoutingState) VersionFieldMapper(org.opensearch.index.mapper.VersionFieldMapper) Matchers.hasSize(org.hamcrest.Matchers.hasSize) ParsedDocument(org.opensearch.index.mapper.ParsedDocument) CorruptionUtils(org.opensearch.test.CorruptionUtils) CommitStats(org.opensearch.index.engine.CommitStats) TopDocs(org.apache.lucene.search.TopDocs) ParseContext(org.opensearch.index.mapper.ParseContext) Versions(org.opensearch.common.lucene.uid.Versions) Matchers.greaterThanOrEqualTo(org.hamcrest.Matchers.greaterThanOrEqualTo) Files(java.nio.file.Files) TestTranslog(org.opensearch.index.translog.TestTranslog) IOException(java.io.IOException) BrokenBarrierException(java.util.concurrent.BrokenBarrierException) BytesStreamOutput(org.opensearch.common.io.stream.BytesStreamOutput) SourceFieldMapper(org.opensearch.index.mapper.SourceFieldMapper) IndexFieldDataService(org.opensearch.index.fielddata.IndexFieldDataService) XContentBuilder(org.opensearch.common.xcontent.XContentBuilder) ExecutionException(java.util.concurrent.ExecutionException) AtomicLong(java.util.concurrent.atomic.AtomicLong) Matchers.sameInstance(org.hamcrest.Matchers.sameInstance) NamedXContentRegistry(org.opensearch.common.xcontent.NamedXContentRegistry) RetentionLeases(org.opensearch.index.seqno.RetentionLeases) ShardStats(org.opensearch.action.admin.indices.stats.ShardStats) RetentionLeaseSyncer(org.opensearch.index.seqno.RetentionLeaseSyncer) Assert(org.junit.Assert) SeqNoFieldMapper(org.opensearch.index.mapper.SeqNoFieldMapper) CommonStats(org.opensearch.action.admin.indices.stats.CommonStats) ReadOnlyEngine(org.opensearch.index.engine.ReadOnlyEngine) IdFieldMapper(org.opensearch.index.mapper.IdFieldMapper) Matchers.either(org.hamcrest.Matchers.either) AbstractRunnable(org.opensearch.common.util.concurrent.AbstractRunnable) FieldDataStats(org.opensearch.index.fielddata.FieldDataStats) IndexableField(org.apache.lucene.index.IndexableField) Lucene.cleanLuceneIndex(org.opensearch.common.lucene.Lucene.cleanLuceneIndex) NoneCircuitBreakerService(org.opensearch.indices.breaker.NoneCircuitBreakerService) OpenSearchException(org.opensearch.OpenSearchException) Releasables(org.opensearch.common.lease.Releasables) CommonStatsFlags(org.opensearch.action.admin.indices.stats.CommonStatsFlags) Matchers.hasKey(org.hamcrest.Matchers.hasKey) CorruptIndexException(org.apache.lucene.index.CorruptIndexException) ForceMergeRequest(org.opensearch.action.admin.indices.forcemerge.ForceMergeRequest) ConcurrentCollections(org.opensearch.common.util.concurrent.ConcurrentCollections) DiscoveryNode(org.opensearch.cluster.node.DiscoveryNode) MapperService(org.opensearch.index.mapper.MapperService) IndexId(org.opensearch.repositories.IndexId) Matchers.everyItem(org.hamcrest.Matchers.everyItem) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Locale(java.util.Locale) Directory(org.apache.lucene.store.Directory) Assertions(org.opensearch.Assertions) XContentFactory(org.opensearch.common.xcontent.XContentFactory) DummyShardLock(org.opensearch.test.DummyShardLock) UnassignedInfo(org.opensearch.cluster.routing.UnassignedInfo) SimpleFileVisitor(java.nio.file.SimpleFileVisitor) IndexShardRoutingTable(org.opensearch.cluster.routing.IndexShardRoutingTable) EngineTestCase(org.opensearch.index.engine.EngineTestCase) CyclicBarrier(java.util.concurrent.CyclicBarrier) DeleteResult(org.opensearch.index.engine.Engine.DeleteResult) BytesRef(org.apache.lucene.util.BytesRef) MappedFieldType(org.opensearch.index.mapper.MappedFieldType) SnapshotId(org.opensearch.snapshots.SnapshotId) Matchers.lessThanOrEqualTo(org.hamcrest.Matchers.lessThanOrEqualTo) DirectoryReader(org.apache.lucene.index.DirectoryReader) Store(org.opensearch.index.store.Store) Collectors(java.util.stream.Collectors) Tuple(org.opensearch.common.collect.Tuple) List(java.util.List) Matchers.containsInAnyOrder(org.hamcrest.Matchers.containsInAnyOrder) Matchers.equalTo(org.hamcrest.Matchers.equalTo) IndexSettings(org.opensearch.index.IndexSettings) ShardRoutingHelper(org.opensearch.cluster.routing.ShardRoutingHelper) Uid(org.opensearch.index.mapper.Uid) TranslogStats(org.opensearch.index.translog.TranslogStats) MappingMetadata(org.opensearch.cluster.metadata.MappingMetadata) IntStream(java.util.stream.IntStream) IndexMetadata(org.opensearch.cluster.metadata.IndexMetadata) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) EngineConfig(org.opensearch.index.engine.EngineConfig) StoreUtils(org.opensearch.index.store.StoreUtils) IndicesFieldDataCache(org.opensearch.indices.fielddata.cache.IndicesFieldDataCache) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) HashSet(java.util.HashSet) IndexFieldData(org.opensearch.index.fielddata.IndexFieldData) SourceToParse(org.opensearch.index.mapper.SourceToParse) Charset(java.nio.charset.Charset) Translog(org.opensearch.index.translog.Translog) UUIDs(org.opensearch.common.UUIDs) IndicesQueryCache(org.opensearch.indices.IndicesQueryCache) StoreStats(org.opensearch.index.store.StoreStats) RetentionLease(org.opensearch.index.seqno.RetentionLease) StreamInput(org.opensearch.common.io.stream.StreamInput) InternalEngineFactory(org.opensearch.index.engine.InternalEngineFactory) Collections.emptyMap(java.util.Collections.emptyMap) Matchers.oneOf(org.hamcrest.Matchers.oneOf) RecoveryTarget(org.opensearch.indices.recovery.RecoveryTarget) LongFunction(java.util.function.LongFunction) Collections.emptySet(java.util.Collections.emptySet) AllocationId(org.opensearch.cluster.routing.AllocationId) Semaphore(java.util.concurrent.Semaphore) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes) EMPTY_PARAMS(org.opensearch.common.xcontent.ToXContent.EMPTY_PARAMS) ShardRouting(org.opensearch.cluster.routing.ShardRouting) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) TestShardRouting(org.opensearch.cluster.routing.TestShardRouting) TermQuery(org.apache.lucene.search.TermQuery) Constants(org.apache.lucene.util.Constants) AtomicArray(org.opensearch.common.util.concurrent.AtomicArray) FilterDirectory(org.apache.lucene.store.FilterDirectory) Snapshot(org.opensearch.snapshots.Snapshot) IndexRequest(org.opensearch.action.index.IndexRequest) Collections(java.util.Collections) DirectoryReader(org.apache.lucene.index.DirectoryReader) FieldMaskingReader(org.opensearch.test.FieldMaskingReader) IOException(java.io.IOException) IndexFieldDataCache(org.opensearch.index.fielddata.IndexFieldDataCache) IndicesFieldDataCache(org.opensearch.indices.fielddata.cache.IndicesFieldDataCache) FlushRequest(org.opensearch.action.admin.indices.flush.FlushRequest) IndexFieldDataService(org.opensearch.index.fielddata.IndexFieldDataService) MappedFieldType(org.opensearch.index.mapper.MappedFieldType) IndexFieldData(org.opensearch.index.fielddata.IndexFieldData) IndexMetadata(org.opensearch.cluster.metadata.IndexMetadata) IndexScopedSettings(org.opensearch.common.settings.IndexScopedSettings) Settings(org.opensearch.common.settings.Settings) IndexSettings(org.opensearch.index.IndexSettings) InternalEngine(org.opensearch.index.engine.InternalEngine) Engine(org.opensearch.index.engine.Engine) ReadOnlyEngine(org.opensearch.index.engine.ReadOnlyEngine) NoneCircuitBreakerService(org.opensearch.indices.breaker.NoneCircuitBreakerService) FieldDataStats(org.opensearch.index.fielddata.FieldDataStats)

Example 2 with IndexFieldData

use of org.opensearch.index.fielddata.IndexFieldData in project OpenSearch by opensearch-project.

the class SliceBuilder method toFilter.

/**
 * Converts this QueryBuilder to a lucene {@link Query}.
 *
 * @param context Additional information needed to build the query
 */
public Query toFilter(ClusterService clusterService, ShardSearchRequest request, QueryShardContext context, Version minNodeVersion) {
    final MappedFieldType type = context.fieldMapper(field);
    if (type == null) {
        throw new IllegalArgumentException("field " + field + " not found");
    }
    int shardId = request.shardId().id();
    int numShards = context.getIndexSettings().getNumberOfShards();
    if ((request.preference() != null || request.indexRoutings().length > 0)) {
        GroupShardsIterator<ShardIterator> group = buildShardIterator(clusterService, request);
        assert group.size() <= numShards : "index routing shards: " + group.size() + " cannot be greater than total number of shards: " + numShards;
        if (group.size() < numShards) {
            /*
                 * The routing of this request targets a subset of the shards of this index so we need to we retrieve
                 * the original {@link GroupShardsIterator} and compute the request shard id and number of
                 * shards from it.
                 */
            numShards = group.size();
            int ord = 0;
            shardId = -1;
            // remap the original shard id with its index (position) in the sorted shard iterator.
            for (ShardIterator it : group) {
                assert it.shardId().getIndex().equals(request.shardId().getIndex());
                if (request.shardId().equals(it.shardId())) {
                    shardId = ord;
                    break;
                }
                ++ord;
            }
            assert shardId != -1 : "shard id: " + request.shardId().getId() + " not found in index shard routing";
        }
    }
    String field = this.field;
    boolean useTermQuery = false;
    if ("_uid".equals(field)) {
        // on new indices, the _id acts as a _uid
        field = IdFieldMapper.NAME;
        if (context.getIndexSettings().getIndexVersionCreated().onOrAfter(LegacyESVersion.V_7_0_0)) {
            throw new IllegalArgumentException("Computing slices on the [_uid] field is illegal for 7.x indices, use [_id] instead");
        }
        DEPRECATION_LOG.deprecate("slice_on_uid", "Computing slices on the [_uid] field is deprecated for 6.x indices, use [_id] instead");
        useTermQuery = true;
    } else if (IdFieldMapper.NAME.equals(field)) {
        useTermQuery = true;
    } else if (type.hasDocValues() == false) {
        throw new IllegalArgumentException("cannot load numeric doc values on " + field);
    } else {
        IndexFieldData ifm = context.getForField(type);
        if (ifm instanceof IndexNumericFieldData == false) {
            throw new IllegalArgumentException("cannot load numeric doc values on " + field);
        }
    }
    if (numShards == 1) {
        return useTermQuery ? new TermsSliceQuery(field, id, max) : new DocValuesSliceQuery(field, id, max);
    }
    if (max >= numShards) {
        // the number of slices is greater than the number of shards
        // in such case we can reduce the number of requested shards by slice
        // first we check if the slice is responsible of this shard
        int targetShard = id % numShards;
        if (targetShard != shardId) {
            // the shard is not part of this slice, we can skip it.
            return new MatchNoDocsQuery("this shard is not part of the slice");
        }
        // compute the number of slices where this shard appears
        int numSlicesInShard = max / numShards;
        int rest = max % numShards;
        if (rest > targetShard) {
            numSlicesInShard++;
        }
        if (numSlicesInShard == 1) {
            // this shard has only one slice so we must check all the documents
            return new MatchAllDocsQuery();
        }
        // get the new slice id for this shard
        int shardSlice = id / numShards;
        return useTermQuery ? new TermsSliceQuery(field, shardSlice, numSlicesInShard) : new DocValuesSliceQuery(field, shardSlice, numSlicesInShard);
    }
    // the number of shards is greater than the number of slices
    // check if the shard is assigned to the slice
    int targetSlice = shardId % max;
    if (id != targetSlice) {
        // the shard is not part of this slice, we can skip it.
        return new MatchNoDocsQuery("this shard is not part of the slice");
    }
    return new MatchAllDocsQuery();
}
Also used : MatchNoDocsQuery(org.apache.lucene.search.MatchNoDocsQuery) IndexNumericFieldData(org.opensearch.index.fielddata.IndexNumericFieldData) MatchAllDocsQuery(org.apache.lucene.search.MatchAllDocsQuery) MappedFieldType(org.opensearch.index.mapper.MappedFieldType) ShardIterator(org.opensearch.cluster.routing.ShardIterator) IndexFieldData(org.opensearch.index.fielddata.IndexFieldData)

Example 3 with IndexFieldData

use of org.opensearch.index.fielddata.IndexFieldData in project OpenSearch by opensearch-project.

the class LeafDocLookupTests method setUp.

@Before
public void setUp() throws Exception {
    super.setUp();
    MappedFieldType fieldType = mock(MappedFieldType.class);
    when(fieldType.name()).thenReturn("field");
    when(fieldType.valueForDisplay(any())).then(returnsFirstArg());
    MapperService mapperService = mock(MapperService.class);
    when(mapperService.fieldType("field")).thenReturn(fieldType);
    when(mapperService.fieldType("alias")).thenReturn(fieldType);
    docValues = mock(ScriptDocValues.class);
    IndexFieldData<?> fieldData = createFieldData(docValues);
    docLookup = new LeafDocLookup(mapperService, ignored -> fieldData, null);
}
Also used : AdditionalAnswers.returnsFirstArg(org.mockito.AdditionalAnswers.returnsFirstArg) IndexFieldData(org.opensearch.index.fielddata.IndexFieldData) MapperService(org.opensearch.index.mapper.MapperService) ScriptDocValues(org.opensearch.index.fielddata.ScriptDocValues) MappedFieldType(org.opensearch.index.mapper.MappedFieldType) OpenSearchTestCase(org.opensearch.test.OpenSearchTestCase) LeafFieldData(org.opensearch.index.fielddata.LeafFieldData) Mockito.when(org.mockito.Mockito.when) Mockito.any(org.mockito.Mockito.any) Mockito.doReturn(org.mockito.Mockito.doReturn) Before(org.junit.Before) Mockito.mock(org.mockito.Mockito.mock) MappedFieldType(org.opensearch.index.mapper.MappedFieldType) ScriptDocValues(org.opensearch.index.fielddata.ScriptDocValues) MapperService(org.opensearch.index.mapper.MapperService) Before(org.junit.Before)

Example 4 with IndexFieldData

use of org.opensearch.index.fielddata.IndexFieldData in project OpenSearch by opensearch-project.

the class PercolateQueryBuilder method wrap.

static QueryShardContext wrap(QueryShardContext shardContext) {
    return new QueryShardContext(shardContext) {

        @Override
        public IndexReader getIndexReader() {
            // the reader of the MemoryIndex. We just use `null` for simplicity.
            return null;
        }

        @Override
        public BitSetProducer bitsetFilter(Query query) {
            return context -> {
                final IndexReaderContext topLevelContext = ReaderUtil.getTopLevelContext(context);
                final IndexSearcher searcher = new IndexSearcher(topLevelContext);
                searcher.setQueryCache(null);
                final Weight weight = searcher.createWeight(searcher.rewrite(query), ScoreMode.COMPLETE_NO_SCORES, 1f);
                final Scorer s = weight.scorer(context);
                if (s != null) {
                    return new BitDocIdSet(BitSet.of(s.iterator(), context.reader().maxDoc())).bits();
                } else {
                    return null;
                }
            };
        }

        @Override
        @SuppressWarnings("unchecked")
        public <IFD extends IndexFieldData<?>> IFD getForField(MappedFieldType fieldType) {
            IndexFieldData.Builder builder = fieldType.fielddataBuilder(shardContext.getFullyQualifiedIndex().getName(), shardContext::lookup);
            IndexFieldDataCache cache = new IndexFieldDataCache.None();
            CircuitBreakerService circuitBreaker = new NoneCircuitBreakerService();
            return (IFD) builder.build(cache, circuitBreaker);
        }
    };
}
Also used : Query(org.apache.lucene.search.Query) ConstructingObjectParser(org.opensearch.common.xcontent.ConstructingObjectParser) FieldNameAnalyzer(org.opensearch.index.analysis.FieldNameAnalyzer) NoneCircuitBreakerService(org.opensearch.indices.breaker.NoneCircuitBreakerService) Version(org.opensearch.Version) InputStreamStreamInput(org.opensearch.common.io.stream.InputStreamStreamInput) BitSet(org.apache.lucene.util.BitSet) OpenSearchException(org.opensearch.OpenSearchException) XContentParser(org.opensearch.common.xcontent.XContentParser) MapperService(org.opensearch.index.mapper.MapperService) ByteArrayInputStream(java.io.ByteArrayInputStream) IndexFieldDataCache(org.opensearch.index.fielddata.IndexFieldDataCache) Directory(org.apache.lucene.store.Directory) XContentFactory(org.opensearch.common.xcontent.XContentFactory) ActionListener(org.opensearch.action.ActionListener) BitDocIdSet(org.apache.lucene.util.BitDocIdSet) Scorer(org.apache.lucene.search.Scorer) BytesRef(org.apache.lucene.util.BytesRef) MappedFieldType(org.opensearch.index.mapper.MappedFieldType) DirectoryReader(org.apache.lucene.index.DirectoryReader) Collection(java.util.Collection) LoggingDeprecationHandler(org.opensearch.common.xcontent.LoggingDeprecationHandler) QueryShardException(org.opensearch.index.query.QueryShardException) Objects(java.util.Objects) IndexWriter(org.apache.lucene.index.IndexWriter) List(java.util.List) QueryBuilder(org.opensearch.index.query.QueryBuilder) LeafReader(org.apache.lucene.index.LeafReader) QueryShardContext(org.opensearch.index.query.QueryShardContext) XContentType(org.opensearch.common.xcontent.XContentType) AbstractQueryBuilder(org.opensearch.index.query.AbstractQueryBuilder) BinaryDocValues(org.apache.lucene.index.BinaryDocValues) IndexWriterConfig(org.apache.lucene.index.IndexWriterConfig) IndexReader(org.apache.lucene.index.IndexReader) IndexSearcher(org.apache.lucene.search.IndexSearcher) ReaderUtil(org.apache.lucene.index.ReaderUtil) BytesReference(org.opensearch.common.bytes.BytesReference) MemoryIndex(org.apache.lucene.index.memory.MemoryIndex) Weight(org.apache.lucene.search.Weight) StreamOutput(org.opensearch.common.io.stream.StreamOutput) ResourceNotFoundException(org.opensearch.ResourceNotFoundException) ParseField(org.opensearch.common.ParseField) Supplier(java.util.function.Supplier) ConstructingObjectParser.constructorArg(org.opensearch.common.xcontent.ConstructingObjectParser.constructorArg) NamedWriteableRegistry(org.opensearch.common.io.stream.NamedWriteableRegistry) ArrayList(java.util.ArrayList) DeprecationLogger(org.opensearch.common.logging.DeprecationLogger) BitSetProducer(org.apache.lucene.search.join.BitSetProducer) IndexFieldData(org.opensearch.index.fielddata.IndexFieldData) SourceToParse(org.opensearch.index.mapper.SourceToParse) ByteBuffersDirectory(org.apache.lucene.store.ByteBuffersDirectory) DelegatingAnalyzerWrapper(org.apache.lucene.analysis.DelegatingAnalyzerWrapper) ParsedDocument(org.opensearch.index.mapper.ParsedDocument) ConstructingObjectParser.optionalConstructorArg(org.opensearch.common.xcontent.ConstructingObjectParser.optionalConstructorArg) NamedWriteableAwareStreamInput(org.opensearch.common.io.stream.NamedWriteableAwareStreamInput) StreamInput(org.opensearch.common.io.stream.StreamInput) ParseContext(org.opensearch.index.mapper.ParseContext) SetOnce(org.apache.lucene.util.SetOnce) Analyzer(org.apache.lucene.analysis.Analyzer) GetRequest(org.opensearch.action.get.GetRequest) Rewriteable(org.opensearch.index.query.Rewriteable) IOException(java.io.IOException) DocumentMapper(org.opensearch.index.mapper.DocumentMapper) ScoreMode(org.apache.lucene.search.ScoreMode) XContentBuilder(org.opensearch.common.xcontent.XContentBuilder) XContentHelper(org.opensearch.common.xcontent.XContentHelper) QueryRewriteContext(org.opensearch.index.query.QueryRewriteContext) CircuitBreakerService(org.opensearch.indices.breaker.CircuitBreakerService) NamedXContentRegistry(org.opensearch.common.xcontent.NamedXContentRegistry) ALLOW_EXPENSIVE_QUERIES(org.opensearch.search.SearchService.ALLOW_EXPENSIVE_QUERIES) Collections(java.util.Collections) IndexReaderContext(org.apache.lucene.index.IndexReaderContext) InputStream(java.io.InputStream) IndexSearcher(org.apache.lucene.search.IndexSearcher) BitDocIdSet(org.apache.lucene.util.BitDocIdSet) Query(org.apache.lucene.search.Query) Scorer(org.apache.lucene.search.Scorer) IndexReaderContext(org.apache.lucene.index.IndexReaderContext) Weight(org.apache.lucene.search.Weight) IndexFieldDataCache(org.opensearch.index.fielddata.IndexFieldDataCache) MappedFieldType(org.opensearch.index.mapper.MappedFieldType) QueryShardContext(org.opensearch.index.query.QueryShardContext) IndexFieldData(org.opensearch.index.fielddata.IndexFieldData) NoneCircuitBreakerService(org.opensearch.indices.breaker.NoneCircuitBreakerService) CircuitBreakerService(org.opensearch.indices.breaker.CircuitBreakerService) NoneCircuitBreakerService(org.opensearch.indices.breaker.NoneCircuitBreakerService)

Example 5 with IndexFieldData

use of org.opensearch.index.fielddata.IndexFieldData in project OpenSearch by opensearch-project.

the class AbstractSortTestCase method createMockShardContext.

protected final QueryShardContext createMockShardContext(IndexSearcher searcher) {
    Index index = new Index(randomAlphaOfLengthBetween(1, 10), "_na_");
    IndexSettings idxSettings = IndexSettingsModule.newIndexSettings(index, Settings.builder().put(IndexMetadata.SETTING_VERSION_CREATED, Version.CURRENT).build());
    BitsetFilterCache bitsetFilterCache = new BitsetFilterCache(idxSettings, Mockito.mock(BitsetFilterCache.Listener.class));
    TriFunction<MappedFieldType, String, Supplier<SearchLookup>, IndexFieldData<?>> indexFieldDataLookup = (fieldType, fieldIndexName, searchLookup) -> {
        IndexFieldData.Builder builder = fieldType.fielddataBuilder(fieldIndexName, searchLookup);
        return builder.build(new IndexFieldDataCache.None(), null);
    };
    return new QueryShardContext(0, idxSettings, BigArrays.NON_RECYCLING_INSTANCE, bitsetFilterCache, indexFieldDataLookup, null, null, scriptService, xContentRegistry(), namedWriteableRegistry, null, searcher, () -> randomNonNegativeLong(), null, null, () -> true, null) {

        @Override
        public MappedFieldType fieldMapper(String name) {
            return provideMappedFieldType(name);
        }

        @Override
        public ObjectMapper getObjectMapper(String name) {
            BuilderContext context = new BuilderContext(this.getIndexSettings().getSettings(), new ContentPath());
            return new ObjectMapper.Builder<>(name).nested(Nested.newNested()).build(context);
        }
    };
}
Also used : ScriptModule(org.opensearch.script.ScriptModule) ToXContent(org.opensearch.common.xcontent.ToXContent) ScriptEngine(org.opensearch.script.ScriptEngine) ContentPath(org.opensearch.index.mapper.ContentPath) Version(org.opensearch.Version) XContentParser(org.opensearch.common.xcontent.XContentParser) IndexFieldDataCache(org.opensearch.index.fielddata.IndexFieldDataCache) Map(java.util.Map) XContentFactory(org.opensearch.common.xcontent.XContentFactory) SortField(org.apache.lucene.search.SortField) BitsetFilterCache(org.opensearch.index.cache.bitset.BitsetFilterCache) MockScriptEngine(org.opensearch.script.MockScriptEngine) ScriptService(org.opensearch.script.ScriptService) AfterClass(org.junit.AfterClass) Index(org.opensearch.index.Index) MappedFieldType(org.opensearch.index.mapper.MappedFieldType) Collections.emptyList(java.util.Collections.emptyList) OpenSearchTestCase(org.opensearch.test.OpenSearchTestCase) Settings(org.opensearch.common.settings.Settings) BuilderContext(org.opensearch.index.mapper.Mapper.BuilderContext) SearchLookup(org.opensearch.search.lookup.SearchLookup) QueryBuilder(org.opensearch.index.query.QueryBuilder) IndexSettings(org.opensearch.index.IndexSettings) QueryShardContext(org.opensearch.index.query.QueryShardContext) XContentType(org.opensearch.common.xcontent.XContentType) BigArrays(org.opensearch.common.util.BigArrays) IndexSearcher(org.apache.lucene.search.IndexSearcher) TriFunction(org.opensearch.common.TriFunction) IndexSettingsModule(org.opensearch.test.IndexSettingsModule) BeforeClass(org.junit.BeforeClass) IndexMetadata(org.opensearch.cluster.metadata.IndexMetadata) DocValueFormat(org.opensearch.search.DocValueFormat) ObjectMapper(org.opensearch.index.mapper.ObjectMapper) Function(java.util.function.Function) Supplier(java.util.function.Supplier) NumberFieldMapper(org.opensearch.index.mapper.NumberFieldMapper) NamedWriteableRegistry(org.opensearch.common.io.stream.NamedWriteableRegistry) Nested(org.opensearch.index.mapper.ObjectMapper.Nested) IndexFieldData(org.opensearch.index.fielddata.IndexFieldData) Environment(org.opensearch.env.Environment) IdsQueryBuilder(org.opensearch.index.query.IdsQueryBuilder) EqualsHashCodeTestUtils.checkEqualsAndHashCode(org.opensearch.test.EqualsHashCodeTestUtils.checkEqualsAndHashCode) Rewriteable(org.opensearch.index.query.Rewriteable) TermQueryBuilder(org.opensearch.index.query.TermQueryBuilder) IOException(java.io.IOException) XContentBuilder(org.opensearch.common.xcontent.XContentBuilder) Mockito(org.mockito.Mockito) NamedXContentRegistry(org.opensearch.common.xcontent.NamedXContentRegistry) MatchAllQueryBuilder(org.opensearch.index.query.MatchAllQueryBuilder) Collections(java.util.Collections) SearchModule(org.opensearch.search.SearchModule) IndexSettings(org.opensearch.index.IndexSettings) QueryBuilder(org.opensearch.index.query.QueryBuilder) IdsQueryBuilder(org.opensearch.index.query.IdsQueryBuilder) TermQueryBuilder(org.opensearch.index.query.TermQueryBuilder) XContentBuilder(org.opensearch.common.xcontent.XContentBuilder) MatchAllQueryBuilder(org.opensearch.index.query.MatchAllQueryBuilder) Index(org.opensearch.index.Index) ContentPath(org.opensearch.index.mapper.ContentPath) MappedFieldType(org.opensearch.index.mapper.MappedFieldType) IndexFieldData(org.opensearch.index.fielddata.IndexFieldData) QueryShardContext(org.opensearch.index.query.QueryShardContext) BuilderContext(org.opensearch.index.mapper.Mapper.BuilderContext) Supplier(java.util.function.Supplier) BitsetFilterCache(org.opensearch.index.cache.bitset.BitsetFilterCache)

Aggregations

IndexFieldData (org.opensearch.index.fielddata.IndexFieldData)7 MappedFieldType (org.opensearch.index.mapper.MappedFieldType)6 IOException (java.io.IOException)4 Collections (java.util.Collections)4 Supplier (java.util.function.Supplier)4 ArrayList (java.util.ArrayList)3 List (java.util.List)3 Map (java.util.Map)3 IndexSearcher (org.apache.lucene.search.IndexSearcher)3 XContentBuilder (org.opensearch.common.xcontent.XContentBuilder)3 IndexFieldDataCache (org.opensearch.index.fielddata.IndexFieldDataCache)3 QueryShardContext (org.opensearch.index.query.QueryShardContext)3 SearchLookup (org.opensearch.search.lookup.SearchLookup)3 Consumer (java.util.function.Consumer)2 Function (java.util.function.Function)2 LeafReaderContext (org.apache.lucene.index.LeafReaderContext)2 Query (org.apache.lucene.search.Query)2 SetOnce (org.apache.lucene.util.SetOnce)2 Version (org.opensearch.Version)2 BytesReference (org.opensearch.common.bytes.BytesReference)2