Search in sources :

Example 1 with CreateIndexResponse

use of org.elasticsearch.client.indices.CreateIndexResponse in project ranger by apache.

the class ElasticSearchIndexBootStrapper method createIndex.

private boolean createIndex() {
    boolean exits = false;
    if (client == null) {
        connect();
    }
    if (client != null) {
        try {
            exits = client.indices().open(new OpenIndexRequest(this.index), RequestOptions.DEFAULT).isShardsAcknowledged();
        } catch (Exception e) {
            LOG.info("Index " + this.index + " not available.");
        }
        if (!exits) {
            LOG.info("Index does not exist. Attempting to create index:" + this.index);
            CreateIndexRequest request = new CreateIndexRequest(this.index);
            if (this.no_of_shards >= 0 && this.no_of_replicas >= 0) {
                request.settings(Settings.builder().put("index.number_of_shards", this.no_of_shards).put("index.number_of_replicas", this.no_of_replicas));
            }
            request.mapping(es_ranger_audit_schema_json, XContentType.JSON);
            request.setMasterTimeout(TimeValue.timeValueMinutes(1));
            request.setTimeout(TimeValue.timeValueMinutes(2));
            try {
                CreateIndexResponse createIndexResponse = client.indices().create(request, RequestOptions.DEFAULT);
                if (createIndexResponse != null) {
                    exits = client.indices().open(new OpenIndexRequest(this.index), RequestOptions.DEFAULT).isShardsAcknowledged();
                    if (exits) {
                        LOG.info("Index " + this.index + " created successfully.");
                    }
                }
            } catch (Exception e) {
                LOG.severe("Unable to create Index. Reason:" + e.toString());
                e.printStackTrace();
            }
        } else {
            LOG.info("Index " + this.index + " is already created.");
        }
    }
    return exits;
}
Also used : OpenIndexRequest(org.elasticsearch.action.admin.indices.open.OpenIndexRequest) CreateIndexRequest(org.elasticsearch.client.indices.CreateIndexRequest) CreateIndexResponse(org.elasticsearch.client.indices.CreateIndexResponse) IOException(java.io.IOException)

Example 2 with CreateIndexResponse

use of org.elasticsearch.client.indices.CreateIndexResponse in project sonarqube by SonarSource.

the class EsTester method createIndices.

private static List<BuiltIndex> createIndices(IndexDefinition... definitions) {
    IndexDefinitionContext context = new IndexDefinitionContext();
    Stream.of(definitions).forEach(d -> d.define(context));
    List<BuiltIndex> result = new ArrayList<>();
    for (NewIndex newIndex : context.getIndices().values()) {
        BuiltIndex index = newIndex.build();
        String indexName = index.getMainType().getIndex().getName();
        deleteIndexIfExists(indexName);
        // create index
        Settings.Builder settings = Settings.builder();
        settings.put(index.getSettings());
        CreateIndexResponse indexResponse = createIndex(indexName, settings);
        if (!indexResponse.isAcknowledged()) {
            throw new IllegalStateException("Failed to create index " + indexName);
        }
        waitForClusterYellowStatus(indexName);
        // create types
        String typeName = index.getMainType().getType();
        putIndexMapping(index, indexName, typeName);
        waitForClusterYellowStatus(indexName);
        result.add(index);
    }
    return result;
}
Also used : BuiltIndex(org.sonar.server.es.newindex.BuiltIndex) Lists.newArrayList(com.google.common.collect.Lists.newArrayList) ArrayList(java.util.ArrayList) NewIndex(org.sonar.server.es.newindex.NewIndex) CreateIndexResponse(org.elasticsearch.client.indices.CreateIndexResponse) IndexDefinitionContext(org.sonar.server.es.IndexDefinition.IndexDefinitionContext) RecoverySettings(org.elasticsearch.indices.recovery.RecoverySettings) Settings(org.elasticsearch.common.settings.Settings) HttpTransportSettings(org.elasticsearch.http.HttpTransportSettings) DiskThresholdSettings(org.elasticsearch.cluster.routing.allocation.DiskThresholdSettings)

Example 3 with CreateIndexResponse

use of org.elasticsearch.client.indices.CreateIndexResponse in project sonarqube by SonarSource.

the class IndexCreator method createIndex.

