Search in sources :

Example 56 with IndexMetaData

use of org.elasticsearch.cluster.metadata.IndexMetaData in project elasticsearch by elastic.

the class IndicesService method buildAliasFilter.

public AliasFilter buildAliasFilter(ClusterState state, String index, String... expressions) {
    /* Being static, parseAliasFilter doesn't have access to whatever guts it needs to parse a query. Instead of passing in a bunch
         * of dependencies we pass in a function that can perform the parsing. */
    CheckedFunction<byte[], QueryBuilder, IOException> filterParser = bytes -> {
        try (XContentParser parser = XContentFactory.xContent(bytes).createParser(xContentRegistry, bytes)) {
            return new QueryParseContext(parser).parseInnerQueryBuilder();
        }
    };
    String[] aliases = indexNameExpressionResolver.filteringAliases(state, index, expressions);
    IndexMetaData indexMetaData = state.metaData().index(index);
    return new AliasFilter(ShardSearchRequest.parseAliasFilter(filterParser, indexMetaData, aliases), aliases);
}
Also used : ShardId(org.elasticsearch.index.shard.ShardId) StreamOutput(org.elasticsearch.common.io.stream.StreamOutput) Nullable(org.elasticsearch.common.Nullable) BigArrays(org.elasticsearch.common.util.BigArrays) FlushStats(org.elasticsearch.index.flush.FlushStats) RecoveryStats(org.elasticsearch.index.recovery.RecoveryStats) ClusterState(org.elasticsearch.cluster.ClusterState) QueryPhase(org.elasticsearch.search.query.QueryPhase) IndexingStats(org.elasticsearch.index.shard.IndexingStats) IndexNotFoundException(org.elasticsearch.index.IndexNotFoundException) Map(java.util.Map) EnumSet(java.util.EnumSet) MergeStats(org.elasticsearch.index.merge.MergeStats) SearchType(org.elasticsearch.action.search.SearchType) PeerRecoveryTargetService(org.elasticsearch.indices.recovery.PeerRecoveryTargetService) Set(java.util.Set) CollectionUtils.arrayAsArrayList(org.elasticsearch.common.util.CollectionUtils.arrayAsArrayList) Executors(java.util.concurrent.Executors) RecoverySource(org.elasticsearch.cluster.routing.RecoverySource) CheckedFunction(org.elasticsearch.common.CheckedFunction) AliasFilter(org.elasticsearch.search.internal.AliasFilter) CountDownLatch(java.util.concurrent.CountDownLatch) Logger(org.apache.logging.log4j.Logger) IndexMetaData(org.elasticsearch.cluster.metadata.IndexMetaData) Callback(org.elasticsearch.common.util.Callback) XContentFactory(org.elasticsearch.common.xcontent.XContentFactory) LockObtainFailedException(org.apache.lucene.store.LockObtainFailedException) IndexShardStats(org.elasticsearch.action.admin.indices.stats.IndexShardStats) ClusterService(org.elasticsearch.cluster.service.ClusterService) BytesStreamOutput(org.elasticsearch.common.io.stream.BytesStreamOutput) IndexModule(org.elasticsearch.index.IndexModule) Supplier(java.util.function.Supplier) CircuitBreakerService(org.elasticsearch.indices.breaker.CircuitBreakerService) ArrayList(java.util.ArrayList) BytesArray(org.elasticsearch.common.bytes.BytesArray) ShardRequestCache(org.elasticsearch.index.cache.request.ShardRequestCache) NamedWriteableRegistry(org.elasticsearch.common.io.stream.NamedWriteableRegistry) CircuitBreaker(org.elasticsearch.common.breaker.CircuitBreaker) MetaDataStateFormat(org.elasticsearch.gateway.MetaDataStateFormat) QueryBuilder(org.elasticsearch.index.query.QueryBuilder) FileSystemUtils(org.elasticsearch.common.io.FileSystemUtils) IndexEventListener(org.elasticsearch.index.shard.IndexEventListener) Files(java.nio.file.Files) Client(org.elasticsearch.client.Client) IndexService(org.elasticsearch.index.IndexService) IndexShard(org.elasticsearch.index.shard.IndexShard) IOUtils(org.apache.lucene.util.IOUtils) IOException(java.io.IOException) ShardLock(org.elasticsearch.env.ShardLock) RepositoriesService(org.elasticsearch.repositories.RepositoriesService) CollectionUtil(org.apache.lucene.util.CollectionUtil) XContentParser(org.elasticsearch.common.xcontent.XContentParser) NamedWriteableAwareStreamInput(org.elasticsearch.common.io.stream.NamedWriteableAwareStreamInput) IndicesFieldDataCache(org.elasticsearch.indices.fielddata.cache.IndicesFieldDataCache) CommonStatsFlags(org.elasticsearch.action.admin.indices.stats.CommonStatsFlags) SearchStats(org.elasticsearch.index.search.stats.SearchStats) ScriptService(org.elasticsearch.script.ScriptService) ElasticsearchException(org.elasticsearch.ElasticsearchException) Property(org.elasticsearch.common.settings.Setting.Property) MapperRegistry(org.elasticsearch.indices.mapper.MapperRegistry) Settings(org.elasticsearch.common.settings.Settings) ShardSearchRequest(org.elasticsearch.search.internal.ShardSearchRequest) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) MappedFieldType(org.elasticsearch.index.mapper.MappedFieldType) ThreadPool(org.elasticsearch.threadpool.ThreadPool) NamedXContentRegistry(org.elasticsearch.common.xcontent.NamedXContentRegistry) Releasable(org.elasticsearch.common.lease.Releasable) ByteSizeValue(org.elasticsearch.common.unit.ByteSizeValue) PluginsService(org.elasticsearch.plugins.PluginsService) Setting(org.elasticsearch.common.settings.Setting) Collections.emptyList(java.util.Collections.emptyList) DirectoryReader(org.apache.lucene.index.DirectoryReader) ShardLockObtainFailedException(org.elasticsearch.env.ShardLockObtainFailedException) AnalysisRegistry(org.elasticsearch.index.analysis.AnalysisRegistry) Flag(org.elasticsearch.action.admin.indices.stats.CommonStatsFlags.Flag) BytesReference(org.elasticsearch.common.bytes.BytesReference) IllegalIndexShardStateException(org.elasticsearch.index.shard.IllegalIndexShardStateException) Collectors(java.util.stream.Collectors) MapBuilder.newMapBuilder(org.elasticsearch.common.collect.MapBuilder.newMapBuilder) QueryParseContext(org.elasticsearch.index.query.QueryParseContext) Engine(org.elasticsearch.index.engine.Engine) RamUsageEstimator(org.apache.lucene.util.RamUsageEstimator) MapperService(org.elasticsearch.index.mapper.MapperService) RefreshStats(org.elasticsearch.index.refresh.RefreshStats) List(java.util.List) QuerySearchResult(org.elasticsearch.search.query.QuerySearchResult) IndicesClusterStateService(org.elasticsearch.indices.cluster.IndicesClusterStateService) RecoveryState(org.elasticsearch.indices.recovery.RecoveryState) GetStats(org.elasticsearch.index.get.GetStats) CommonStats(org.elasticsearch.action.admin.indices.stats.CommonStats) FieldStats(org.elasticsearch.action.fieldstats.FieldStats) IndexingOperationListener(org.elasticsearch.index.shard.IndexingOperationListener) ShardRouting(org.elasticsearch.cluster.routing.ShardRouting) XContentType(org.elasticsearch.common.xcontent.XContentType) SearchContext(org.elasticsearch.search.internal.SearchContext) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) MetaStateService(org.elasticsearch.gateway.MetaStateService) Index(org.elasticsearch.index.Index) ParameterizedMessage(org.apache.logging.log4j.message.ParameterizedMessage) ResourceAlreadyExistsException(org.elasticsearch.ResourceAlreadyExistsException) ShardStats(org.elasticsearch.action.admin.indices.stats.ShardStats) TimeValue(org.elasticsearch.common.unit.TimeValue) Iterables(org.elasticsearch.common.util.iterable.Iterables) IndexSettings(org.elasticsearch.index.IndexSettings) ExecutorService(java.util.concurrent.ExecutorService) Collections.emptyMap(java.util.Collections.emptyMap) EsExecutors(org.elasticsearch.common.util.concurrent.EsExecutors) IndexShardState(org.elasticsearch.index.shard.IndexShardState) IndexFieldDataCache(org.elasticsearch.index.fielddata.IndexFieldDataCache) Iterator(java.util.Iterator) AbstractLifecycleComponent(org.elasticsearch.common.component.AbstractLifecycleComponent) IndexScopedSettings(org.elasticsearch.common.settings.IndexScopedSettings) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) ClusterSettings(org.elasticsearch.common.settings.ClusterSettings) NodeEnvironment(org.elasticsearch.env.NodeEnvironment) StreamInput(org.elasticsearch.common.io.stream.StreamInput) Closeable(java.io.Closeable) Collections.unmodifiableMap(java.util.Collections.unmodifiableMap) IndexNameExpressionResolver(org.elasticsearch.cluster.metadata.IndexNameExpressionResolver) AliasFilter(org.elasticsearch.search.internal.AliasFilter) QueryParseContext(org.elasticsearch.index.query.QueryParseContext) QueryBuilder(org.elasticsearch.index.query.QueryBuilder) IOException(java.io.IOException) XContentParser(org.elasticsearch.common.xcontent.XContentParser) IndexMetaData(org.elasticsearch.cluster.metadata.IndexMetaData)

