Search in sources :

Example 1 with IndexCache

use of org.elasticsearch.index.cache.IndexCache in project crate by crate.

the class LuceneQueryBuilderTest method prepare.

@Before
public void prepare() throws Exception {
    DocTableInfo users = TestingTableInfo.builder(new TableIdent(null, "users"), null).add("name", DataTypes.STRING).add("x", DataTypes.INTEGER).add("d", DataTypes.DOUBLE).add("d_array", new ArrayType(DataTypes.DOUBLE)).add("y_array", new ArrayType(DataTypes.LONG)).add("shape", DataTypes.GEO_SHAPE).add("point", DataTypes.GEO_POINT).build();
    TableRelation usersTr = new TableRelation(users);
    sources = ImmutableMap.of(new QualifiedName("users"), usersTr);
    expressions = new SqlExpressions(sources, usersTr);
    builder = new LuceneQueryBuilder(expressions.getInstance(Functions.class));
    indexCache = mock(IndexCache.class, Answers.RETURNS_MOCKS.get());
    Path tempDir = createTempDir();
    Settings indexSettings = Settings.builder().put(IndexMetaData.SETTING_VERSION_CREATED, Version.CURRENT).put("path.home", tempDir).build();
    Index index = new Index(users.ident().indexName());
    when(indexCache.indexSettings()).thenReturn(indexSettings);
    AnalysisService analysisService = createAnalysisService(indexSettings, index);
    mapperService = createMapperService(index, indexSettings, analysisService);
    // @formatter:off
    XContentBuilder xContentBuilder = XContentFactory.jsonBuilder().startObject().startObject("default").startObject("properties").startObject("name").field("type", "string").endObject().startObject("x").field("type", "integer").endObject().startObject("d").field("type", "double").endObject().startObject("point").field("type", "geo_point").endObject().startObject("shape").field("type", "geo_shape").endObject().startObject("d_array").field("type", "array").startObject("inner").field("type", "double").endObject().endObject().startObject("y_array").field("type", "array").startObject("inner").field("type", "integer").endObject().endObject().endObject().endObject().endObject();
    // @formatter:on
    mapperService.merge("default", new CompressedXContent(xContentBuilder.bytes()), MapperService.MergeReason.MAPPING_UPDATE, true);
    indexFieldDataService = mock(IndexFieldDataService.class);
    IndexFieldData geoFieldData = mock(IndexGeoPointFieldData.class);
    when(geoFieldData.getFieldNames()).thenReturn(new MappedFieldType.Names("point"));
    when(indexFieldDataService.getForField(mapperService.smartNameFieldType("point"))).thenReturn(geoFieldData);
}
Also used : Path(java.nio.file.Path) DocTableInfo(io.crate.metadata.doc.DocTableInfo) QualifiedName(io.crate.sql.tree.QualifiedName) TableIdent(io.crate.metadata.TableIdent) Index(org.elasticsearch.index.Index) TableRelation(io.crate.analyze.relations.TableRelation) ArrayType(io.crate.types.ArrayType) IndexFieldDataService(org.elasticsearch.index.fielddata.IndexFieldDataService) IndexCache(org.elasticsearch.index.cache.IndexCache) CompressedXContent(org.elasticsearch.common.compress.CompressedXContent) MappedFieldType(org.elasticsearch.index.mapper.MappedFieldType) IndexFieldData(org.elasticsearch.index.fielddata.IndexFieldData) IndicesAnalysisService(org.elasticsearch.indices.analysis.IndicesAnalysisService) AnalysisService(org.elasticsearch.index.analysis.AnalysisService) SqlExpressions(io.crate.testing.SqlExpressions) Settings(org.elasticsearch.common.settings.Settings) XContentBuilder(org.elasticsearch.common.xcontent.XContentBuilder) Before(org.junit.Before)

Example 2 with IndexCache

use of org.elasticsearch.index.cache.IndexCache in project elasticsearch by elastic.

