Search in sources :

Example 16 with IndexService

use of org.elasticsearch.index.IndexService in project elasticsearch by elastic.

the class MetaDataIndexTemplateService method validateAndAddTemplate.

private static void validateAndAddTemplate(final PutRequest request, IndexTemplateMetaData.Builder templateBuilder, IndicesService indicesService, NamedXContentRegistry xContentRegistry) throws Exception {
    Index createdIndex = null;
    final String temporaryIndexName = UUIDs.randomBase64UUID();
    try {
        // use the provided values, otherwise just pick valid dummy values
        int dummyPartitionSize = IndexMetaData.INDEX_ROUTING_PARTITION_SIZE_SETTING.get(request.settings);
        int dummyShards = request.settings.getAsInt(IndexMetaData.SETTING_NUMBER_OF_SHARDS, dummyPartitionSize == 1 ? 1 : dummyPartitionSize + 1);
        //create index service for parsing and validating "mappings"
        Settings dummySettings = Settings.builder().put(IndexMetaData.SETTING_VERSION_CREATED, Version.CURRENT).put(request.settings).put(IndexMetaData.SETTING_NUMBER_OF_SHARDS, dummyShards).put(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, 0).put(IndexMetaData.SETTING_INDEX_UUID, UUIDs.randomBase64UUID()).build();
        final IndexMetaData tmpIndexMetadata = IndexMetaData.builder(temporaryIndexName).settings(dummySettings).build();
        IndexService dummyIndexService = indicesService.createIndex(tmpIndexMetadata, Collections.emptyList(), shardId -> {
        });
        createdIndex = dummyIndexService.index();
        templateBuilder.order(request.order);
        templateBuilder.version(request.version);
        templateBuilder.patterns(request.indexPatterns);
        templateBuilder.settings(request.settings);
        Map<String, Map<String, Object>> mappingsForValidation = new HashMap<>();
        for (Map.Entry<String, String> entry : request.mappings.entrySet()) {
            try {
                templateBuilder.putMapping(entry.getKey(), entry.getValue());
            } catch (Exception e) {
                throw new MapperParsingException("Failed to parse mapping [{}]: {}", e, entry.getKey(), e.getMessage());
            }
            mappingsForValidation.put(entry.getKey(), MapperService.parseMapping(xContentRegistry, entry.getValue()));
        }
        dummyIndexService.mapperService().merge(mappingsForValidation, MergeReason.MAPPING_UPDATE, false);
    } finally {
        if (createdIndex != null) {
            indicesService.removeIndex(createdIndex, NO_LONGER_ASSIGNED, " created for parsing template mapping");
        }
    }
}
Also used : MapperParsingException(org.elasticsearch.index.mapper.MapperParsingException) IndexService(org.elasticsearch.index.IndexService) HashMap(java.util.HashMap) Index(org.elasticsearch.index.Index) HashMap(java.util.HashMap) Map(java.util.Map) Settings(org.elasticsearch.common.settings.Settings) IndexScopedSettings(org.elasticsearch.common.settings.IndexScopedSettings) ValidationException(org.elasticsearch.common.ValidationException) MapperParsingException(org.elasticsearch.index.mapper.MapperParsingException) InvalidIndexTemplateException(org.elasticsearch.indices.InvalidIndexTemplateException) IndexTemplateMissingException(org.elasticsearch.indices.IndexTemplateMissingException)

Example 17 with IndexService

use of org.elasticsearch.index.IndexService in project elasticsearch by elastic.

the class MetaDataMappingService method executeRefresh.

/**
     * Batch method to apply all the queued refresh operations. The idea is to try and batch as much
     * as possible so we won't create the same index all the time for example for the updates on the same mapping
     * and generate a single cluster change event out of all of those.
     */