Example 57 with IndexMetaData

use of org.elasticsearch.cluster.metadata.IndexMetaData in project elasticsearch by elastic.

the class SyncedFlushService method attemptSyncedFlush.

/**
     * a utility method to perform a synced flush for all shards of multiple indices. see {@link #attemptSyncedFlush(ShardId, ActionListener)}
     * for more details.
     */
public void attemptSyncedFlush(final String[] aliasesOrIndices, IndicesOptions indicesOptions, final ActionListener<SyncedFlushResponse> listener) {
    final ClusterState state = clusterService.state();
    final Index[] concreteIndices = indexNameExpressionResolver.concreteIndices(state, indicesOptions, aliasesOrIndices);
    final Map<String, List<ShardsSyncedFlushResult>> results = ConcurrentCollections.newConcurrentMap();
    int numberOfShards = 0;
    for (Index index : concreteIndices) {
        final IndexMetaData indexMetaData = state.metaData().getIndexSafe(index);
        numberOfShards += indexMetaData.getNumberOfShards();
        results.put(index.getName(), Collections.synchronizedList(new ArrayList<>()));
    }
    if (numberOfShards == 0) {
        listener.onResponse(new SyncedFlushResponse(results));
        return;
    }
    final CountDown countDown = new CountDown(numberOfShards);
    for (final Index concreteIndex : concreteIndices) {
        final String index = concreteIndex.getName();
        final IndexMetaData indexMetaData = state.metaData().getIndexSafe(concreteIndex);
        final int indexNumberOfShards = indexMetaData.getNumberOfShards();
        for (int shard = 0; shard < indexNumberOfShards; shard++) {
            final ShardId shardId = new ShardId(indexMetaData.getIndex(), shard);
            innerAttemptSyncedFlush(shardId, state, new ActionListener<ShardsSyncedFlushResult>() {

                @Override
                public void onResponse(ShardsSyncedFlushResult syncedFlushResult) {
                    results.get(index).add(syncedFlushResult);
                    if (countDown.countDown()) {
                        listener.onResponse(new SyncedFlushResponse(results));
                    }
                }

                @Override
                public void onFailure(Exception e) {
                    logger.debug("{} unexpected error while executing synced flush", shardId);
                    final int totalShards = indexMetaData.getNumberOfReplicas() + 1;
                    results.get(index).add(new ShardsSyncedFlushResult(shardId, totalShards, e.getMessage()));
                    if (countDown.countDown()) {
                        listener.onResponse(new SyncedFlushResponse(results));
                    }
                }
            });
        }
    }
}
Also used : ClusterState(org.elasticsearch.cluster.ClusterState) ArrayList(java.util.ArrayList) Index(org.elasticsearch.index.Index) CountDown(org.elasticsearch.common.util.concurrent.CountDown) ElasticsearchException(org.elasticsearch.ElasticsearchException) IndexClosedException(org.elasticsearch.indices.IndexClosedException) ShardNotFoundException(org.elasticsearch.index.shard.ShardNotFoundException) IndexNotFoundException(org.elasticsearch.index.IndexNotFoundException) IOException(java.io.IOException) TransportException(org.elasticsearch.transport.TransportException) IndexMetaData(org.elasticsearch.cluster.metadata.IndexMetaData) ShardId(org.elasticsearch.index.shard.ShardId) SyncedFlushResponse(org.elasticsearch.action.admin.indices.flush.SyncedFlushResponse) ArrayList(java.util.ArrayList) List(java.util.List)