the class IndexService method createShard.

public synchronized IndexShard createShard(ShardRouting routing) throws IOException {
    final boolean primary = routing.primary();
    /*
         * TODO: we execute this in parallel but it's a synced method. Yet, we might
         * be able to serialize the execution via the cluster state in the future. for now we just
         * keep it synced.
         */
    if (closed.get()) {
        throw new IllegalStateException("Can't create shard " + routing.shardId() + ", closed");
    }
    final Settings indexSettings = this.indexSettings.getSettings();
    final ShardId shardId = routing.shardId();
    boolean success = false;
    Store store = null;
    IndexShard indexShard = null;
    ShardLock lock = null;
    try {
        lock = nodeEnv.shardLock(shardId, TimeUnit.SECONDS.toMillis(5));
        eventListener.beforeIndexShardCreated(shardId, indexSettings);
        ShardPath path;
        try {
            path = ShardPath.loadShardPath(logger, nodeEnv, shardId, this.indexSettings);
        } catch (IllegalStateException ex) {
            logger.warn("{} failed to load shard path, trying to remove leftover", shardId);
            try {
                ShardPath.deleteLeftoverShardDirectory(logger, nodeEnv, lock, this.indexSettings);
                path = ShardPath.loadShardPath(logger, nodeEnv, shardId, this.indexSettings);
            } catch (Exception inner) {
                ex.addSuppressed(inner);
                throw ex;
            }
        }
        if (path == null) {
            // TODO: we should, instead, hold a "bytes reserved" of how large we anticipate this shard will be, e.g. for a shard
            // that's being relocated/replicated we know how large it will become once it's done copying:
            // Count up how many shards are currently on each data path:
            Map<Path, Integer> dataPathToShardCount = new HashMap<>();
            for (IndexShard shard : this) {
                Path dataPath = shard.shardPath().getRootStatePath();
                Integer curCount = dataPathToShardCount.get(dataPath);
                if (curCount == null) {
                    curCount = 0;
                }
                dataPathToShardCount.put(dataPath, curCount + 1);
            }
            path = ShardPath.selectNewPathForShard(nodeEnv, shardId, this.indexSettings, routing.getExpectedShardSize() == ShardRouting.UNAVAILABLE_EXPECTED_SHARD_SIZE ? getAvgShardSizeInBytes() : routing.getExpectedShardSize(), dataPathToShardCount);
            logger.debug("{} creating using a new path [{}]", shardId, path);
        } else {
            logger.debug("{} creating using an existing path [{}]", shardId, path);
        }
        if (shards.containsKey(shardId.id())) {
            throw new IllegalStateException(shardId + " already exists");
        }
        logger.debug("creating shard_id {}", shardId);
        // if we are on a shared FS we only own the shard (ie. we can safely delete it) if we are the primary.
        final boolean canDeleteShardContent = this.indexSettings.isOnSharedFilesystem() == false || (primary && this.indexSettings.isOnSharedFilesystem());
        final Engine.Warmer engineWarmer = (searcher) -> {
            IndexShard shard = getShardOrNull(shardId.getId());
            if (shard != null) {
                warmer.warm(searcher, shard, IndexService.this.indexSettings);
            }
        };
        store = new Store(shardId, this.indexSettings, indexStore.newDirectoryService(path), lock, new StoreCloseListener(shardId, canDeleteShardContent, () -> eventListener.onStoreClosed(shardId)));
        if (useShadowEngine(primary, this.indexSettings)) {
            indexShard = new ShadowIndexShard(routing, this.indexSettings, path, store, indexCache, mapperService, similarityService, indexFieldData, engineFactory, eventListener, searcherWrapper, threadPool, bigArrays, engineWarmer, searchOperationListeners);
        // no indexing listeners - shadow  engines don't index
        } else {
            indexShard = new IndexShard(routing, this.indexSettings, path, store, indexCache, mapperService, similarityService, indexFieldData, engineFactory, eventListener, searcherWrapper, threadPool, bigArrays, engineWarmer, () -> globalCheckpointSyncer.accept(shardId), searchOperationListeners, indexingOperationListeners);
        }
        eventListener.indexShardStateChanged(indexShard, null, indexShard.state(), "shard created");
        eventListener.afterIndexShardCreated(indexShard);
        shards = newMapBuilder(shards).put(shardId.id(), indexShard).immutableMap();
        success = true;
        return indexShard;
    } catch (ShardLockObtainFailedException e) {
        throw new IOException("failed to obtain in-memory shard lock", e);
    } finally {
        if (success == false) {
            if (lock != null) {
                IOUtils.closeWhileHandlingException(lock);
            }
            closeShard("initialization failed", shardId, indexShard, store, eventListener);
        }
    }
}
Also used : Path(java.nio.file.Path) ShardPath(org.elasticsearch.index.shard.ShardPath) BitsetFilterCache(org.elasticsearch.index.cache.bitset.BitsetFilterCache) ShardId(org.elasticsearch.index.shard.ShardId) ScheduledFuture(java.util.concurrent.ScheduledFuture) QueryShardContext(org.elasticsearch.index.query.QueryShardContext) LongSupplier(java.util.function.LongSupplier) Nullable(org.elasticsearch.common.Nullable) BigArrays(org.elasticsearch.common.util.BigArrays) AlreadyClosedException(org.apache.lucene.store.AlreadyClosedException) IndexAnalyzers(org.elasticsearch.index.analysis.IndexAnalyzers) MapperRegistry(org.elasticsearch.indices.mapper.MapperRegistry) ShardNotFoundException(org.elasticsearch.index.shard.ShardNotFoundException) Settings(org.elasticsearch.common.settings.Settings) SearchOperationListener(org.elasticsearch.index.shard.SearchOperationListener) Map(java.util.Map) ThreadPool(org.elasticsearch.threadpool.ThreadPool) Path(java.nio.file.Path) NamedXContentRegistry(org.elasticsearch.common.xcontent.NamedXContentRegistry) IndexStore(org.elasticsearch.index.store.IndexStore) Set(java.util.Set) ShardLockObtainFailedException(org.elasticsearch.env.ShardLockObtainFailedException) AnalysisRegistry(org.elasticsearch.index.analysis.AnalysisRegistry) MapBuilder.newMapBuilder(org.elasticsearch.common.collect.MapBuilder.newMapBuilder) Engine(org.elasticsearch.index.engine.Engine) SimilarityService(org.elasticsearch.index.similarity.SimilarityService) Objects(java.util.Objects) MapperService(org.elasticsearch.index.mapper.MapperService) List(java.util.List) Supplier(org.apache.logging.log4j.util.Supplier) IndexMetaData(org.elasticsearch.cluster.metadata.IndexMetaData) IndicesClusterStateService(org.elasticsearch.indices.cluster.IndicesClusterStateService) Accountable(org.apache.lucene.util.Accountable) ShardPath(org.elasticsearch.index.shard.ShardPath) IndexingOperationListener(org.elasticsearch.index.shard.IndexingOperationListener) ShadowIndexShard(org.elasticsearch.index.shard.ShadowIndexShard) IndexReader(org.apache.lucene.index.IndexReader) ShardRouting(org.elasticsearch.cluster.routing.ShardRouting) IndexShardClosedException(org.elasticsearch.index.shard.IndexShardClosedException) IndexFieldDataService(org.elasticsearch.index.fielddata.IndexFieldDataService) ClusterService(org.elasticsearch.cluster.service.ClusterService) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) ParameterizedMessage(org.apache.logging.log4j.message.ParameterizedMessage) CircuitBreakerService(org.elasticsearch.indices.breaker.CircuitBreakerService) IndexCache(org.elasticsearch.index.cache.IndexCache) IndexSearcherWrapper(org.elasticsearch.index.shard.IndexSearcherWrapper) TimeValue(org.elasticsearch.common.unit.TimeValue) Store(org.elasticsearch.index.store.Store) Collections.emptyMap(java.util.Collections.emptyMap) FutureUtils(org.elasticsearch.common.util.concurrent.FutureUtils) IndexFieldDataCache(org.elasticsearch.index.fielddata.IndexFieldDataCache) IndexEventListener(org.elasticsearch.index.shard.IndexEventListener) Iterator(java.util.Iterator) Client(org.elasticsearch.client.Client) IndexShard(org.elasticsearch.index.shard.IndexShard) IOUtils(org.apache.lucene.util.IOUtils) IOException(java.io.IOException) ShardLock(org.elasticsearch.env.ShardLock) EngineFactory(org.elasticsearch.index.engine.EngineFactory) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) NodeEnvironment(org.elasticsearch.env.NodeEnvironment) IndicesFieldDataCache(org.elasticsearch.indices.fielddata.cache.IndicesFieldDataCache) QueryCache(org.elasticsearch.index.cache.query.QueryCache) Closeable(java.io.Closeable) Translog(org.elasticsearch.index.translog.Translog) Collections.unmodifiableMap(java.util.Collections.unmodifiableMap) ScriptService(org.elasticsearch.script.ScriptService) Collections(java.util.Collections) HashMap(java.util.HashMap) ShadowIndexShard(org.elasticsearch.index.shard.ShadowIndexShard) IndexShard(org.elasticsearch.index.shard.IndexShard) IndexStore(org.elasticsearch.index.store.IndexStore) Store(org.elasticsearch.index.store.Store) ShadowIndexShard(org.elasticsearch.index.shard.ShadowIndexShard) IOException(java.io.IOException) AlreadyClosedException(org.apache.lucene.store.AlreadyClosedException) ShardNotFoundException(org.elasticsearch.index.shard.ShardNotFoundException) ShardLockObtainFailedException(org.elasticsearch.env.ShardLockObtainFailedException) IndexShardClosedException(org.elasticsearch.index.shard.IndexShardClosedException) IOException(java.io.IOException) ShardId(org.elasticsearch.index.shard.ShardId) ShardPath(org.elasticsearch.index.shard.ShardPath) ShardLock(org.elasticsearch.env.ShardLock) ShardLockObtainFailedException(org.elasticsearch.env.ShardLockObtainFailedException) Settings(org.elasticsearch.common.settings.Settings) Engine(org.elasticsearch.index.engine.Engine)

