Search in sources :

Example 41 with MappingMetaData

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

the class ClusterState method toXContent.

@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
    EnumSet<Metric> metrics = Metric.parseString(params.param("metric", "_all"), true);
    if (metrics.contains(Metric.VERSION)) {
        builder.field("version", version);
        builder.field("state_uuid", stateUUID);
    }
    if (metrics.contains(Metric.MASTER_NODE)) {
        builder.field("master_node", nodes().getMasterNodeId());
    }
    if (metrics.contains(Metric.BLOCKS)) {
        builder.startObject("blocks");
        if (!blocks().global().isEmpty()) {
            builder.startObject("global");
            for (ClusterBlock block : blocks().global()) {
                block.toXContent(builder, params);
            }
            builder.endObject();
        }
        if (!blocks().indices().isEmpty()) {
            builder.startObject("indices");
            for (ObjectObjectCursor<String, Set<ClusterBlock>> entry : blocks().indices()) {
                builder.startObject(entry.key);
                for (ClusterBlock block : entry.value) {
                    block.toXContent(builder, params);
                }
                builder.endObject();
            }
            builder.endObject();
        }
        builder.endObject();
    }
    // nodes
    if (metrics.contains(Metric.NODES)) {
        builder.startObject("nodes");
        for (DiscoveryNode node : nodes) {
            node.toXContent(builder, params);
        }
        builder.endObject();
    }
    // meta data
    if (metrics.contains(Metric.METADATA)) {
        builder.startObject("metadata");
        builder.field("cluster_uuid", metaData().clusterUUID());
        builder.startObject("templates");
        for (ObjectCursor<IndexTemplateMetaData> cursor : metaData().templates().values()) {
            IndexTemplateMetaData templateMetaData = cursor.value;
            builder.startObject(templateMetaData.name());
            builder.field("index_patterns", templateMetaData.patterns());
            builder.field("order", templateMetaData.order());
            builder.startObject("settings");
            Settings settings = templateMetaData.settings();
            settings.toXContent(builder, params);
            builder.endObject();
            builder.startObject("mappings");
            for (ObjectObjectCursor<String, CompressedXContent> cursor1 : templateMetaData.mappings()) {
                Map<String, Object> mapping = XContentHelper.convertToMap(new BytesArray(cursor1.value.uncompressed()), false).v2();
                if (mapping.size() == 1 && mapping.containsKey(cursor1.key)) {
                    // the type name is the root value, reduce it
                    mapping = (Map<String, Object>) mapping.get(cursor1.key);
                }
                builder.field(cursor1.key);
                builder.map(mapping);
            }
            builder.endObject();
            builder.endObject();
        }
        builder.endObject();
        builder.startObject("indices");
        for (IndexMetaData indexMetaData : metaData()) {
            builder.startObject(indexMetaData.getIndex().getName());
            builder.field("state", indexMetaData.getState().toString().toLowerCase(Locale.ENGLISH));
            builder.startObject("settings");
            Settings settings = indexMetaData.getSettings();
            settings.toXContent(builder, params);
            builder.endObject();
            builder.startObject("mappings");
            for (ObjectObjectCursor<String, MappingMetaData> cursor : indexMetaData.getMappings()) {
                Map<String, Object> mapping = XContentHelper.convertToMap(new BytesArray(cursor.value.source().uncompressed()), false).v2();
                if (mapping.size() == 1 && mapping.containsKey(cursor.key)) {
                    // the type name is the root value, reduce it
                    mapping = (Map<String, Object>) mapping.get(cursor.key);
                }
                builder.field(cursor.key);
                builder.map(mapping);
            }
            builder.endObject();
            builder.startArray("aliases");
            for (ObjectCursor<String> cursor : indexMetaData.getAliases().keys()) {
                builder.value(cursor.value);
            }
            builder.endArray();
            builder.startObject(IndexMetaData.KEY_PRIMARY_TERMS);
            for (int shard = 0; shard < indexMetaData.getNumberOfShards(); shard++) {
                builder.field(Integer.toString(shard), indexMetaData.primaryTerm(shard));
            }
            builder.endObject();
            builder.startObject(IndexMetaData.KEY_IN_SYNC_ALLOCATIONS);
            for (IntObjectCursor<Set<String>> cursor : indexMetaData.getInSyncAllocationIds()) {
                builder.startArray(String.valueOf(cursor.key));
                for (String allocationId : cursor.value) {
                    builder.value(allocationId);
                }
                builder.endArray();
            }
            builder.endObject();
            // index metadata
            builder.endObject();
        }
        builder.endObject();
        for (ObjectObjectCursor<String, MetaData.Custom> cursor : metaData.customs()) {
            builder.startObject(cursor.key);
            cursor.value.toXContent(builder, params);
            builder.endObject();
        }
        builder.endObject();
    }
    // routing table
    if (metrics.contains(Metric.ROUTING_TABLE)) {
        builder.startObject("routing_table");
        builder.startObject("indices");
        for (IndexRoutingTable indexRoutingTable : routingTable()) {
            builder.startObject(indexRoutingTable.getIndex().getName());
            builder.startObject("shards");
            for (IndexShardRoutingTable indexShardRoutingTable : indexRoutingTable) {
                builder.startArray(Integer.toString(indexShardRoutingTable.shardId().id()));
                for (ShardRouting shardRouting : indexShardRoutingTable) {
                    shardRouting.toXContent(builder, params);
                }
                builder.endArray();
            }
            builder.endObject();
            builder.endObject();
        }
        builder.endObject();
        builder.endObject();
    }
    // routing nodes
    if (metrics.contains(Metric.ROUTING_NODES)) {
        builder.startObject("routing_nodes");
        builder.startArray("unassigned");
        for (ShardRouting shardRouting : getRoutingNodes().unassigned()) {
            shardRouting.toXContent(builder, params);
        }
        builder.endArray();
        builder.startObject("nodes");
        for (RoutingNode routingNode : getRoutingNodes()) {
            builder.startArray(routingNode.nodeId() == null ? "null" : routingNode.nodeId());
            for (ShardRouting shardRouting : routingNode) {
                shardRouting.toXContent(builder, params);
            }
            builder.endArray();
        }
        builder.endObject();
        builder.endObject();
    }
    if (metrics.contains(Metric.CUSTOMS)) {
        for (ObjectObjectCursor<String, Custom> cursor : customs) {
            builder.startObject(cursor.key);
            cursor.value.toXContent(builder, params);
            builder.endObject();
        }
    }
    return builder;
}
Also used : IndexRoutingTable(org.elasticsearch.cluster.routing.IndexRoutingTable) IndexShardRoutingTable(org.elasticsearch.cluster.routing.IndexShardRoutingTable) DiscoveryNode(org.elasticsearch.cluster.node.DiscoveryNode) EnumSet(java.util.EnumSet) Set(java.util.Set) ClusterBlock(org.elasticsearch.cluster.block.ClusterBlock) RoutingNode(org.elasticsearch.cluster.routing.RoutingNode) IndexTemplateMetaData(org.elasticsearch.cluster.metadata.IndexTemplateMetaData) CompressedXContent(org.elasticsearch.common.compress.CompressedXContent) Settings(org.elasticsearch.common.settings.Settings) BytesArray(org.elasticsearch.common.bytes.BytesArray) MappingMetaData(org.elasticsearch.cluster.metadata.MappingMetaData) IndexMetaData(org.elasticsearch.cluster.metadata.IndexMetaData) ShardRouting(org.elasticsearch.cluster.routing.ShardRouting)