Example 58 with IndexMetaData

use of org.elasticsearch.cluster.metadata.IndexMetaData in project elasticsearch by elastic.

the class StoreRecovery method recoverFromLocalShards.

boolean recoverFromLocalShards(BiConsumer<String, MappingMetaData> mappingUpdateConsumer, final IndexShard indexShard, final List<LocalShardSnapshot> shards) throws IOException {
    if (canRecover(indexShard)) {
        RecoverySource.Type recoveryType = indexShard.recoveryState().getRecoverySource().getType();
        assert recoveryType == RecoverySource.Type.LOCAL_SHARDS : "expected local shards recovery type: " + recoveryType;
        if (shards.isEmpty()) {
            throw new IllegalArgumentException("shards must not be empty");
        }
        Set<Index> indices = shards.stream().map((s) -> s.getIndex()).collect(Collectors.toSet());
        if (indices.size() > 1) {
            throw new IllegalArgumentException("can't add shards from more than one index");
        }
        IndexMetaData indexMetaData = shards.get(0).getIndexMetaData();
        for (ObjectObjectCursor<String, MappingMetaData> mapping : indexMetaData.getMappings()) {
            mappingUpdateConsumer.accept(mapping.key, mapping.value);
        }
        indexShard.mapperService().merge(indexMetaData, MapperService.MergeReason.MAPPING_RECOVERY, true);
        return executeRecovery(indexShard, () -> {
            logger.debug("starting recovery from local shards {}", shards);
            try {
                // don't close this directory!!
                final Directory directory = indexShard.store().directory();
                addIndices(indexShard.recoveryState().getIndex(), directory, shards.stream().map(s -> s.getSnapshotDirectory()).collect(Collectors.toList()).toArray(new Directory[shards.size()]));
                internalRecoverFromStore(indexShard);
                // just trigger a merge to do housekeeping on the
                // copied segments - we will also see them in stats etc.
                indexShard.getEngine().forceMerge(false, -1, false, false, false);
            } catch (IOException ex) {
                throw new IndexShardRecoveryException(indexShard.shardId(), "failed to recover from local shards", ex);
            }
        });
    }
    return false;
}
Also used : NoMergePolicy(org.apache.lucene.index.NoMergePolicy) Arrays(java.util.Arrays) MappingMetaData(org.elasticsearch.cluster.metadata.MappingMetaData) SnapshotRecoverySource(org.elasticsearch.cluster.routing.RecoverySource.SnapshotRecoverySource) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Index(org.elasticsearch.index.Index) Lucene(org.elasticsearch.common.lucene.Lucene) IndexId(org.elasticsearch.repositories.IndexId) ObjectObjectCursor(com.carrotsearch.hppc.cursors.ObjectObjectCursor) IndexRequest(org.elasticsearch.action.index.IndexRequest) Directory(org.apache.lucene.store.Directory) TimeValue(org.elasticsearch.common.unit.TimeValue) Store(org.elasticsearch.index.store.Store) BiConsumer(java.util.function.BiConsumer) TimeValue.timeValueMillis(org.elasticsearch.common.unit.TimeValue.timeValueMillis) IndexShardRestoreFailedException(org.elasticsearch.index.snapshots.IndexShardRestoreFailedException) IOContext(org.apache.lucene.store.IOContext) EngineException(org.elasticsearch.index.engine.EngineException) ByteSizeValue(org.elasticsearch.common.unit.ByteSizeValue) Repository(org.elasticsearch.repositories.Repository) IndexInput(org.apache.lucene.store.IndexInput) Set(java.util.Set) IOException(java.io.IOException) Collectors(java.util.stream.Collectors) SegmentInfos(org.apache.lucene.index.SegmentInfos) ExceptionsHelper(org.elasticsearch.ExceptionsHelper) RecoverySource(org.elasticsearch.cluster.routing.RecoverySource) MapperService(org.elasticsearch.index.mapper.MapperService) IndexWriter(org.apache.lucene.index.IndexWriter) List(java.util.List) Logger(org.apache.logging.log4j.Logger) FilterDirectory(org.apache.lucene.store.FilterDirectory) IndexMetaData(org.elasticsearch.cluster.metadata.IndexMetaData) RecoveryState(org.elasticsearch.indices.recovery.RecoveryState) IndexWriterConfig(org.apache.lucene.index.IndexWriterConfig) Index(org.elasticsearch.index.Index) IOException(java.io.IOException) MappingMetaData(org.elasticsearch.cluster.metadata.MappingMetaData) SnapshotRecoverySource(org.elasticsearch.cluster.routing.RecoverySource.SnapshotRecoverySource) RecoverySource(org.elasticsearch.cluster.routing.RecoverySource) IndexMetaData(org.elasticsearch.cluster.metadata.IndexMetaData) Directory(org.apache.lucene.store.Directory) FilterDirectory(org.apache.lucene.store.FilterDirectory)