private void createIndex(BuiltIndex<?> builtIndex, boolean useMetadata) {
    Index index = builtIndex.getMainType().getIndex();
    LOGGER.info(String.format("Create index [%s]", index.getName()));
    Settings.Builder settings = Settings.builder();
    settings.put(builtIndex.getSettings());
    if (useMetadata) {
        metadataIndex.setHash(index, IndexDefinitionHash.of(builtIndex));
        metadataIndex.setInitialized(builtIndex.getMainType(), false);
        builtIndex.getRelationTypes().forEach(relationType -> metadataIndex.setInitialized(relationType, false));
    }
    CreateIndexResponse indexResponse = client.create(new CreateIndexRequest(index.getName()).settings((settings)));
    if (!indexResponse.isAcknowledged()) {
        throw new IllegalStateException("Failed to create index [" + index.getName() + "]");
    }
    client.waitForStatus(ClusterHealthStatus.YELLOW);
    // create types
    LOGGER.info("Create type {}", builtIndex.getMainType().format());
    AcknowledgedResponse mappingResponse = client.putMapping(new PutMappingRequest(builtIndex.getMainType().getIndex().getName()).type(builtIndex.getMainType().getType()).source(builtIndex.getAttributes()));
    if (!mappingResponse.isAcknowledged()) {
        throw new IllegalStateException("Failed to create type " + builtIndex.getMainType().getType());
    }
    client.waitForStatus(ClusterHealthStatus.YELLOW);
}
Also used : PutMappingRequest(org.elasticsearch.action.admin.indices.mapping.put.PutMappingRequest) AcknowledgedResponse(org.elasticsearch.action.support.master.AcknowledgedResponse) BuiltIndex(org.sonar.server.es.newindex.BuiltIndex) MetadataIndex(org.sonar.server.es.metadata.MetadataIndex) NewIndex(org.sonar.server.es.newindex.NewIndex) CreateIndexResponse(org.elasticsearch.client.indices.CreateIndexResponse) CreateIndexRequest(org.elasticsearch.client.indices.CreateIndexRequest) Settings(org.elasticsearch.common.settings.Settings)

Example 4 with CreateIndexResponse

use of org.elasticsearch.client.indices.CreateIndexResponse in project snow-owl by b2ihealthcare.

the class EsIndexAdmin method create.