ClusterState executeRefresh(final ClusterState currentState, final List<RefreshTask> allTasks) throws Exception {
    // break down to tasks per index, so we can optimize the on demand index service creation
    // to only happen for the duration of a single index processing of its respective events
    Map<String, List<RefreshTask>> tasksPerIndex = new HashMap<>();
    for (RefreshTask task : allTasks) {
        if (task.index == null) {
            logger.debug("ignoring a mapping task of type [{}] with a null index.", task);
        }
        tasksPerIndex.computeIfAbsent(task.index, k -> new ArrayList<>()).add(task);
    }
    boolean dirty = false;
    MetaData.Builder mdBuilder = MetaData.builder(currentState.metaData());
    for (Map.Entry<String, List<RefreshTask>> entry : tasksPerIndex.entrySet()) {
        IndexMetaData indexMetaData = mdBuilder.get(entry.getKey());
        if (indexMetaData == null) {
            // index got deleted on us, ignore...
            logger.debug("[{}] ignoring tasks - index meta data doesn't exist", entry.getKey());
            continue;
        }
        final Index index = indexMetaData.getIndex();
        // the tasks lists to iterate over, filled with the list of mapping tasks, trying to keep
        // the latest (based on order) update mapping one per node
        List<RefreshTask> allIndexTasks = entry.getValue();
        boolean hasTaskWithRightUUID = false;
        for (RefreshTask task : allIndexTasks) {
            if (indexMetaData.isSameUUID(task.indexUUID)) {
                hasTaskWithRightUUID = true;
            } else {
                logger.debug("{} ignoring task [{}] - index meta data doesn't match task uuid", index, task);
            }
        }
        if (hasTaskWithRightUUID == false) {
            continue;
        }
        // construct the actual index if needed, and make sure the relevant mappings are there
        boolean removeIndex = false;
        IndexService indexService = indicesService.indexService(indexMetaData.getIndex());
        if (indexService == null) {
            // we need to create the index here, and add the current mapping to it, so we can merge
            indexService = indicesService.createIndex(indexMetaData, Collections.emptyList(), shardId -> {
            });
            removeIndex = true;
            indexService.mapperService().merge(indexMetaData, MergeReason.MAPPING_RECOVERY, true);
        }
        IndexMetaData.Builder builder = IndexMetaData.builder(indexMetaData);
        try {
            boolean indexDirty = refreshIndexMapping(indexService, builder);
            if (indexDirty) {
                mdBuilder.put(builder);
                dirty = true;
            }
        } finally {
            if (removeIndex) {
                indicesService.removeIndex(index, NO_LONGER_ASSIGNED, "created for mapping processing");
            }
        }
    }
    if (!dirty) {
        return currentState;
    }
    return ClusterState.builder(currentState).metaData(mdBuilder).build();
}
Also used : InvalidTypeNameException(org.elasticsearch.indices.InvalidTypeNameException) Nullable(org.elasticsearch.common.Nullable) ClusterService(org.elasticsearch.cluster.service.ClusterService) HashMap(java.util.HashMap) Index(org.elasticsearch.index.Index) ParameterizedMessage(org.apache.logging.log4j.message.ParameterizedMessage) Inject(org.elasticsearch.common.inject.Inject) ArrayList(java.util.ArrayList) ClusterState(org.elasticsearch.cluster.ClusterState) DiscoveryNode(org.elasticsearch.cluster.node.DiscoveryNode) Settings(org.elasticsearch.common.settings.Settings) CompressedXContent(org.elasticsearch.common.compress.CompressedXContent) TimeValue(org.elasticsearch.common.unit.TimeValue) Map(java.util.Map) IndicesService(org.elasticsearch.indices.IndicesService) DocumentMapper(org.elasticsearch.index.mapper.DocumentMapper) Priority(org.elasticsearch.common.Priority) AbstractComponent(org.elasticsearch.common.component.AbstractComponent) IndexService(org.elasticsearch.index.IndexService) IOUtils(org.apache.lucene.util.IOUtils) ClusterStateTaskConfig(org.elasticsearch.cluster.ClusterStateTaskConfig) IOException(java.io.IOException) ClusterStateTaskExecutor(org.elasticsearch.cluster.ClusterStateTaskExecutor) ObjectCursor(com.carrotsearch.hppc.cursors.ObjectCursor) MapperService(org.elasticsearch.index.mapper.MapperService) List(java.util.List) Supplier(org.apache.logging.log4j.util.Supplier) PutMappingClusterStateUpdateRequest(org.elasticsearch.action.admin.indices.mapping.put.PutMappingClusterStateUpdateRequest) AckedClusterStateTaskListener(org.elasticsearch.cluster.AckedClusterStateTaskListener) ClusterStateUpdateResponse(org.elasticsearch.cluster.ack.ClusterStateUpdateResponse) MergeReason(org.elasticsearch.index.mapper.MapperService.MergeReason) NO_LONGER_ASSIGNED(org.elasticsearch.indices.cluster.IndicesClusterStateService.AllocatedIndices.IndexRemovalReason.NO_LONGER_ASSIGNED) Collections(java.util.Collections) ActionListener(org.elasticsearch.action.ActionListener) HashMap(java.util.HashMap) IndexService(org.elasticsearch.index.IndexService) ArrayList(java.util.ArrayList) Index(org.elasticsearch.index.Index) ArrayList(java.util.ArrayList) List(java.util.List) HashMap(java.util.HashMap) Map(java.util.Map)

Example 18 with IndexService

use of org.elasticsearch.index.IndexService in project elasticsearch by elastic.

the class ShardStateIT method assertPrimaryTerms.