Example 42 with MappingMetaData

use of org.elasticsearch.cluster.metadata.MappingMetaData in project sonarqube by SonarSource.

the class IndexCreatorTest method recreate_index_on_definition_changes.

@Test
public void recreate_index_on_definition_changes() throws Exception {
    assertThat(mappings()).isEmpty();
    // v1
    IndexDefinitions registry = new IndexDefinitions(new IndexDefinition[] { new FakeIndexDefinition() }, new MapSettings());
    registry.start();
    IndexCreator creator = new IndexCreator(es.client(), registry);
    creator.start();
    creator.stop();
    String hashV1 = setting("fakes", "index.sonar_hash");
    assertThat(hashV1).isNotEmpty();
    // v2
    registry = new IndexDefinitions(new IndexDefinition[] { new FakeIndexDefinitionV2() }, new MapSettings());
    registry.start();
    creator = new IndexCreator(es.client(), registry);
    creator.start();
    ImmutableOpenMap<String, ImmutableOpenMap<String, MappingMetaData>> mappings = mappings();
    MappingMetaData mapping = mappings.get("fakes").get("fake");
    assertThat(countMappingFields(mapping)).isEqualTo(3);
    assertThat(field(mapping, "updatedAt").get("type")).isEqualTo("date");
    assertThat(field(mapping, "newField").get("type")).isEqualTo("integer");
    String hashV2 = setting("fakes", "index.sonar_hash");
    assertThat(hashV2).isNotEqualTo(hashV1);
    creator.stop();
}
Also used : MapSettings(org.sonar.api.config.MapSettings) ImmutableOpenMap(org.elasticsearch.common.collect.ImmutableOpenMap) MappingMetaData(org.elasticsearch.cluster.metadata.MappingMetaData) Test(org.junit.Test)

