Search in sources :

Example 1 with ForceMergeRequest

use of org.opensearch.action.admin.indices.forcemerge.ForceMergeRequest in project OpenSearch by opensearch-project.

the class IndicesRequestConverters method forceMerge.

static Request forceMerge(ForceMergeRequest forceMergeRequest) {
    String[] indices = forceMergeRequest.indices() == null ? Strings.EMPTY_ARRAY : forceMergeRequest.indices();
    Request request = new Request(HttpPost.METHOD_NAME, RequestConverters.endpoint(indices, "_forcemerge"));
    RequestConverters.Params parameters = new RequestConverters.Params();
    parameters.withIndicesOptions(forceMergeRequest.indicesOptions());
    parameters.putParam("max_num_segments", Integer.toString(forceMergeRequest.maxNumSegments()));
    parameters.putParam("only_expunge_deletes", Boolean.toString(forceMergeRequest.onlyExpungeDeletes()));
    parameters.putParam("flush", Boolean.toString(forceMergeRequest.flush()));
    request.addParameters(parameters.asMap());
    return request;
}
Also used : UpdateSettingsRequest(org.opensearch.action.admin.indices.settings.put.UpdateSettingsRequest) CreateIndexRequest(org.opensearch.client.indices.CreateIndexRequest) SimulateIndexTemplateRequest(org.opensearch.client.indices.SimulateIndexTemplateRequest) FlushRequest(org.opensearch.action.admin.indices.flush.FlushRequest) RefreshRequest(org.opensearch.action.admin.indices.refresh.RefreshRequest) GetIndexRequest(org.opensearch.client.indices.GetIndexRequest) DeleteAliasRequest(org.opensearch.client.indices.DeleteAliasRequest) OpenIndexRequest(org.opensearch.action.admin.indices.open.OpenIndexRequest) GetFieldMappingsRequest(org.opensearch.client.indices.GetFieldMappingsRequest) ForceMergeRequest(org.opensearch.action.admin.indices.forcemerge.ForceMergeRequest) GetSettingsRequest(org.opensearch.action.admin.indices.settings.get.GetSettingsRequest) GetDataStreamRequest(org.opensearch.client.indices.GetDataStreamRequest) DeleteIndexRequest(org.opensearch.action.admin.indices.delete.DeleteIndexRequest) ComposableIndexTemplateExistRequest(org.opensearch.client.indices.ComposableIndexTemplateExistRequest) AnalyzeRequest(org.opensearch.client.indices.AnalyzeRequest) ResizeRequest(org.opensearch.client.indices.ResizeRequest) GetComposableIndexTemplateRequest(org.opensearch.client.indices.GetComposableIndexTemplateRequest) DataStreamsStatsRequest(org.opensearch.client.indices.DataStreamsStatsRequest) DeleteIndexTemplateRequest(org.opensearch.action.admin.indices.template.delete.DeleteIndexTemplateRequest) CloseIndexRequest(org.opensearch.client.indices.CloseIndexRequest) GetIndexTemplatesRequest(org.opensearch.client.indices.GetIndexTemplatesRequest) GetMappingsRequest(org.opensearch.client.indices.GetMappingsRequest) GetAliasesRequest(org.opensearch.action.admin.indices.alias.get.GetAliasesRequest) PutComposableIndexTemplateRequest(org.opensearch.client.indices.PutComposableIndexTemplateRequest) CreateDataStreamRequest(org.opensearch.client.indices.CreateDataStreamRequest) IndicesAliasesRequest(org.opensearch.action.admin.indices.alias.IndicesAliasesRequest) PutMappingRequest(org.opensearch.client.indices.PutMappingRequest) DeleteComposableIndexTemplateRequest(org.opensearch.client.indices.DeleteComposableIndexTemplateRequest) PutIndexTemplateRequest(org.opensearch.client.indices.PutIndexTemplateRequest) ValidateQueryRequest(org.opensearch.action.admin.indices.validate.query.ValidateQueryRequest) DeleteDataStreamRequest(org.opensearch.client.indices.DeleteDataStreamRequest) ClearIndicesCacheRequest(org.opensearch.action.admin.indices.cache.clear.ClearIndicesCacheRequest) IndexTemplatesExistRequest(org.opensearch.client.indices.IndexTemplatesExistRequest) RolloverRequest(org.opensearch.client.indices.rollover.RolloverRequest)