Example 3 with IndexCache

use of org.elasticsearch.index.cache.IndexCache in project elasticsearch by elastic.

the class IndexShardTestCase method newShard.

/**
     * creates a new initializing shard.
     *
     * @param routing              shard routing to use
     * @param shardPath            path to use for shard data
     * @param indexMetaData        indexMetaData for the shard, including any mapping
     * @param indexSearcherWrapper an optional wrapper to be used during searchers
     * @param listeners            an optional set of listeners to add to the shard
     */
protected IndexShard newShard(ShardRouting routing, ShardPath shardPath, IndexMetaData indexMetaData, @Nullable IndexSearcherWrapper indexSearcherWrapper, Runnable globalCheckpointSyncer, @Nullable EngineFactory engineFactory, IndexingOperationListener... listeners) throws IOException {
    final Settings nodeSettings = Settings.builder().put("node.name", routing.currentNodeId()).build();
    final IndexSettings indexSettings = new IndexSettings(indexMetaData, nodeSettings);
    final IndexShard indexShard;
    final Store store = createStore(indexSettings, shardPath);
    boolean success = false;
    try {
        IndexCache indexCache = new IndexCache(indexSettings, new DisabledQueryCache(indexSettings), null);
        MapperService mapperService = MapperTestUtils.newMapperService(xContentRegistry(), createTempDir(), indexSettings.getSettings());
        mapperService.merge(indexMetaData, MapperService.MergeReason.MAPPING_RECOVERY, true);
        SimilarityService similarityService = new SimilarityService(indexSettings, Collections.emptyMap());
        final IndexEventListener indexEventListener = new IndexEventListener() {
        };
        final Engine.Warmer warmer = searcher -> {
        };
        IndicesFieldDataCache indicesFieldDataCache = new IndicesFieldDataCache(nodeSettings, new IndexFieldDataCache.Listener() {
        });
        IndexFieldDataService indexFieldDataService = new IndexFieldDataService(indexSettings, indicesFieldDataCache, new NoneCircuitBreakerService(), mapperService);
        indexShard = new IndexShard(routing, indexSettings, shardPath, store, indexCache, mapperService, similarityService, indexFieldDataService, engineFactory, indexEventListener, indexSearcherWrapper, threadPool, BigArrays.NON_RECYCLING_INSTANCE, warmer, globalCheckpointSyncer, Collections.emptyList(), Arrays.asList(listeners));
        success = true;
    } finally {
        if (success == false) {
            IOUtils.close(store);
        }
    }
    return indexShard;
}
Also used : IndexNotFoundException(org.apache.lucene.index.IndexNotFoundException) Versions(org.elasticsearch.common.lucene.uid.Versions) ByteSizeUnit(org.elasticsearch.common.unit.ByteSizeUnit) Arrays(java.util.Arrays) Nullable(org.elasticsearch.common.Nullable) BigArrays(org.elasticsearch.common.util.BigArrays) BiFunction(java.util.function.BiFunction) VersionType(org.elasticsearch.index.VersionType) Document(org.apache.lucene.document.Document) IndexRequest(org.elasticsearch.action.index.IndexRequest) Settings(org.elasticsearch.common.settings.Settings) ShardRoutingHelper(org.elasticsearch.cluster.routing.ShardRoutingHelper) Directory(org.apache.lucene.store.Directory) ThreadPool(org.elasticsearch.threadpool.ThreadPool) LeafReaderContext(org.apache.lucene.index.LeafReaderContext) UidFieldMapper(org.elasticsearch.index.mapper.UidFieldMapper) EnumSet(java.util.EnumSet) PeerRecoveryTargetService(org.elasticsearch.indices.recovery.PeerRecoveryTargetService) Set(java.util.Set) MapperTestUtils(org.elasticsearch.index.MapperTestUtils) Engine(org.elasticsearch.index.engine.Engine) SimilarityService(org.elasticsearch.index.similarity.SimilarityService) RecoverySource(org.elasticsearch.cluster.routing.RecoverySource) MapperService(org.elasticsearch.index.mapper.MapperService) Version(org.elasticsearch.Version) Matchers.contains(org.hamcrest.Matchers.contains) IndexMetaData(org.elasticsearch.cluster.metadata.IndexMetaData) RecoveryState(org.elasticsearch.indices.recovery.RecoveryState) LeafReader(org.apache.lucene.index.LeafReader) TestShardRouting(org.elasticsearch.cluster.routing.TestShardRouting) ShardRouting(org.elasticsearch.cluster.routing.ShardRouting) StartRecoveryRequest(org.elasticsearch.indices.recovery.StartRecoveryRequest) XContentType(org.elasticsearch.common.xcontent.XContentType) IndexFieldDataService(org.elasticsearch.index.fielddata.IndexFieldDataService) RecoveryFailedException(org.elasticsearch.indices.recovery.RecoveryFailedException) ShardRoutingState(org.elasticsearch.cluster.routing.ShardRoutingState) DisabledQueryCache(org.elasticsearch.index.cache.query.DisabledQueryCache) BytesArray(org.elasticsearch.common.bytes.BytesArray) RecoverySourceHandler(org.elasticsearch.indices.recovery.RecoverySourceHandler) HashSet(java.util.HashSet) DiscoveryNode(org.elasticsearch.cluster.node.DiscoveryNode) IndexCache(org.elasticsearch.index.cache.IndexCache) SequenceNumbersService(org.elasticsearch.index.seqno.SequenceNumbersService) NoneCircuitBreakerService(org.elasticsearch.indices.breaker.NoneCircuitBreakerService) Store(org.elasticsearch.index.store.Store) IndexSettings(org.elasticsearch.index.IndexSettings) Node(org.elasticsearch.node.Node) Matchers.hasSize(org.hamcrest.Matchers.hasSize) ESTestCase(org.elasticsearch.test.ESTestCase) Bits(org.apache.lucene.util.Bits) SourceToParse(org.elasticsearch.index.mapper.SourceToParse) TestThreadPool(org.elasticsearch.threadpool.TestThreadPool) IndexFieldDataCache(org.elasticsearch.index.fielddata.IndexFieldDataCache) Uid(org.elasticsearch.index.mapper.Uid) RecoveryTarget(org.elasticsearch.indices.recovery.RecoveryTarget) IOUtils(org.apache.lucene.util.IOUtils) IOException(java.io.IOException) DirectoryService(org.elasticsearch.index.store.DirectoryService) EngineFactory(org.elasticsearch.index.engine.EngineFactory) TimeUnit(java.util.concurrent.TimeUnit) FlushRequest(org.elasticsearch.action.admin.indices.flush.FlushRequest) NodeEnvironment(org.elasticsearch.env.NodeEnvironment) IndicesFieldDataCache(org.elasticsearch.indices.fielddata.cache.IndicesFieldDataCache) DummyShardLock(org.elasticsearch.test.DummyShardLock) Collections(java.util.Collections) IndexSettings(org.elasticsearch.index.IndexSettings) Store(org.elasticsearch.index.store.Store) IndexFieldDataCache(org.elasticsearch.index.fielddata.IndexFieldDataCache) IndicesFieldDataCache(org.elasticsearch.indices.fielddata.cache.IndicesFieldDataCache) IndexFieldDataService(org.elasticsearch.index.fielddata.IndexFieldDataService) IndexCache(org.elasticsearch.index.cache.IndexCache) SimilarityService(org.elasticsearch.index.similarity.SimilarityService) Settings(org.elasticsearch.common.settings.Settings) IndexSettings(org.elasticsearch.index.IndexSettings) DisabledQueryCache(org.elasticsearch.index.cache.query.DisabledQueryCache) MapperService(org.elasticsearch.index.mapper.MapperService) Engine(org.elasticsearch.index.engine.Engine) NoneCircuitBreakerService(org.elasticsearch.indices.breaker.NoneCircuitBreakerService)

