Search in sources :

Example 1 with Uid

use of org.elasticsearch.index.mapper.Uid in project elasticsearch by elastic.

the class IndexShardTestCase method getShardDocUIDs.

protected Set<Uid> getShardDocUIDs(final IndexShard shard) throws IOException {
    shard.refresh("get_uids");
    try (Engine.Searcher searcher = shard.acquireSearcher("test")) {
        Set<Uid> ids = new HashSet<>();
        for (LeafReaderContext leafContext : searcher.reader().leaves()) {
            LeafReader reader = leafContext.reader();
            Bits liveDocs = reader.getLiveDocs();
            for (int i = 0; i < reader.maxDoc(); i++) {
                if (liveDocs == null || liveDocs.get(i)) {
                    Document uuid = reader.document(i, Collections.singleton(UidFieldMapper.NAME));
                    ids.add(Uid.createUid(uuid.get(UidFieldMapper.NAME)));
                }
            }
        }
        return ids;
    }
}
Also used : Uid(org.elasticsearch.index.mapper.Uid) LeafReader(org.apache.lucene.index.LeafReader) LeafReaderContext(org.apache.lucene.index.LeafReaderContext) Bits(org.apache.lucene.util.Bits) Document(org.apache.lucene.document.Document) Engine(org.elasticsearch.index.engine.Engine) HashSet(java.util.HashSet)

Example 2 with Uid

use of org.elasticsearch.index.mapper.Uid in project crate by crate.

the class InternalEngineTests method testRebuildLocalCheckpointTrackerAndVersionMap.