Example 2 with ForceMergeRequest

use of org.opensearch.action.admin.indices.forcemerge.ForceMergeRequest in project OpenSearch by opensearch-project.

the class RecoveryDuringReplicationTests method testAddNewReplicas.

public void testAddNewReplicas() throws Exception {
    AtomicBoolean stopped = new AtomicBoolean();
    List<Thread> threads = new ArrayList<>();
    Runnable stopIndexing = () -> {
        try {
            stopped.set(true);
            for (Thread thread : threads) {
                thread.join();
            }
        } catch (Exception e) {
            throw new AssertionError(e);
        }
    };
    try (ReplicationGroup shards = createGroup(between(0, 1));
        Releasable ignored = stopIndexing::run) {
        shards.startAll();
        boolean appendOnly = randomBoolean();
        AtomicInteger docId = new AtomicInteger();
        int numThreads = between(1, 3);
        for (int i = 0; i < numThreads; i++) {
            Thread thread = new Thread(() -> {
                while (stopped.get() == false) {
                    try {
                        int nextId = docId.incrementAndGet();
                        if (appendOnly) {
                            String id = randomBoolean() ? Integer.toString(nextId) : null;
                            shards.index(new IndexRequest(index.getName()).id(id).source("{}", XContentType.JSON));
                        } else if (frequently()) {
                            String id = Integer.toString(frequently() ? nextId : between(0, nextId));
                            shards.index(new IndexRequest(index.getName()).id(id).source("{}", XContentType.JSON));
                        } else {
                            String id = Integer.toString(between(0, nextId));
                            shards.delete(new DeleteRequest(index.getName()).id(id));
                        }
                        if (randomInt(100) < 10) {
                            shards.getPrimary().flush(new FlushRequest());
                        }
                        if (randomInt(100) < 5) {
                            shards.getPrimary().forceMerge(new ForceMergeRequest().flush(randomBoolean()).maxNumSegments(1));
                        }
                    } catch (Exception ex) {
                        throw new AssertionError(ex);
                    }
                }
            });
            threads.add(thread);
            thread.start();
        }
        // we flush quite often
        assertBusy(() -> assertThat(docId.get(), greaterThanOrEqualTo(50)), 60, TimeUnit.SECONDS);
        shards.getPrimary().sync();
        IndexShard newReplica = shards.addReplica();
        shards.recoverReplica(newReplica);
        // we flush quite often
        assertBusy(() -> assertThat(docId.get(), greaterThanOrEqualTo(100)), 60, TimeUnit.SECONDS);
        stopIndexing.run();
        assertBusy(() -> assertThat(getDocIdAndSeqNos(newReplica), equalTo(getDocIdAndSeqNos(shards.getPrimary()))));
    }
}
Also used : ForceMergeRequest(org.opensearch.action.admin.indices.forcemerge.ForceMergeRequest) IndexShard(org.opensearch.index.shard.IndexShard) ArrayList(java.util.ArrayList) IndexRequest(org.opensearch.action.index.IndexRequest) AlreadyClosedException(org.apache.lucene.store.AlreadyClosedException) IOException(java.io.IOException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) FlushRequest(org.opensearch.action.admin.indices.flush.FlushRequest) Releasable(org.opensearch.common.lease.Releasable) DeleteRequest(org.opensearch.action.delete.DeleteRequest)

Example 3 with ForceMergeRequest

use of org.opensearch.action.admin.indices.forcemerge.ForceMergeRequest in project OpenSearch by opensearch-project.

the class IndexShardTests method testDocStats.