protected void assertPrimaryTerms(long term0, long term1) {
    for (String node : internalCluster().getNodeNames()) {
        logger.debug("--> asserting primary terms terms on [{}]", node);
        ClusterState state = client(node).admin().cluster().prepareState().setLocal(true).get().getState();
        IndexMetaData metaData = state.metaData().index("test");
        assertThat(metaData.primaryTerm(0), equalTo(term0));
        assertThat(metaData.primaryTerm(1), equalTo(term1));
        IndicesService indicesService = internalCluster().getInstance(IndicesService.class, node);
        IndexService indexService = indicesService.indexService(metaData.getIndex());
        if (indexService != null) {
            for (IndexShard shard : indexService) {
                assertThat("term mismatch for shard " + shard.shardId(), shard.getPrimaryTerm(), equalTo(metaData.primaryTerm(shard.shardId().id())));
            }
        }
    }
}
Also used : ClusterState(org.elasticsearch.cluster.ClusterState) IndexService(org.elasticsearch.index.IndexService) IndexShard(org.elasticsearch.index.shard.IndexShard) IndicesService(org.elasticsearch.indices.IndicesService) IndexMetaData(org.elasticsearch.cluster.metadata.IndexMetaData)

Example 19 with IndexService

use of org.elasticsearch.index.IndexService in project elasticsearch by elastic.

the class ExpressionTests method setUp.

@Override
public void setUp() throws Exception {
    super.setUp();
    IndexService index = createIndex("test", Settings.EMPTY, "type", "d", "type=double");
    service = new ExpressionScriptEngineService(Settings.EMPTY);
    lookup = new SearchLookup(index.mapperService(), index.fieldData(), null);
}
Also used : IndexService(org.elasticsearch.index.IndexService) SearchLookup(org.elasticsearch.search.lookup.SearchLookup)

Example 20 with IndexService

use of org.elasticsearch.index.IndexService in project elasticsearch by elastic.

the class NeedsScoreTests method testNeedsScores.

public void testNeedsScores() {
    IndexService index = createIndex("test", Settings.EMPTY, "type", "d", "type=double");
    PainlessScriptEngineService service = new PainlessScriptEngineService(Settings.EMPTY);
    SearchLookup lookup = new SearchLookup(index.mapperService(), index.fieldData(), null);
    Object compiled = service.compile(null, "1.2", Collections.emptyMap());
    SearchScript ss = service.search(new CompiledScript(ScriptType.INLINE, "randomName", "painless", compiled), lookup, Collections.<String, Object>emptyMap());
    assertFalse(ss.needsScores());
    compiled = service.compile(null, "doc['d'].value", Collections.emptyMap());
    ss = service.search(new CompiledScript(ScriptType.INLINE, "randomName", "painless", compiled), lookup, Collections.<String, Object>emptyMap());
    assertFalse(ss.needsScores());
    compiled = service.compile(null, "1/_score", Collections.emptyMap());
    ss = service.search(new CompiledScript(ScriptType.INLINE, "randomName", "painless", compiled), lookup, Collections.<String, Object>emptyMap());
    assertTrue(ss.needsScores());
    compiled = service.compile(null, "doc['d'].value * _score", Collections.emptyMap());
    ss = service.search(new CompiledScript(ScriptType.INLINE, "randomName", "painless", compiled), lookup, Collections.<String, Object>emptyMap());
    assertTrue(ss.needsScores());
    service.close();
}
Also used : CompiledScript(org.elasticsearch.script.CompiledScript) SearchScript(org.elasticsearch.script.SearchScript) IndexService(org.elasticsearch.index.IndexService) SearchLookup(org.elasticsearch.search.lookup.SearchLookup)

Aggregations

IndexService (org.elasticsearch.index.IndexService)212 IndexShard (org.elasticsearch.index.shard.IndexShard)77 IndicesService (org.elasticsearch.indices.IndicesService)56 CompressedXContent (org.elasticsearch.common.compress.CompressedXContent)50 ShardId (org.elasticsearch.index.shard.ShardId)38 Index (org.elasticsearch.index.Index)36 DocumentMapper (org.elasticsearch.index.mapper.DocumentMapper)33 Settings (org.elasticsearch.common.settings.Settings)31 IOException (java.io.IOException)22 ArrayList (java.util.ArrayList)22 ShardRouting (org.elasticsearch.cluster.routing.ShardRouting)22 HashMap (java.util.HashMap)21 Map (java.util.Map)19 ClusterService (org.elasticsearch.cluster.service.ClusterService)19 QueryShardContext (org.elasticsearch.index.query.QueryShardContext)18 ElasticsearchException (org.elasticsearch.ElasticsearchException)17 ClusterState (org.elasticsearch.cluster.ClusterState)16 List (java.util.List)14 ParameterizedMessage (org.apache.logging.log4j.message.ParameterizedMessage)13 IndexSettings (org.elasticsearch.index.IndexSettings)13