@Test
public void testRebuildLocalCheckpointTrackerAndVersionMap() throws Exception {
    Settings.Builder settings = Settings.builder().put(defaultSettings.getSettings()).put(IndexSettings.INDEX_SOFT_DELETES_RETENTION_OPERATIONS_SETTING.getKey(), 10000).put(IndexSettings.INDEX_SOFT_DELETES_SETTING.getKey(), true);
    final IndexMetadata indexMetadata = IndexMetadata.builder(defaultSettings.getIndexMetadata()).settings(settings).build();
    final IndexSettings indexSettings = IndexSettingsModule.newIndexSettings(indexMetadata);
    final AtomicLong globalCheckpoint = new AtomicLong(SequenceNumbers.NO_OPS_PERFORMED);
    Path translogPath = createTempDir();
    List<Engine.Operation> operations = generateHistoryOnReplica(between(1, 500), randomBoolean(), randomBoolean());
    List<List<Engine.Operation>> commits = new ArrayList<>();
    commits.add(new ArrayList<>());
    try (Store store = createStore()) {
        EngineConfig config = config(indexSettings, store, translogPath, NoMergePolicy.INSTANCE, null, null, globalCheckpoint::get);
        final List<DocIdSeqNoAndSource> docs;
        try (InternalEngine engine = createEngine(config)) {
            List<Engine.Operation> flushedOperations = new ArrayList<>();
            for (Engine.Operation op : operations) {
                flushedOperations.add(op);
                applyOperation(engine, op);
                if (randomBoolean()) {
                    engine.syncTranslog();
                    globalCheckpoint.set(randomLongBetween(globalCheckpoint.get(), engine.getPersistedLocalCheckpoint()));
                }
                if (randomInt(100) < 10) {
                    engine.refresh("test");
                }
                if (randomInt(100) < 5) {
                    engine.flush(true, true);
                    flushedOperations.sort(Comparator.comparing(Engine.Operation::seqNo));
                    commits.add(new ArrayList<>(flushedOperations));
                }
            }
            docs = getDocIds(engine, true);
        }
        List<Engine.Operation> operationsInSafeCommit = null;
        for (int i = commits.size() - 1; i >= 0; i--) {
            if (commits.get(i).stream().allMatch(op -> op.seqNo() <= globalCheckpoint.get())) {
                operationsInSafeCommit = commits.get(i);
                break;
            }
        }
        assertThat(operationsInSafeCommit, notNullValue());
        try (InternalEngine engine = new InternalEngine(config)) {
            // do not recover from translog
            final Map<BytesRef, Engine.Operation> deletesAfterCheckpoint = new HashMap<>();
            for (Engine.Operation op : operationsInSafeCommit) {
                if (op instanceof Engine.NoOp == false && op.seqNo() > engine.getPersistedLocalCheckpoint()) {
                    deletesAfterCheckpoint.put(new Term(IdFieldMapper.NAME, Uid.encodeId(op.id())).bytes(), op);
                }
            }
            deletesAfterCheckpoint.values().removeIf(o -> o instanceof Engine.Delete == false);
            final Map<BytesRef, VersionValue> versionMap = engine.getVersionMap();
            for (BytesRef uid : deletesAfterCheckpoint.keySet()) {
                final VersionValue versionValue = versionMap.get(uid);
                final Engine.Operation op = deletesAfterCheckpoint.get(uid);
                final String msg = versionValue + " vs " + "op[" + op.operationType() + "id=" + op.id() + " seqno=" + op.seqNo() + " term=" + op.primaryTerm() + "]";
                assertThat(versionValue, instanceOf(DeleteVersionValue.class));
                assertThat(msg, versionValue.seqNo, equalTo(op.seqNo()));
                assertThat(msg, versionValue.term, equalTo(op.primaryTerm()));
                assertThat(msg, versionValue.version, equalTo(op.version()));
            }
            assertThat(versionMap.keySet(), equalTo(deletesAfterCheckpoint.keySet()));
            final LocalCheckpointTracker tracker = engine.getLocalCheckpointTracker();
            final Set<Long> seqNosInSafeCommit = operationsInSafeCommit.stream().map(op -> op.seqNo()).collect(Collectors.toSet());
            for (Engine.Operation op : operations) {
                assertThat("seq_no=" + op.seqNo() + " max_seq_no=" + tracker.getMaxSeqNo() + " checkpoint=" + tracker.getProcessedCheckpoint(), tracker.hasProcessed(op.seqNo()), equalTo(seqNosInSafeCommit.contains(op.seqNo())));
            }
            engine.recoverFromTranslog(translogHandler, Long.MAX_VALUE);
            assertThat(getDocIds(engine, true), equalTo(docs));
        }
    }
}
Also used : ShardId(org.elasticsearch.index.shard.ShardId) NoMergePolicy(org.apache.lucene.index.NoMergePolicy) Arrays(java.util.Arrays) Versions(org.elasticsearch.common.lucene.uid.Versions) LongSupplier(java.util.function.LongSupplier) PEER_RECOVERY(org.elasticsearch.index.engine.Engine.Operation.Origin.PEER_RECOVERY) BigArrays(org.elasticsearch.common.util.BigArrays) IndexSettingsModule(org.elasticsearch.test.IndexSettingsModule) IndexMetadata(org.elasticsearch.cluster.metadata.IndexMetadata) Matchers.not(org.hamcrest.Matchers.not) Term(org.apache.lucene.index.Term) Level(org.apache.logging.log4j.Level) AlreadyClosedException(org.apache.lucene.store.AlreadyClosedException) ElasticsearchDirectoryReader(org.elasticsearch.common.lucene.index.ElasticsearchDirectoryReader) LogEvent(org.apache.logging.log4j.core.LogEvent) ReferenceManager(org.apache.lucene.search.ReferenceManager) ParseContext(org.elasticsearch.index.mapper.ParseContext) CoreMatchers.instanceOf(org.hamcrest.CoreMatchers.instanceOf) SeqNoStats(org.elasticsearch.index.seqno.SeqNoStats) LOCAL_TRANSLOG_RECOVERY(org.elasticsearch.index.engine.Engine.Operation.Origin.LOCAL_TRANSLOG_RECOVERY) RandomNumbers(com.carrotsearch.randomizedtesting.generators.RandomNumbers) MergePolicy(org.apache.lucene.index.MergePolicy) TermsEnum(org.apache.lucene.index.TermsEnum) Matchers.nullValue(org.hamcrest.Matchers.nullValue) Map(java.util.Map) TestTranslog(org.elasticsearch.index.translog.TestTranslog) CheckedRunnable(org.elasticsearch.common.CheckedRunnable) FieldsVisitor(org.elasticsearch.index.fieldvisitor.FieldsVisitor) Path(java.nio.file.Path) REPLICA(org.elasticsearch.index.engine.Engine.Operation.Origin.REPLICA) NumericDocValuesField(org.apache.lucene.document.NumericDocValuesField) Matchers.notNullValue(org.hamcrest.Matchers.notNullValue) SoftDeletesRetentionMergePolicy(org.apache.lucene.index.SoftDeletesRetentionMergePolicy) UUIDs(org.elasticsearch.common.UUIDs) Set(java.util.Set) MatchAllDocsQuery(org.apache.lucene.search.MatchAllDocsQuery) SnapshotMatchers(org.elasticsearch.index.translog.SnapshotMatchers) UncheckedIOException(java.io.UncheckedIOException) PointValues(org.apache.lucene.index.PointValues) CountDownLatch(java.util.concurrent.CountDownLatch) SeqNoFieldMapper(org.elasticsearch.index.mapper.SeqNoFieldMapper) AbstractRunnable(org.elasticsearch.common.util.concurrent.AbstractRunnable) Logger(org.apache.logging.log4j.Logger) Matchers.contains(org.hamcrest.Matchers.contains) Matchers.greaterThan(org.hamcrest.Matchers.greaterThan) ReplicationTracker(org.elasticsearch.index.seqno.ReplicationTracker) Matchers.containsString(org.hamcrest.Matchers.containsString) TestShardRouting(org.elasticsearch.cluster.routing.TestShardRouting) IndexCommit(org.apache.lucene.index.IndexCommit) Tuple(io.crate.common.collections.Tuple) LiveIndexWriterConfig(org.apache.lucene.index.LiveIndexWriterConfig) LogDocMergePolicy(org.apache.lucene.index.LogDocMergePolicy) FixedBitSet(org.apache.lucene.util.FixedBitSet) RegexFilter(org.apache.logging.log4j.core.filter.RegexFilter) CodecService(org.elasticsearch.index.codec.CodecService) Mockito.spy(org.mockito.Mockito.spy) ShardRoutingState(org.elasticsearch.cluster.routing.ShardRoutingState) Supplier(java.util.function.Supplier) CheckedBiConsumer(org.elasticsearch.common.CheckedBiConsumer) ArrayList(java.util.ArrayList) LinkedHashMap(java.util.LinkedHashMap) ToLongBiFunction(java.util.function.ToLongBiFunction) BytesArray(org.elasticsearch.common.bytes.BytesArray) RetentionLease(org.elasticsearch.index.seqno.RetentionLease) RetentionLeases(org.elasticsearch.index.seqno.RetentionLeases) Lock(org.apache.lucene.store.Lock) Store(org.elasticsearch.index.store.Store) Matchers.hasSize(org.hamcrest.Matchers.hasSize) Matchers.isIn(org.hamcrest.Matchers.isIn) Bits(org.apache.lucene.util.Bits) TranslogConfig(org.elasticsearch.index.translog.TranslogConfig) TieredMergePolicy(org.apache.lucene.index.TieredMergePolicy) Loggers(org.elasticsearch.common.logging.Loggers) TopDocs(org.apache.lucene.search.TopDocs) Matchers.greaterThanOrEqualTo(org.hamcrest.Matchers.greaterThanOrEqualTo) LongStream(java.util.stream.LongStream) SequenceNumbers(org.elasticsearch.index.seqno.SequenceNumbers) Files(java.nio.file.Files) IdFieldMapper(org.elasticsearch.index.mapper.IdFieldMapper) AbstractAppender(org.apache.logging.log4j.core.appender.AbstractAppender) DocIdAndSeqNo(org.elasticsearch.common.lucene.uid.VersionsAndSeqNoResolver.DocIdAndSeqNo) IOUtils(io.crate.common.io.IOUtils) SequentialStoredFieldsLeafReader(org.elasticsearch.common.lucene.index.SequentialStoredFieldsLeafReader) IOException(java.io.IOException) BrokenBarrierException(java.util.concurrent.BrokenBarrierException) Test(org.junit.Test) ParsedDocument(org.elasticsearch.index.mapper.ParsedDocument) AtomicLong(java.util.concurrent.atomic.AtomicLong) SourceFieldMapper(org.elasticsearch.index.mapper.SourceFieldMapper) VersionFieldMapper(org.elasticsearch.index.mapper.VersionFieldMapper) Matchers.hasItem(org.hamcrest.Matchers.hasItem) Matchers.sameInstance(org.hamcrest.Matchers.sameInstance) Phaser(java.util.concurrent.Phaser) Matcher(org.hamcrest.Matcher) TextField(org.apache.lucene.document.TextField) TranslogDeletionPolicies.createTranslogDeletionPolicy(org.elasticsearch.index.translog.TranslogDeletionPolicies.createTranslogDeletionPolicy) Lucene87StoredFieldsFormat(org.apache.lucene.codecs.lucene87.Lucene87StoredFieldsFormat) ActionListener(org.elasticsearch.action.ActionListener) Randomness(org.elasticsearch.common.Randomness) Collections.shuffle(java.util.Collections.shuffle) CoreMatchers.is(org.hamcrest.CoreMatchers.is) ElasticsearchException(org.elasticsearch.ElasticsearchException) BiFunction(java.util.function.BiFunction) IndexableField(org.apache.lucene.index.IndexableField) ConcurrentCollections(org.elasticsearch.common.util.concurrent.ConcurrentCollections) StoredField(org.apache.lucene.document.StoredField) Matchers.hasKey(org.hamcrest.Matchers.hasKey) VersionType(org.elasticsearch.index.VersionType) Settings(org.elasticsearch.common.settings.Settings) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Directory(org.apache.lucene.store.Directory) ThreadPool(org.elasticsearch.threadpool.ThreadPool) LeafReaderContext(org.apache.lucene.index.LeafReaderContext) ShardUtils(org.elasticsearch.index.shard.ShardUtils) TotalHitCountCollector(org.apache.lucene.search.TotalHitCountCollector) ByteSizeValue(org.elasticsearch.common.unit.ByteSizeValue) CyclicBarrier(java.util.concurrent.CyclicBarrier) Terms(org.apache.lucene.index.Terms) Matchers.lessThanOrEqualTo(org.hamcrest.Matchers.lessThanOrEqualTo) BytesRef(org.apache.lucene.util.BytesRef) DirectoryReader(org.apache.lucene.index.DirectoryReader) UNASSIGNED_PRIMARY_TERM(org.elasticsearch.index.seqno.SequenceNumbers.UNASSIGNED_PRIMARY_TERM) UNASSIGNED_SEQ_NO(org.elasticsearch.index.seqno.SequenceNumbers.UNASSIGNED_SEQ_NO) IndexShardRoutingTable(org.elasticsearch.cluster.routing.IndexShardRoutingTable) BytesReference(org.elasticsearch.common.bytes.BytesReference) Collectors(java.util.stream.Collectors) SegmentInfos(org.apache.lucene.index.SegmentInfos) Searcher(org.elasticsearch.index.engine.Engine.Searcher) MapperService(org.elasticsearch.index.mapper.MapperService) Base64(java.util.Base64) List(java.util.List) IndexWriter(org.apache.lucene.index.IndexWriter) Version(org.elasticsearch.Version) MatcherAssert(org.hamcrest.MatcherAssert) Matchers.containsInAnyOrder(org.hamcrest.Matchers.containsInAnyOrder) TriFunction(org.elasticsearch.common.TriFunction) Matchers.equalTo(org.hamcrest.Matchers.equalTo) LeafReader(org.apache.lucene.index.LeafReader) TimeValue(io.crate.common.unit.TimeValue) Queue(java.util.Queue) IndexWriterConfig(org.apache.lucene.index.IndexWriterConfig) LogByteSizeMergePolicy(org.apache.lucene.index.LogByteSizeMergePolicy) MockDirectoryWrapper(org.apache.lucene.store.MockDirectoryWrapper) IndexReader(org.apache.lucene.index.IndexReader) IndexSearcher(org.apache.lucene.search.IndexSearcher) ShardRouting(org.elasticsearch.cluster.routing.ShardRouting) LongPoint(org.apache.lucene.document.LongPoint) NumericDocValues(org.apache.lucene.index.NumericDocValues) PRIMARY(org.elasticsearch.index.engine.Engine.Operation.Origin.PRIMARY) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Document(org.elasticsearch.index.mapper.ParseContext.Document) HashMap(java.util.HashMap) VersionsAndSeqNoResolver(org.elasticsearch.common.lucene.uid.VersionsAndSeqNoResolver) Lucene(org.elasticsearch.common.lucene.Lucene) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) TransportActions(org.elasticsearch.action.support.TransportActions) Strings(org.elasticsearch.common.Strings) HashSet(java.util.HashSet) LOCAL_RESET(org.elasticsearch.index.engine.Engine.Operation.Origin.LOCAL_RESET) Charset(java.nio.charset.Charset) NoneCircuitBreakerService(org.elasticsearch.indices.breaker.NoneCircuitBreakerService) IndexSettings(org.elasticsearch.index.IndexSettings) LocalCheckpointTracker(org.elasticsearch.index.seqno.LocalCheckpointTracker) IntSupplier(java.util.function.IntSupplier) Matchers.empty(org.hamcrest.Matchers.empty) Iterator(java.util.Iterator) Uid(org.elasticsearch.index.mapper.Uid) Matchers(org.hamcrest.Matchers) Mockito.when(org.mockito.Mockito.when) VersionUtils(org.elasticsearch.test.VersionUtils) TimeUnit(java.util.concurrent.TimeUnit) TermQuery(org.apache.lucene.search.TermQuery) NO_OPS_PERFORMED(org.elasticsearch.index.seqno.SequenceNumbers.NO_OPS_PERFORMED) Field(org.apache.lucene.document.Field) Closeable(java.io.Closeable) Translog(org.elasticsearch.index.translog.Translog) Comparator(java.util.Comparator) Collections(java.util.Collections) LogManager(org.apache.logging.log4j.LogManager) LinkedHashMap(java.util.LinkedHashMap) HashMap(java.util.HashMap) IndexSettings(org.elasticsearch.index.IndexSettings) ArrayList(java.util.ArrayList) Store(org.elasticsearch.index.store.Store) Matchers.containsString(org.hamcrest.Matchers.containsString) LocalCheckpointTracker(org.elasticsearch.index.seqno.LocalCheckpointTracker) ArrayList(java.util.ArrayList) List(java.util.List) IndexMetadata(org.elasticsearch.cluster.metadata.IndexMetadata) Settings(org.elasticsearch.common.settings.Settings) IndexSettings(org.elasticsearch.index.IndexSettings) BytesRef(org.apache.lucene.util.BytesRef) Path(java.nio.file.Path) Term(org.apache.lucene.index.Term) LongPoint(org.apache.lucene.document.LongPoint) AtomicLong(java.util.concurrent.atomic.AtomicLong) AtomicLong(java.util.concurrent.atomic.AtomicLong) Test(org.junit.Test)