public void testDocStats() throws Exception {
    IndexShard indexShard = null;
    try {
        indexShard = newStartedShard(false, Settings.builder().put(IndexSettings.INDEX_SOFT_DELETES_RETENTION_OPERATIONS_SETTING.getKey(), 0).build());
        // at least two documents so we have docs to delete
        final long numDocs = randomIntBetween(2, 32);
        final long numDocsToDelete = randomLongBetween(1, numDocs);
        for (int i = 0; i < numDocs; i++) {
            final String id = Integer.toString(i);
            indexDoc(indexShard, "_doc", id);
        }
        if (randomBoolean()) {
            indexShard.refresh("test");
        } else {
            indexShard.flush(new FlushRequest());
        }
        {
            IndexShard shard = indexShard;
            assertBusy(() -> {
                ThreadPool threadPool = shard.getThreadPool();
                assertThat(threadPool.relativeTimeInMillis(), greaterThan(shard.getLastSearcherAccess()));
            });
            long prevAccessTime = shard.getLastSearcherAccess();
            final DocsStats docsStats = indexShard.docStats();
            assertThat("searcher was marked as accessed", shard.getLastSearcherAccess(), equalTo(prevAccessTime));
            assertThat(docsStats.getCount(), equalTo(numDocs));
            try (Engine.Searcher searcher = indexShard.acquireSearcher("test")) {
                assertTrue(searcher.getIndexReader().numDocs() <= docsStats.getCount());
            }
            assertThat(docsStats.getDeleted(), equalTo(0L));
            assertThat(docsStats.getAverageSizeInBytes(), greaterThan(0L));
        }
        final List<Integer> ids = randomSubsetOf(Math.toIntExact(numDocsToDelete), IntStream.range(0, Math.toIntExact(numDocs)).boxed().collect(Collectors.toList()));
        for (final Integer i : ids) {
            final String id = Integer.toString(i);
            deleteDoc(indexShard, "_doc", id);
            indexDoc(indexShard, "_doc", id);
        }
        // Need to update and sync the global checkpoint and the retention leases for the soft-deletes retention MergePolicy.
        final long newGlobalCheckpoint = indexShard.getLocalCheckpoint();
        if (indexShard.routingEntry().primary()) {
            indexShard.updateLocalCheckpointForShard(indexShard.routingEntry().allocationId().getId(), indexShard.getLocalCheckpoint());
            indexShard.updateGlobalCheckpointForShard(indexShard.routingEntry().allocationId().getId(), indexShard.getLocalCheckpoint());
            indexShard.syncRetentionLeases();
        } else {
            indexShard.updateGlobalCheckpointOnReplica(newGlobalCheckpoint, "test");
            final RetentionLeases retentionLeases = indexShard.getRetentionLeases();
            indexShard.updateRetentionLeasesOnReplica(new RetentionLeases(retentionLeases.primaryTerm(), retentionLeases.version() + 1, retentionLeases.leases().stream().map(lease -> new RetentionLease(lease.id(), newGlobalCheckpoint + 1, lease.timestamp(), ReplicationTracker.PEER_RECOVERY_RETENTION_LEASE_SOURCE)).collect(Collectors.toList())));
        }
        indexShard.sync();
        // flush the buffered deletes
        final FlushRequest flushRequest = new FlushRequest();
        flushRequest.force(false);
        flushRequest.waitIfOngoing(false);
        indexShard.flush(flushRequest);
        if (randomBoolean()) {
            indexShard.refresh("test");
        }
        {
            final DocsStats docStats = indexShard.docStats();
            try (Engine.Searcher searcher = indexShard.acquireSearcher("test")) {
                assertTrue(searcher.getIndexReader().numDocs() <= docStats.getCount());
            }
            assertThat(docStats.getCount(), equalTo(numDocs));
        }
        // merge them away
        final ForceMergeRequest forceMergeRequest = new ForceMergeRequest();
        forceMergeRequest.maxNumSegments(1);
        indexShard.forceMerge(forceMergeRequest);
        if (randomBoolean()) {
            indexShard.refresh("test");
        } else {
            indexShard.flush(new FlushRequest());
        }
        {
            final DocsStats docStats = indexShard.docStats();
            assertThat(docStats.getCount(), equalTo(numDocs));
            assertThat(docStats.getDeleted(), equalTo(0L));
            assertThat(docStats.getAverageSizeInBytes(), greaterThan(0L));
        }
    } finally {
        closeShards(indexShard);
    }
}
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) ForceMergeRequest(org.opensearch.action.admin.indices.forcemerge.ForceMergeRequest) ThreadPool(org.opensearch.threadpool.ThreadPool) Matchers.hasToString(org.hamcrest.Matchers.hasToString) Matchers.containsString(org.hamcrest.Matchers.containsString) RetentionLeases(org.opensearch.index.seqno.RetentionLeases) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) FlushRequest(org.opensearch.action.admin.indices.flush.FlushRequest) RetentionLease(org.opensearch.index.seqno.RetentionLease)