Aggregations

Settings (org.elasticsearch.common.settings.Settings)3 IndexCache (org.elasticsearch.index.cache.IndexCache)3 IndexFieldDataService (org.elasticsearch.index.fielddata.IndexFieldDataService)3 IOException (java.io.IOException)2 Path (java.nio.file.Path)2 Collections (java.util.Collections)2 Set (java.util.Set)2 TimeUnit (java.util.concurrent.TimeUnit)2 IOUtils (org.apache.lucene.util.IOUtils)2 IndexMetaData (org.elasticsearch.cluster.metadata.IndexMetaData)2 ShardRouting (org.elasticsearch.cluster.routing.ShardRouting)2 Nullable (org.elasticsearch.common.Nullable)2 BigArrays (org.elasticsearch.common.util.BigArrays)2 NodeEnvironment (org.elasticsearch.env.NodeEnvironment)2 Engine (org.elasticsearch.index.engine.Engine)2 EngineFactory (org.elasticsearch.index.engine.EngineFactory)2 IndexFieldDataCache (org.elasticsearch.index.fielddata.IndexFieldDataCache)2 MapperService (org.elasticsearch.index.mapper.MapperService)2 SimilarityService (org.elasticsearch.index.similarity.SimilarityService)2 Store (org.elasticsearch.index.store.Store)2