Example 3 with Uid

use of org.elasticsearch.index.mapper.Uid in project elasticsearch by elastic.

the class TranslogRecoveryPerformer method performRecoveryOperation.

/**
     * Performs a single recovery operation.
     *
     * @param allowMappingUpdates true if mapping update should be accepted (but collected). Setting it to false will
     *                            cause a {@link MapperException} to be thrown if an update
     *                            is encountered.
     */
private void performRecoveryOperation(Engine engine, Translog.Operation operation, boolean allowMappingUpdates, Engine.Operation.Origin origin) throws IOException {
    try {
        switch(operation.opType()) {
            case INDEX:
                Translog.Index index = (Translog.Index) operation;
                // we set canHaveDuplicates to true all the time such that we de-optimze the translog case and ensure that all
                // autoGeneratedID docs that are coming from the primary are updated correctly.
                Engine.Index engineIndex = IndexShard.prepareIndex(docMapper(index.type()), source(shardId.getIndexName(), index.type(), index.id(), index.source(), XContentFactory.xContentType(index.source())).routing(index.routing()).parent(index.parent()), index.seqNo(), index.primaryTerm(), index.version(), index.versionType().versionTypeForReplicationAndRecovery(), origin, index.getAutoGeneratedIdTimestamp(), true);
                maybeAddMappingUpdate(engineIndex.type(), engineIndex.parsedDoc().dynamicMappingsUpdate(), engineIndex.id(), allowMappingUpdates);
                logger.trace("[translog] recover [index] op [({}, {})] of [{}][{}]", index.seqNo(), index.primaryTerm(), index.type(), index.id());
                index(engine, engineIndex);
                break;
            case DELETE:
                Translog.Delete delete = (Translog.Delete) operation;
                Uid uid = Uid.createUid(delete.uid().text());
                logger.trace("[translog] recover [delete] op [({}, {})] of [{}][{}]", delete.seqNo(), delete.primaryTerm(), uid.type(), uid.id());
                final Engine.Delete engineDelete = new Engine.Delete(uid.type(), uid.id(), delete.uid(), delete.seqNo(), delete.primaryTerm(), delete.version(), delete.versionType().versionTypeForReplicationAndRecovery(), origin, System.nanoTime());
                delete(engine, engineDelete);
                break;
            case NO_OP:
                final Translog.NoOp noOp = (Translog.NoOp) operation;
                final long seqNo = noOp.seqNo();
                final long primaryTerm = noOp.primaryTerm();
                final String reason = noOp.reason();
                logger.trace("[translog] recover [no_op] op [({}, {})] of [{}]", seqNo, primaryTerm, reason);
                final Engine.NoOp engineNoOp = new Engine.NoOp(null, seqNo, primaryTerm, 0, VersionType.INTERNAL, origin, System.nanoTime(), reason);
                noOp(engine, engineNoOp);
                break;
            default:
                throw new IllegalStateException("No operation defined for [" + operation + "]");
        }
    } catch (ElasticsearchException e) {
        boolean hasIgnoreOnRecoveryException = false;
        ElasticsearchException current = e;
        while (true) {
            if (current instanceof IgnoreOnRecoveryEngineException) {
                hasIgnoreOnRecoveryException = true;
                break;
            }
            if (current.getCause() instanceof ElasticsearchException) {
                current = (ElasticsearchException) current.getCause();
            } else {
                break;
            }
        }
        if (!hasIgnoreOnRecoveryException) {
            throw e;
        }
    }
    operationProcessed();
}
Also used : IgnoreOnRecoveryEngineException(org.elasticsearch.index.engine.IgnoreOnRecoveryEngineException) ElasticsearchException(org.elasticsearch.ElasticsearchException) Translog(org.elasticsearch.index.translog.Translog) Uid(org.elasticsearch.index.mapper.Uid) Engine(org.elasticsearch.index.engine.Engine)