Example 4 with ForceMergeRequest

use of org.opensearch.action.admin.indices.forcemerge.ForceMergeRequest in project OpenSearch by opensearch-project.

the class RestForceMergeAction method prepareRequest.

@Override
public RestChannelConsumer prepareRequest(final RestRequest request, final NodeClient client) throws IOException {
    final ForceMergeRequest mergeRequest = new ForceMergeRequest(Strings.splitStringByCommaToArray(request.param("index")));
    mergeRequest.indicesOptions(IndicesOptions.fromRequest(request, mergeRequest.indicesOptions()));
    mergeRequest.maxNumSegments(request.paramAsInt("max_num_segments", mergeRequest.maxNumSegments()));
    mergeRequest.onlyExpungeDeletes(request.paramAsBoolean("only_expunge_deletes", mergeRequest.onlyExpungeDeletes()));
    mergeRequest.flush(request.paramAsBoolean("flush", mergeRequest.flush()));
    if (mergeRequest.onlyExpungeDeletes() && mergeRequest.maxNumSegments() != ForceMergeRequest.Defaults.MAX_NUM_SEGMENTS) {
        deprecationLogger.deprecate("force_merge_expunge_deletes_and_max_num_segments_deprecation", "setting only_expunge_deletes and max_num_segments at the same time is deprecated and will be rejected in a future version");
    }
    return channel -> client.admin().indices().forceMerge(mergeRequest, new RestToXContentListener<>(channel));
}
Also used : ForceMergeRequest(org.opensearch.action.admin.indices.forcemerge.ForceMergeRequest) POST(org.opensearch.rest.RestRequest.Method.POST) NodeClient(org.opensearch.client.node.NodeClient) Collections.unmodifiableList(java.util.Collections.unmodifiableList) RestRequest(org.opensearch.rest.RestRequest) IOException(java.io.IOException) IndicesOptions(org.opensearch.action.support.IndicesOptions) ForceMergeRequest(org.opensearch.action.admin.indices.forcemerge.ForceMergeRequest) Strings(org.opensearch.common.Strings) DeprecationLogger(org.opensearch.common.logging.DeprecationLogger) List(java.util.List) RestToXContentListener(org.opensearch.rest.action.RestToXContentListener) Arrays.asList(java.util.Arrays.asList) BaseRestHandler(org.opensearch.rest.BaseRestHandler)

Example 5 with ForceMergeRequest

use of org.opensearch.action.admin.indices.forcemerge.ForceMergeRequest in project OpenSearch by opensearch-project.

the class IndicesRequestConvertersTests method testForceMerge.