Example 43 with MappingMetaData

use of org.elasticsearch.cluster.metadata.MappingMetaData in project graylog2-server by Graylog2.

the class Indices method getAllMessageFieldsForIndices.

public Map<String, Set<String>> getAllMessageFieldsForIndices(final String[] writeIndexWildcards) {
    final Map<String, Set<String>> fields = new HashMap<>();
    final ClusterStateRequest csr = new ClusterStateRequest().blocks(true).nodes(true).indices(writeIndexWildcards);
    final ClusterState cs = c.admin().cluster().state(csr).actionGet().getState();
    for (ObjectObjectCursor<String, IndexMetaData> m : cs.getMetaData().indices()) {
        try {
            MappingMetaData mmd = m.value.mapping(IndexMapping.TYPE_MESSAGE);
            if (mmd == null) {
                // There is no mapping if there are no messages in the index.
                continue;
            }
            @SuppressWarnings("unchecked") final Map<String, Object> mapping = (Map<String, Object>) mmd.getSourceAsMap().get("properties");
            if (mapping != null) {
                fields.put(m.key, mapping.keySet());
            }
        } catch (Exception e) {
            LOG.error("Error while trying to get fields of <" + m.index + ">", e);
        }
    }
    return fields;
}
Also used : ClusterState(org.elasticsearch.cluster.ClusterState) IndexSet(org.graylog2.indexer.IndexSet) Collectors.toSet(java.util.stream.Collectors.toSet) ImmutableSet(com.google.common.collect.ImmutableSet) Set(java.util.Set) HashMap(java.util.HashMap) ClusterStateRequest(org.elasticsearch.action.admin.cluster.state.ClusterStateRequest) MappingMetaData(org.elasticsearch.cluster.metadata.MappingMetaData) ElasticsearchException(org.elasticsearch.ElasticsearchException) IndexClosedException(org.elasticsearch.indices.IndexClosedException) IndexNotFoundException(org.graylog2.indexer.IndexNotFoundException) IOException(java.io.IOException) IndexMetaData(org.elasticsearch.cluster.metadata.IndexMetaData) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap) ImmutableOpenMap(org.elasticsearch.common.collect.ImmutableOpenMap) HashMap(java.util.HashMap)

Example 44 with MappingMetaData

use of org.elasticsearch.cluster.metadata.MappingMetaData in project fess by codelibs.

the class FessEsClient method addMapping.