Example 59 with IndexMetaData

use of org.elasticsearch.cluster.metadata.IndexMetaData in project elasticsearch by elastic.

the class TransportShardBulkActionTests method testExecuteBulkDeleteRequest.

public void testExecuteBulkDeleteRequest() throws Exception {
    IndexMetaData metaData = indexMetaData();
    IndexShard shard = newStartedShard(true);
    BulkItemRequest[] items = new BulkItemRequest[1];
    DocWriteRequest writeRequest = new DeleteRequest("index", "type", "id");
    items[0] = new BulkItemRequest(0, writeRequest);
    BulkShardRequest bulkShardRequest = new BulkShardRequest(shardId, RefreshPolicy.NONE, items);
    Translog.Location location = new Translog.Location(0, 0, 0);
    UpdateHelper updateHelper = null;
    Translog.Location newLocation = TransportShardBulkAction.executeBulkItemRequest(metaData, shard, bulkShardRequest, location, 0, updateHelper, threadPool::absoluteTimeInMillis, new NoopMappingUpdatePerformer());
    // Translog changes, even though the document didn't exist
    assertThat(newLocation, not(location));
    BulkItemRequest replicaRequest = bulkShardRequest.items()[0];
    DocWriteRequest replicaDeleteRequest = replicaRequest.request();
    BulkItemResponse primaryResponse = replicaRequest.getPrimaryResponse();
    DeleteResponse response = primaryResponse.getResponse();
    // Any version can be matched on replica
    assertThat(replicaDeleteRequest.version(), equalTo(Versions.MATCH_ANY));
    assertThat(replicaDeleteRequest.versionType(), equalTo(VersionType.INTERNAL));
    assertThat(primaryResponse.getItemId(), equalTo(0));
    assertThat(primaryResponse.getId(), equalTo("id"));
    assertThat(primaryResponse.getOpType(), equalTo(DocWriteRequest.OpType.DELETE));
    assertFalse(primaryResponse.isFailed());
    assertThat(response.getResult(), equalTo(DocWriteResponse.Result.NOT_FOUND));
    assertThat(response.getShardId(), equalTo(shard.shardId()));
    assertThat(response.getIndex(), equalTo("index"));
    assertThat(response.getType(), equalTo("type"));
    assertThat(response.getId(), equalTo("id"));
    assertThat(response.getVersion(), equalTo(1L));
    assertThat(response.getSeqNo(), equalTo(0L));
    assertThat(response.forcedRefresh(), equalTo(false));
    // Now do the same after indexing the document, it should now find and delete the document
    indexDoc(shard, "type", "id", "{\"foo\": \"bar\"}");
    writeRequest = new DeleteRequest("index", "type", "id");
    items[0] = new BulkItemRequest(0, writeRequest);
    bulkShardRequest = new BulkShardRequest(shardId, RefreshPolicy.NONE, items);
    location = newLocation;
    newLocation = TransportShardBulkAction.executeBulkItemRequest(metaData, shard, bulkShardRequest, location, 0, updateHelper, threadPool::absoluteTimeInMillis, new NoopMappingUpdatePerformer());
    // Translog changes, because the document was deleted
    assertThat(newLocation, not(location));
    replicaRequest = bulkShardRequest.items()[0];
    replicaDeleteRequest = replicaRequest.request();
    primaryResponse = replicaRequest.getPrimaryResponse();
    response = primaryResponse.getResponse();
    // Any version can be matched on replica
    assertThat(replicaDeleteRequest.version(), equalTo(Versions.MATCH_ANY));
    assertThat(replicaDeleteRequest.versionType(), equalTo(VersionType.INTERNAL));
    assertThat(primaryResponse.getItemId(), equalTo(0));
    assertThat(primaryResponse.getId(), equalTo("id"));
    assertThat(primaryResponse.getOpType(), equalTo(DocWriteRequest.OpType.DELETE));
    assertFalse(primaryResponse.isFailed());
    assertThat(response.getResult(), equalTo(DocWriteResponse.Result.DELETED));
    assertThat(response.getShardId(), equalTo(shard.shardId()));
    assertThat(response.getIndex(), equalTo("index"));
    assertThat(response.getType(), equalTo("type"));
    assertThat(response.getId(), equalTo("id"));
    assertThat(response.getVersion(), equalTo(3L));
    assertThat(response.getSeqNo(), equalTo(2L));
    assertThat(response.forcedRefresh(), equalTo(false));
    assertDocCount(shard, 0);
    closeShards(shard);
}
Also used : IndexShard(org.elasticsearch.index.shard.IndexShard) IndexMetaData(org.elasticsearch.cluster.metadata.IndexMetaData) Translog(org.elasticsearch.index.translog.Translog) UpdateHelper(org.elasticsearch.action.update.UpdateHelper) DeleteResponse(org.elasticsearch.action.delete.DeleteResponse) DocWriteRequest(org.elasticsearch.action.DocWriteRequest) DeleteRequest(org.elasticsearch.action.delete.DeleteRequest)