public void testForceMerge() {
    String[] indices = OpenSearchTestCase.randomBoolean() ? null : RequestConvertersTests.randomIndicesNames(0, 5);
    ForceMergeRequest forceMergeRequest;
    if (OpenSearchTestCase.randomBoolean()) {
        forceMergeRequest = new ForceMergeRequest(indices);
    } else {
        forceMergeRequest = new ForceMergeRequest();
        forceMergeRequest.indices(indices);
    }
    Map<String, String> expectedParams = new HashMap<>();
    RequestConvertersTests.setRandomIndicesOptions(forceMergeRequest::indicesOptions, forceMergeRequest::indicesOptions, expectedParams);
    if (OpenSearchTestCase.randomBoolean()) {
        forceMergeRequest.maxNumSegments(OpenSearchTestCase.randomInt());
    }
    expectedParams.put("max_num_segments", Integer.toString(forceMergeRequest.maxNumSegments()));
    if (OpenSearchTestCase.randomBoolean()) {
        forceMergeRequest.onlyExpungeDeletes(OpenSearchTestCase.randomBoolean());
    }
    expectedParams.put("only_expunge_deletes", Boolean.toString(forceMergeRequest.onlyExpungeDeletes()));
    if (OpenSearchTestCase.randomBoolean()) {
        forceMergeRequest.flush(OpenSearchTestCase.randomBoolean());
    }
    expectedParams.put("flush", Boolean.toString(forceMergeRequest.flush()));
    Request request = IndicesRequestConverters.forceMerge(forceMergeRequest);
    StringJoiner endpoint = new StringJoiner("/", "/", "");
    if (indices != null && indices.length > 0) {
        endpoint.add(String.join(",", indices));
    }
    endpoint.add("_forcemerge");
    Assert.assertThat(request.getEndpoint(), equalTo(endpoint.toString()));
    Assert.assertThat(request.getParameters(), equalTo(expectedParams));
    Assert.assertThat(request.getEntity(), nullValue());
    Assert.assertThat(request.getMethod(), equalTo(HttpPost.METHOD_NAME));
}
Also used : ForceMergeRequest(org.opensearch.action.admin.indices.forcemerge.ForceMergeRequest) HashMap(java.util.HashMap) UpdateSettingsRequest(org.opensearch.action.admin.indices.settings.put.UpdateSettingsRequest) RefreshRequest(org.opensearch.action.admin.indices.refresh.RefreshRequest) OpenIndexRequest(org.opensearch.action.admin.indices.open.OpenIndexRequest) ForceMergeRequest(org.opensearch.action.admin.indices.forcemerge.ForceMergeRequest) GetDataStreamRequest(org.opensearch.client.indices.GetDataStreamRequest) AnalyzeRequest(org.opensearch.client.indices.AnalyzeRequest) DeleteIndexTemplateRequest(org.opensearch.action.admin.indices.template.delete.DeleteIndexTemplateRequest) AcknowledgedRequest(org.opensearch.action.support.master.AcknowledgedRequest) PutMappingRequest(org.opensearch.client.indices.PutMappingRequest) PutIndexTemplateRequest(org.opensearch.client.indices.PutIndexTemplateRequest) DeleteDataStreamRequest(org.opensearch.client.indices.DeleteDataStreamRequest) ClearIndicesCacheRequest(org.opensearch.action.admin.indices.cache.clear.ClearIndicesCacheRequest) RolloverRequest(org.opensearch.client.indices.rollover.RolloverRequest) CreateIndexRequest(org.opensearch.client.indices.CreateIndexRequest) FlushRequest(org.opensearch.action.admin.indices.flush.FlushRequest) GetIndexRequest(org.opensearch.client.indices.GetIndexRequest) DeleteAliasRequest(org.opensearch.client.indices.DeleteAliasRequest) GetFieldMappingsRequest(org.opensearch.client.indices.GetFieldMappingsRequest) GetSettingsRequest(org.opensearch.action.admin.indices.settings.get.GetSettingsRequest) DeleteIndexRequest(org.opensearch.action.admin.indices.delete.DeleteIndexRequest) ResizeRequest(org.opensearch.client.indices.ResizeRequest) CloseIndexRequest(org.opensearch.client.indices.CloseIndexRequest) GetIndexTemplatesRequest(org.opensearch.client.indices.GetIndexTemplatesRequest) GetMappingsRequest(org.opensearch.client.indices.GetMappingsRequest) GetAliasesRequest(org.opensearch.action.admin.indices.alias.get.GetAliasesRequest) CreateDataStreamRequest(org.opensearch.client.indices.CreateDataStreamRequest) IndicesAliasesRequest(org.opensearch.action.admin.indices.alias.IndicesAliasesRequest) ValidateQueryRequest(org.opensearch.action.admin.indices.validate.query.ValidateQueryRequest) IndexTemplatesExistRequest(org.opensearch.client.indices.IndexTemplatesExistRequest) StringJoiner(java.util.StringJoiner)

Aggregations

ForceMergeRequest (org.opensearch.action.admin.indices.forcemerge.ForceMergeRequest)7 FlushRequest (org.opensearch.action.admin.indices.flush.FlushRequest)4 IOException (java.io.IOException)3 ArrayList (java.util.ArrayList)2 List (java.util.List)2 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)2 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)2 AlreadyClosedException (org.apache.lucene.store.AlreadyClosedException)2 IndexRequest (org.opensearch.action.index.IndexRequest)2 Strings (org.opensearch.common.Strings)2 Releasable (org.opensearch.common.lease.Releasable)2 Charset (java.nio.charset.Charset)1 FileVisitResult (java.nio.file.FileVisitResult)1 Files (java.nio.file.Files)1 Path (java.nio.file.Path)1 SimpleFileVisitor (java.nio.file.SimpleFileVisitor)1 BasicFileAttributes (java.nio.file.attribute.BasicFileAttributes)1 Arrays (java.util.Arrays)1 Arrays.asList (java.util.Arrays.asList)1 Collections (java.util.Collections)1