public void addMapping(final String index, final String docType, final String indexName) {
    final FessConfig fessConfig = ComponentUtil.getFessConfig();
    final GetMappingsResponse getMappingsResponse = client.admin().indices().prepareGetMappings(indexName).execute().actionGet(fessConfig.getIndexIndicesTimeout());
    final ImmutableOpenMap<String, MappingMetaData> indexMappings = getMappingsResponse.mappings().get(indexName);
    if (indexMappings == null || !indexMappings.containsKey(docType)) {
        String source = null;
        final String mappingFile = indexConfigPath + "/" + index + "/" + docType + ".json";
        try {
            source = FileUtil.readUTF8(mappingFile);
        } catch (final Exception e) {
            logger.warn(mappingFile + " is not found.", e);
        }
        try {
            final PutMappingResponse putMappingResponse = client.admin().indices().preparePutMapping(indexName).setType(docType).setSource(source, XContentFactory.xContentType(source)).execute().actionGet(fessConfig.getIndexIndicesTimeout());
            if (putMappingResponse.isAcknowledged()) {
                logger.info("Created " + indexName + "/" + docType + " mapping.");
            } else {
                logger.warn("Failed to create " + indexName + "/" + docType + " mapping.");
            }
            final String dataPath = indexConfigPath + "/" + index + "/" + docType + ".bulk";
            if (ResourceUtil.isExist(dataPath)) {
                insertBulkData(fessConfig, index, docType, dataPath);
            }
        } catch (final Exception e) {
            logger.warn("Failed to create " + indexName + "/" + docType + " mapping.", e);
        }
    } else if (logger.isDebugEnabled()) {
        logger.debug(indexName + "/" + docType + " mapping exists.");
    }
}
Also used : PutMappingResponse(org.elasticsearch.action.admin.indices.mapping.put.PutMappingResponse) MappingMetaData(org.elasticsearch.cluster.metadata.MappingMetaData) FessConfig(org.codelibs.fess.mylasta.direction.FessConfig) IllegalBehaviorStateException(org.dbflute.exception.IllegalBehaviorStateException) FessSystemException(org.codelibs.fess.exception.FessSystemException) ResultOffsetExceededException(org.codelibs.fess.exception.ResultOffsetExceededException) ResourceNotFoundRuntimeException(org.codelibs.core.exception.ResourceNotFoundRuntimeException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) ElasticsearchException(org.elasticsearch.ElasticsearchException) SearchPhaseExecutionException(org.elasticsearch.action.search.SearchPhaseExecutionException) SearchQueryException(org.codelibs.fess.exception.SearchQueryException) InvalidQueryException(org.codelibs.fess.exception.InvalidQueryException) GetMappingsResponse(org.elasticsearch.action.admin.indices.mapping.get.GetMappingsResponse)

Example 45 with MappingMetaData

use of org.elasticsearch.cluster.metadata.MappingMetaData in project play2-elasticsearch by cleverage.

the class IndexService method getMapping.

/**
     * Read the Mapping for a type
     * @param indexType
     * @return
     */
public static String getMapping(String indexName, String indexType) {
    ClusterState state = IndexClient.client.admin().cluster().prepareState().setIndices(IndexService.INDEX_DEFAULT).execute().actionGet().getState();
    MappingMetaData mappingMetaData = state.getMetaData().index(indexName).mapping(indexType);
    if (mappingMetaData != null) {
        return mappingMetaData.source().toString();
    } else {
        return null;
    }
}
Also used : ClusterState(org.elasticsearch.cluster.ClusterState) MappingMetaData(org.elasticsearch.cluster.metadata.MappingMetaData)

Aggregations

MappingMetaData (org.elasticsearch.cluster.metadata.MappingMetaData)45 ImmutableOpenMap (org.elasticsearch.common.collect.ImmutableOpenMap)15 Map (java.util.Map)14 GetMappingsResponse (org.elasticsearch.action.admin.indices.mapping.get.GetMappingsResponse)11 IndexMetaData (org.elasticsearch.cluster.metadata.IndexMetaData)10 Settings (org.elasticsearch.common.settings.Settings)9 Test (org.junit.Test)9 IOException (java.io.IOException)8 IndexTemplateMetaData (org.elasticsearch.cluster.metadata.IndexTemplateMetaData)7 PartitionName (io.crate.metadata.PartitionName)6 HashMap (java.util.HashMap)6 BytesRef (org.apache.lucene.util.BytesRef)6 SearchResponse (org.elasticsearch.action.search.SearchResponse)5 List (java.util.List)4 Set (java.util.Set)4 ClusterState (org.elasticsearch.cluster.ClusterState)4 CompressedXContent (org.elasticsearch.common.compress.CompressedXContent)4 ObjectObjectCursor (com.carrotsearch.hppc.cursors.ObjectObjectCursor)3 ArrayList (java.util.ArrayList)3 GetIndexTemplatesResponse (org.elasticsearch.action.admin.indices.template.get.GetIndexTemplatesResponse)3