@Override
public void create() {
    log.info("Preparing '{}' indexes...", name);
    // register any type that requires a refresh at the end of the index create/open
    Set<DocumentMapping> mappingsToRefresh = Sets.newHashSet();
    // create number of indexes based on number of types
    for (DocumentMapping mapping : mappings.getMappings()) {
        final String index = getTypeIndex(mapping);
        final Map<String, Object> typeMapping = ImmutableMap.<String, Object>builder().put("date_detection", false).put("numeric_detection", false).put("dynamic_templates", List.of(stringsAsKeywords())).putAll(toProperties(mapping)).build();
        if (exists(mapping)) {
            // update mapping if required
            final MappingMetadata currentIndexMapping;
            try {
                final GetMappingsRequest getMappingsRequest = new GetMappingsRequest().indices(index);
                currentIndexMapping = client.indices().getMapping(getMappingsRequest).mappings().get(index);
            } catch (Exception e) {
                throw new IndexException(String.format("Failed to get mapping of '%s' for type '%s'", name, mapping.typeAsString()), e);
            }
            try {
                final ObjectNode newTypeMapping = mapper.valueToTree(typeMapping);
                final ObjectNode currentTypeMapping = mapper.valueToTree(currentIndexMapping.getSourceAsMap());
                SortedSet<String> compatibleChanges = Sets.newTreeSet();
                SortedSet<String> incompatibleChanges = Sets.newTreeSet();
                JsonDiff.diff(currentTypeMapping, newTypeMapping).forEach(change -> {
                    if (change.isAdd()) {
                        compatibleChanges.add(change.getFieldPath());
                    } else if (change.isMove() || change.isReplace()) {
                        incompatibleChanges.add(change.getFieldPath());
                    }
                });
                if (!incompatibleChanges.isEmpty()) {
                    log.warn("Cannot migrate index '{}' to new mapping with breaking changes on properties '{}'. Run repository reindex to migrate to new mapping schema or drop that index manually using the Elasticsearch API.", index, incompatibleChanges);
                } else if (!compatibleChanges.isEmpty()) {
                    log.info("Applying mapping changes {} in index {}", compatibleChanges, index);
                    PutMappingRequest putMappingRequest = new PutMappingRequest(index).source(typeMapping);
                    AcknowledgedResponse response = client.indices().updateMapping(putMappingRequest);
                    checkState(response.isAcknowledged(), "Failed to update mapping '%s' for type '%s'", name, mapping.typeAsString());
                    // new fields do not require reindex, they will be added to new documents, existing documents don't have any data that needs reindex
                    if (hasFieldAliasChange(compatibleChanges)) {
                        if (bulkIndexByScroll(client, mapping, Expressions.matchAll(), "update", null, /*no script, in place update of docs to pick up mapping changes*/
                        "mapping migration")) {
                            mappingsToRefresh.add(mapping);
                        }
                        log.info("Migrated documents to new mapping in index '{}'", index);
                    }
                }
            } catch (IOException e) {
                throw new IndexException(String.format("Failed to update mapping '%s' for type '%s'", name, mapping.typeAsString()), e);
            }
        } else {
            // create index
            final Map<String, Object> indexSettings;
            try {
                indexSettings = createIndexSettings();
                log.info("Configuring '{}' index with settings: {}", index, indexSettings);
            } catch (IOException e) {
                throw new IndexException("Couldn't prepare settings for index " + index, e);
            }
            final CreateIndexRequest createIndexRequest = new CreateIndexRequest(index).mapping(typeMapping).settings(indexSettings);
            try {
                final CreateIndexResponse response = client.indices().create(createIndexRequest);
                checkState(response.isAcknowledged(), "Failed to create index '%s' for type '%s'", name, mapping.typeAsString());
            } catch (Exception e) {
                throw new IndexException(String.format("Failed to create index '%s' for type '%s'", name, mapping.typeAsString()), e);
            }
        }
    }
    // wait until the cluster processes each index create request
    waitForYellowHealth(indices());
    if (!mappingsToRefresh.isEmpty()) {
        refresh(mappingsToRefresh);
    }
    log.info("'{}' indexes are ready.", name);
}
Also used : ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) PutMappingRequest(org.elasticsearch.client.indices.PutMappingRequest) AcknowledgedResponse(org.elasticsearch.action.support.master.AcknowledgedResponse) IOException(java.io.IOException) GetMappingsRequest(org.elasticsearch.client.indices.GetMappingsRequest) DocumentMapping(com.b2international.index.mapping.DocumentMapping) IOException(java.io.IOException) CreateIndexRequest(org.elasticsearch.client.indices.CreateIndexRequest) CreateIndexResponse(org.elasticsearch.client.indices.CreateIndexResponse) MappingMetadata(org.elasticsearch.cluster.metadata.MappingMetadata)

Aggregations

CreateIndexResponse (org.elasticsearch.client.indices.CreateIndexResponse)4 CreateIndexRequest (org.elasticsearch.client.indices.CreateIndexRequest)3 IOException (java.io.IOException)2 AcknowledgedResponse (org.elasticsearch.action.support.master.AcknowledgedResponse)2 Settings (org.elasticsearch.common.settings.Settings)2 BuiltIndex (org.sonar.server.es.newindex.BuiltIndex)2 NewIndex (org.sonar.server.es.newindex.NewIndex)2 DocumentMapping (com.b2international.index.mapping.DocumentMapping)1 ObjectNode (com.fasterxml.jackson.databind.node.ObjectNode)1 Lists.newArrayList (com.google.common.collect.Lists.newArrayList)1 ArrayList (java.util.ArrayList)1 PutMappingRequest (org.elasticsearch.action.admin.indices.mapping.put.PutMappingRequest)1 OpenIndexRequest (org.elasticsearch.action.admin.indices.open.OpenIndexRequest)1 GetMappingsRequest (org.elasticsearch.client.indices.GetMappingsRequest)1 PutMappingRequest (org.elasticsearch.client.indices.PutMappingRequest)1 MappingMetadata (org.elasticsearch.cluster.metadata.MappingMetadata)1 DiskThresholdSettings (org.elasticsearch.cluster.routing.allocation.DiskThresholdSettings)1 HttpTransportSettings (org.elasticsearch.http.HttpTransportSettings)1 RecoverySettings (org.elasticsearch.indices.recovery.RecoverySettings)1 IndexDefinitionContext (org.sonar.server.es.IndexDefinition.IndexDefinitionContext)1