Example 60 with IndexMetaData

use of org.elasticsearch.cluster.metadata.IndexMetaData in project elasticsearch by elastic.

the class TransportShardBulkActionTests method testExecuteBulkIndexRequest.

public void testExecuteBulkIndexRequest() throws Exception {
    IndexMetaData metaData = indexMetaData();
    IndexShard shard = newStartedShard(true);
    BulkItemRequest[] items = new BulkItemRequest[1];
    boolean create = randomBoolean();
    DocWriteRequest writeRequest = new IndexRequest("index", "type", "id").source(Requests.INDEX_CONTENT_TYPE, "foo", "bar").create(create);
    BulkItemRequest primaryRequest = new BulkItemRequest(0, writeRequest);
    items[0] = primaryRequest;
    BulkShardRequest bulkShardRequest = new BulkShardRequest(shardId, RefreshPolicy.NONE, items);
    Translog.Location location = new Translog.Location(0, 0, 0);
    UpdateHelper updateHelper = null;
    Translog.Location newLocation = TransportShardBulkAction.executeBulkItemRequest(metaData, shard, bulkShardRequest, location, 0, updateHelper, threadPool::absoluteTimeInMillis, new NoopMappingUpdatePerformer());
    // Translog should change, since there were no problems
    assertThat(newLocation, not(location));
    BulkItemResponse primaryResponse = bulkShardRequest.items()[0].getPrimaryResponse();
    assertThat(primaryResponse.getItemId(), equalTo(0));
    assertThat(primaryResponse.getId(), equalTo("id"));
    assertThat(primaryResponse.getOpType(), equalTo(create ? DocWriteRequest.OpType.CREATE : DocWriteRequest.OpType.INDEX));
    assertFalse(primaryResponse.isFailed());
    // Assert that the document actually made it there
    assertDocCount(shard, 1);
    writeRequest = new IndexRequest("index", "type", "id").source(Requests.INDEX_CONTENT_TYPE, "foo", "bar").create(true);
    primaryRequest = new BulkItemRequest(0, writeRequest);
    items[0] = primaryRequest;
    bulkShardRequest = new BulkShardRequest(shardId, RefreshPolicy.NONE, items);
    Translog.Location secondLocation = TransportShardBulkAction.executeBulkItemRequest(metaData, shard, bulkShardRequest, newLocation, 0, updateHelper, threadPool::absoluteTimeInMillis, new NoopMappingUpdatePerformer());
    // Translog should not change, since the document was not indexed due to a version conflict
    assertThat(secondLocation, equalTo(newLocation));
    BulkItemRequest replicaRequest = bulkShardRequest.items()[0];
    primaryResponse = bulkShardRequest.items()[0].getPrimaryResponse();
    assertThat(primaryResponse.getItemId(), equalTo(0));
    assertThat(primaryResponse.getId(), equalTo("id"));
    assertThat(primaryResponse.getOpType(), equalTo(DocWriteRequest.OpType.CREATE));
    // Should be failed since the document already exists
    assertTrue(primaryResponse.isFailed());
    BulkItemResponse.Failure failure = primaryResponse.getFailure();
    assertThat(failure.getIndex(), equalTo("index"));
    assertThat(failure.getType(), equalTo("type"));
    assertThat(failure.getId(), equalTo("id"));
    assertThat(failure.getCause().getClass(), equalTo(VersionConflictEngineException.class));
    assertThat(failure.getCause().getMessage(), containsString("version conflict, document already exists (current version [1])"));
    assertThat(failure.getStatus(), equalTo(RestStatus.CONFLICT));
    assertThat(replicaRequest, equalTo(primaryRequest));
    // Assert that the document count is still 1
    assertDocCount(shard, 1);
    closeShards(shard);
}
Also used : IndexShard(org.elasticsearch.index.shard.IndexShard) IndexRequest(org.elasticsearch.action.index.IndexRequest) IndexMetaData(org.elasticsearch.cluster.metadata.IndexMetaData) Translog(org.elasticsearch.index.translog.Translog) UpdateHelper(org.elasticsearch.action.update.UpdateHelper) VersionConflictEngineException(org.elasticsearch.index.engine.VersionConflictEngineException) DocWriteRequest(org.elasticsearch.action.DocWriteRequest)