Example 4 with Uid

use of org.elasticsearch.index.mapper.Uid in project elasticsearch by elastic.

the class IndexShardTests method testRestoreShard.

public void testRestoreShard() throws IOException {
    final IndexShard source = newStartedShard(true);
    IndexShard target = newStartedShard(true);
    indexDoc(source, "test", "0");
    if (randomBoolean()) {
        source.refresh("test");
    }
    indexDoc(target, "test", "1");
    target.refresh("test");
    assertDocs(target, new Uid("test", "1"));
    // only flush source
    flushShard(source);
    final ShardRouting origRouting = target.routingEntry();
    ShardRouting routing = ShardRoutingHelper.reinitPrimary(origRouting);
    final Snapshot snapshot = new Snapshot("foo", new SnapshotId("bar", UUIDs.randomBase64UUID()));
    routing = ShardRoutingHelper.newWithRestoreSource(routing, new RecoverySource.SnapshotRecoverySource(snapshot, Version.CURRENT, "test"));
    target = reinitShard(target, routing);
    Store sourceStore = source.store();
    Store targetStore = target.store();
    DiscoveryNode localNode = new DiscoveryNode("foo", buildNewFakeTransportAddress(), emptyMap(), emptySet(), Version.CURRENT);
    target.markAsRecovering("store", new RecoveryState(routing, localNode, null));
    assertTrue(target.restoreFromRepository(new RestoreOnlyRepository("test") {

        @Override
        public void restoreShard(IndexShard shard, SnapshotId snapshotId, Version version, IndexId indexId, ShardId snapshotShardId, RecoveryState recoveryState) {
            try {
                cleanLuceneIndex(targetStore.directory());
                for (String file : sourceStore.directory().listAll()) {
                    if (file.equals("write.lock") || file.startsWith("extra")) {
                        continue;
                    }
                    targetStore.directory().copyFrom(sourceStore.directory(), file, file, IOContext.DEFAULT);
                }
            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }
        }
    }));
    target.updateRoutingEntry(routing.moveToStarted());
    assertDocs(target, new Uid("test", "0"));
    closeShards(source, target);
}
Also used : IndexId(org.elasticsearch.repositories.IndexId) DiscoveryNode(org.elasticsearch.cluster.node.DiscoveryNode) Store(org.elasticsearch.index.store.Store) Matchers.containsString(org.hamcrest.Matchers.containsString) AlreadyClosedException(org.apache.lucene.store.AlreadyClosedException) EngineException(org.elasticsearch.index.engine.EngineException) IOException(java.io.IOException) BrokenBarrierException(java.util.concurrent.BrokenBarrierException) ExecutionException(java.util.concurrent.ExecutionException) CorruptIndexException(org.apache.lucene.index.CorruptIndexException) Uid(org.elasticsearch.index.mapper.Uid) Snapshot(org.elasticsearch.snapshots.Snapshot) SnapshotId(org.elasticsearch.snapshots.SnapshotId) Version(org.elasticsearch.Version) TestShardRouting(org.elasticsearch.cluster.routing.TestShardRouting) ShardRouting(org.elasticsearch.cluster.routing.ShardRouting) RecoveryState(org.elasticsearch.indices.recovery.RecoveryState)

Example 5 with Uid

use of org.elasticsearch.index.mapper.Uid in project elasticsearch by elastic.

the class Engine method getFromSearcher.

protected final GetResult getFromSearcher(Get get, Function<String, Searcher> searcherFactory) throws EngineException {
    final Searcher searcher = searcherFactory.apply("get");
    final Versions.DocIdAndVersion docIdAndVersion;
    try {
        docIdAndVersion = Versions.loadDocIdAndVersion(searcher.reader(), get.uid());
    } catch (Exception e) {
        Releasables.closeWhileHandlingException(searcher);
        //TODO: A better exception goes here
        throw new EngineException(shardId, "Couldn't resolve version", e);
    }
    if (docIdAndVersion != null) {
        if (get.versionType().isVersionConflictForReads(docIdAndVersion.version, get.version())) {
            Releasables.close(searcher);
            Uid uid = Uid.createUid(get.uid().text());
            throw new VersionConflictEngineException(shardId, uid.type(), uid.id(), get.versionType().explainConflictForReads(docIdAndVersion.version, get.version()));
        }
    }
    if (docIdAndVersion != null) {
        // responsibility of the caller to call GetResult.release
        return new GetResult(searcher, docIdAndVersion);
    } else {
        Releasables.close(searcher);
        return GetResult.NOT_EXISTS;
    }
}
Also used : Uid(org.elasticsearch.index.mapper.Uid) Versions(org.elasticsearch.common.lucene.uid.Versions) IndexSearcher(org.apache.lucene.search.IndexSearcher) NoSuchFileException(java.nio.file.NoSuchFileException) AlreadyClosedException(org.apache.lucene.store.AlreadyClosedException) FileNotFoundException(java.io.FileNotFoundException) IOException(java.io.IOException)

Aggregations

Uid (org.elasticsearch.index.mapper.Uid)5 IOException (java.io.IOException)3 HashSet (java.util.HashSet)2 BrokenBarrierException (java.util.concurrent.BrokenBarrierException)2 LeafReader (org.apache.lucene.index.LeafReader)2 LeafReaderContext (org.apache.lucene.index.LeafReaderContext)2 AlreadyClosedException (org.apache.lucene.store.AlreadyClosedException)2 Bits (org.apache.lucene.util.Bits)2 RandomNumbers (com.carrotsearch.randomizedtesting.generators.RandomNumbers)1 Tuple (io.crate.common.collections.Tuple)1 IOUtils (io.crate.common.io.IOUtils)1 TimeValue (io.crate.common.unit.TimeValue)1 Closeable (java.io.Closeable)1 FileNotFoundException (java.io.FileNotFoundException)1 UncheckedIOException (java.io.UncheckedIOException)1 Charset (java.nio.charset.Charset)1 Files (java.nio.file.Files)1 NoSuchFileException (java.nio.file.NoSuchFileException)1 Path (java.nio.file.Path)1 ArrayList (java.util.ArrayList)1