Aggregations

IndexMetaData (org.elasticsearch.cluster.metadata.IndexMetaData)253 IndexMetadata (org.elasticsearch.cluster.metadata.IndexMetadata)194 ClusterState (org.elasticsearch.cluster.ClusterState)124 Settings (org.elasticsearch.common.settings.Settings)104 Index (org.elasticsearch.index.Index)100 Test (org.junit.Test)90 ShardId (org.elasticsearch.index.shard.ShardId)71 ShardRouting (org.elasticsearch.cluster.routing.ShardRouting)68 IOException (java.io.IOException)65 Metadata (org.elasticsearch.cluster.metadata.Metadata)62 IndexSettings (org.elasticsearch.index.IndexSettings)62 RoutingTable (org.elasticsearch.cluster.routing.RoutingTable)60 MetaData (org.elasticsearch.cluster.metadata.MetaData)58 HashSet (java.util.HashSet)56 HashMap (java.util.HashMap)54 IndexShardRoutingTable (org.elasticsearch.cluster.routing.IndexShardRoutingTable)54 Map (java.util.Map)50 XContentBuilder (org.elasticsearch.common.xcontent.XContentBuilder)49 ArrayList (java.util.ArrayList)47 DiscoveryNode (org.elasticsearch.cluster.node.DiscoveryNode)44