org.elasticsearch.action.admin.indices.alias.Alias Java Examples

The following examples show how to use org.elasticsearch.action.admin.indices.alias.Alias. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RandomCreateIndexGenerator.java    From crate with Apache License 2.0 6 votes vote down vote up
private static Alias randomAlias() {
    Alias alias = new Alias(randomAlphaOfLength(5));

    if (randomBoolean()) {
        if (randomBoolean()) {
            alias.routing(randomAlphaOfLength(5));
        } else {
            if (randomBoolean()) {
                alias.indexRouting(randomAlphaOfLength(5));
            }
            if (randomBoolean()) {
                alias.searchRouting(randomAlphaOfLength(5));
            }
        }
    }

    if (randomBoolean()) {
        alias.filter("{\"term\":{\"year\":2016}}");
    }

    if (randomBoolean()) {
        alias.writeIndex(randomBoolean());
    }

    return alias;
}
 
Example #2
Source File: CreateIndexRequest.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
@Override
public void readFrom(StreamInput in) throws IOException {
    super.readFrom(in);
    cause = in.readString();
    index = in.readString();
    settings = readSettingsFromStream(in);
    readTimeout(in);
    int size = in.readVInt();
    for (int i = 0; i < size; i++) {
        mappings.put(in.readString(), in.readString());
    }
    int customSize = in.readVInt();
    for (int i = 0; i < customSize; i++) {
        String type = in.readString();
        IndexMetaData.Custom customIndexMetaData = IndexMetaData.lookupPrototypeSafe(type).readFrom(in);
        customs.put(type, customIndexMetaData);
    }
    int aliasesSize = in.readVInt();
    for (int i = 0; i < aliasesSize; i++) {
        aliases.add(Alias.read(in));
    }
    updateAllTypes = in.readBoolean();
}
 
Example #3
Source File: PutIndexTemplateRequest.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
@Override
public void readFrom(StreamInput in) throws IOException {
    super.readFrom(in);
    cause = in.readString();
    name = in.readString();
    template = in.readString();
    order = in.readInt();
    create = in.readBoolean();
    settings = readSettingsFromStream(in);
    int size = in.readVInt();
    for (int i = 0; i < size; i++) {
        mappings.put(in.readString(), in.readString());
    }
    int customSize = in.readVInt();
    for (int i = 0; i < customSize; i++) {
        String type = in.readString();
        IndexMetaData.Custom customIndexMetaData = IndexMetaData.lookupPrototypeSafe(type).readFrom(in);
        customs.put(type, customIndexMetaData);
    }
    int aliasesSize = in.readVInt();
    for (int i = 0; i < aliasesSize; i++) {
        aliases.add(Alias.read(in));
    }
}
 
Example #4
Source File: ElasticSearch7Client.java    From skywalking with Apache License 2.0 6 votes vote down vote up
public boolean createTemplate(String indexName, Map<String, Object> settings,
                              Map<String, Object> mapping) throws IOException {
    indexName = formatIndexName(indexName);

    PutIndexTemplateRequest putIndexTemplateRequest = new PutIndexTemplateRequest(indexName).patterns(
        Collections.singletonList(indexName + "-*"))
                                                                                            .alias(new Alias(
                                                                                                indexName))
                                                                                            .settings(settings)
                                                                                            .mapping(mapping);

    AcknowledgedResponse acknowledgedResponse = client.indices()
                                                      .putTemplate(putIndexTemplateRequest, RequestOptions.DEFAULT);

    return acknowledgedResponse.isAcknowledged();
}
 
Example #5
Source File: CreateIndexRequest.java    From crate with Apache License 2.0 6 votes vote down vote up
public CreateIndexRequest(StreamInput in) throws IOException {
    super(in);
    cause = in.readString();
    index = in.readString();
    settings = readSettingsFromStream(in);
    int size = in.readVInt();
    for (int i = 0; i < size; i++) {
        final String type = in.readString();
        String source = in.readString();
        mappings.put(type, source);
    }
    int aliasesSize = in.readVInt();
    for (int i = 0; i < aliasesSize; i++) {
        aliases.add(new Alias(in));
    }
    updateAllTypes = in.readBoolean();
    waitForActiveShards = ActiveShardCount.readFrom(in);
}
 
Example #6
Source File: CreateIndexRequest.java    From crate with Apache License 2.0 6 votes vote down vote up
@Override
public void writeTo(StreamOutput out) throws IOException {
    super.writeTo(out);
    out.writeString(cause);
    out.writeString(index);
    writeSettingsToStream(settings, out);
    out.writeVInt(mappings.size());
    for (Map.Entry<String, String> entry : mappings.entrySet()) {
        out.writeString(entry.getKey());
        out.writeString(entry.getValue());
    }
    out.writeVInt(aliases.size());
    for (Alias alias : aliases) {
        alias.writeTo(out);
    }
    out.writeBoolean(updateAllTypes);
    waitForActiveShards.writeTo(out);
}
 
Example #7
Source File: PutIndexTemplateRequest.java    From crate with Apache License 2.0 6 votes vote down vote up
public PutIndexTemplateRequest(StreamInput in) throws IOException {
    super(in);
    cause = in.readString();
    name = in.readString();

    indexPatterns = in.readList(StreamInput::readString);
    order = in.readInt();
    create = in.readBoolean();
    settings = readSettingsFromStream(in);
    int size = in.readVInt();
    for (int i = 0; i < size; i++) {
        final String type = in.readString();
        String mappingSource = in.readString();
        mappings.put(type, mappingSource);
    }
    int aliasesSize = in.readVInt();
    for (int i = 0; i < aliasesSize; i++) {
        aliases.add(new Alias(in));
    }
    version = in.readOptionalVInt();
}
 
Example #8
Source File: PutIndexTemplateRequest.java    From crate with Apache License 2.0 6 votes vote down vote up
@Override
public void writeTo(StreamOutput out) throws IOException {
    super.writeTo(out);
    out.writeString(cause);
    out.writeString(name);
    out.writeStringCollection(indexPatterns);
    out.writeInt(order);
    out.writeBoolean(create);
    writeSettingsToStream(settings, out);
    out.writeVInt(mappings.size());
    for (Map.Entry<String, String> entry : mappings.entrySet()) {
        out.writeString(entry.getKey());
        out.writeString(entry.getValue());
    }
    out.writeVInt(aliases.size());
    for (Alias alias : aliases) {
        alias.writeTo(out);
    }
    out.writeOptionalVInt(version);
}
 
Example #9
Source File: ElasticsearchIndexInitializer.java    From staccato with Apache License 2.0 6 votes vote down vote up
private boolean createTemplate(CollectionMetadata collection) throws Exception {
    String searchAlias = collection.getId() + "-search";
    String indexTemplateName = collection.getId() + "-template";
    String indexTemplatePattern = collection.getId() + "-*";

    log.debug("Attempting to initialize template for collection '" + collection.getId() + "'");

    PutIndexTemplateRequest request = new PutIndexTemplateRequest(indexTemplateName)
            .patterns(Arrays.asList(indexTemplatePattern))
            .alias(new Alias(searchAlias))
            .mapping("_doc", buildMappings(collection));

    client.indices().putTemplate(request, RequestOptions.DEFAULT);

    log.info("Template '" + indexTemplateName + "' for collection '" + collection.getId() + "' initialized");
    return true;
}
 
Example #10
Source File: AlterTableOperation.java    From crate with Apache License 2.0 6 votes vote down vote up
private CompletableFuture<Long> resizeIndex(IndexMetaData sourceIndex,
                                            @Nullable String sourceIndexAlias,
                                            String targetIndexName,
                                            int targetNumberOfShards) {
    Settings targetIndexSettings = Settings.builder()
        .put(SETTING_NUMBER_OF_SHARDS, targetNumberOfShards)
        .build();

    int currentNumShards = sourceIndex.getNumberOfShards();
    ResizeRequest request = new ResizeRequest(targetIndexName, sourceIndex.getIndex().getName());
    request.getTargetIndexRequest().settings(targetIndexSettings);
    if (sourceIndexAlias != null) {
        request.getTargetIndexRequest().alias(new Alias(sourceIndexAlias));
    }
    request.setResizeType(targetNumberOfShards > currentNumShards ? ResizeType.SPLIT : ResizeType.SHRINK);
    request.setCopySettings(Boolean.TRUE);
    request.setWaitForActiveShards(ActiveShardCount.ONE);
    FutureActionListener<ResizeResponse, Long> listener =
        new FutureActionListener<>(resp -> resp.isAcknowledged() ? 1L : 0L);

    transportResizeAction.execute(request, listener);
    return listener;
}
 
Example #11
Source File: PutIndexTemplateRequest.java    From crate with Apache License 2.0 5 votes vote down vote up
/**
 * Sets the aliases that will be associated with the index when it gets created
 */
public PutIndexTemplateRequest aliases(BytesReference source) {
    // EMPTY is safe here because we never call namedObject
    try (XContentParser parser = XContentHelper
            .createParser(NamedXContentRegistry.EMPTY, LoggingDeprecationHandler.INSTANCE, source)) {
        //move to the first alias
        parser.nextToken();
        while ((parser.nextToken()) != XContentParser.Token.END_OBJECT) {
            alias(Alias.fromXContent(parser));
        }
        return this;
    } catch (IOException e) {
        throw new ElasticsearchParseException("Failed to parse aliases", e);
    }
}
 
Example #12
Source File: CreateIndexRequest.java    From crate with Apache License 2.0 5 votes vote down vote up
/**
 * Sets the aliases that will be associated with the index when it gets created
 */
public CreateIndexRequest aliases(BytesReference source) {
    // EMPTY is safe here because we never call namedObject
    try (XContentParser parser = XContentHelper
            .createParser(NamedXContentRegistry.EMPTY, LoggingDeprecationHandler.INSTANCE, source)) {
        //move to the first alias
        parser.nextToken();
        while ((parser.nextToken()) != XContentParser.Token.END_OBJECT) {
            alias(Alias.fromXContent(parser));
        }
        return this;
    } catch (IOException e) {
        throw new ElasticsearchParseException("Failed to parse aliases", e);
    }
}
 
Example #13
Source File: AliasValidator.java    From crate with Apache License 2.0 5 votes vote down vote up
/**
 * Allows to partially validate an alias, without knowing which index it'll get applied to.
 * Useful with index templates containing aliases. Checks also that it is possible to parse
 * the alias filter via {@link org.elasticsearch.common.xcontent.XContentParser},
 * without validating it as a filter though.
 * @throws IllegalArgumentException if the alias is not valid
 */
public void validateAliasStandalone(Alias alias) {
    validateAliasStandalone(alias.name(), alias.indexRouting());
    if (Strings.hasLength(alias.filter())) {
        try {
            XContentHelper.convertToMap(XContentFactory.xContent(alias.filter()), alias.filter(), false);
        } catch (Exception e) {
            throw new IllegalArgumentException("failed to parse filter for alias [" + alias.name() + "]", e);
        }
    }
}
 
Example #14
Source File: TableCreator.java    From crate with Apache License 2.0 5 votes vote down vote up
public CompletableFuture<Long> create(BoundCreateTable createTable) {
    var templateName = createTable.templateName();
    var relationName = createTable.tableIdent();
    var createTableRequest = templateName == null
        ? new CreateTableRequest(
            new CreateIndexRequest(
                relationName.indexNameOrAlias(),
                createTable.tableParameter().settings()
            ).mapping(Constants.DEFAULT_MAPPING_TYPE, createTable.mapping())
        )
        : new CreateTableRequest(
            new PutIndexTemplateRequest(templateName)
                .mapping(Constants.DEFAULT_MAPPING_TYPE, createTable.mapping())
                .create(true)
                .settings(createTable.tableParameter().settings())
                .patterns(Collections.singletonList(createTable.templatePrefix()))
                .order(100)
                .alias(new Alias(relationName.indexNameOrAlias()))
    );
    return Transports.execute(transportCreateTableAction, createTableRequest, resp -> {
        if (!resp.isAllShardsAcked() && LOGGER.isWarnEnabled()) {
            LOGGER.warn("CREATE TABLE `{}` was not acknowledged. This could lead to inconsistent state.", relationName.fqn());
        }
        return 1L;
    }).exceptionally(error -> {
        Throwable t = SQLExceptions.unwrap(error);
        String message = t.getMessage();
        Throwable cause = t.getCause();
        if ("mapping [default]".equals(message) && cause != null) {
            // this is a generic mapping parse exception,
            // the cause has usually a better more detailed error message
            return Exceptions.rethrowRuntimeException(cause);
        } else if (createTable.ifNotExists() && isTableExistsError(t, templateName)) {
            return 0L;
        } else {
            return Exceptions.rethrowRuntimeException(t);
        }
    });
}
 
Example #15
Source File: PutIndexTemplateRequest.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
/**
 * Sets the aliases that will be associated with the index when it gets created
 */
public PutIndexTemplateRequest aliases(BytesReference source) {
    try {
        XContentParser parser = XContentHelper.createParser(source);
        //move to the first alias
        parser.nextToken();
        while ((parser.nextToken()) != XContentParser.Token.END_OBJECT) {
            alias(Alias.fromXContent(parser));
        }
        return this;
    } catch(IOException e) {
        throw new ElasticsearchParseException("Failed to parse aliases", e);
    }
}
 
Example #16
Source File: MultitenancyTests.java    From deprecated-security-advanced-modules with Apache License 2.0 5 votes vote down vote up
@Test
public void testKibanaAlias65() throws Exception {
    final Settings settings = Settings.builder()
            .build();
    setup(settings);

    try (TransportClient tc = getInternalTransportClient()) {
        String body = "{\"buildNum\": 15460, \"defaultIndex\": \"humanresources\", \"tenant\": \"human_resources\"}";
        Map indexSettings = new HashMap();
        indexSettings.put("number_of_shards", 1);
        indexSettings.put("number_of_replicas", 0);
        tc.admin().indices().create(new CreateIndexRequest(".kibana_1")
            .alias(new Alias(".kibana"))
            .settings(indexSettings))
            .actionGet();

        tc.index(new IndexRequest(".kibana_1").type("doc").id("6.2.2").setRefreshPolicy(RefreshPolicy.IMMEDIATE).source(body, XContentType.JSON)).actionGet();
        tc.index(new IndexRequest(".kibana_-900636979_kibanaro").type("doc").id("6.2.2").setRefreshPolicy(RefreshPolicy.IMMEDIATE).source(body, XContentType.JSON)).actionGet();

    }

    final RestHelper rh = nonSslRestHelper();

    HttpResponse res;
    Assert.assertEquals(HttpStatus.SC_OK, (res = rh.executeGetRequest(".kibana/doc/6.2.2?pretty", new BasicHeader("securitytenant", "__user__"), encodeBasicHeader("kibanaro", "kibanaro"))).getStatusCode());
    System.out.println(res.getBody());
    Assert.assertTrue(res.getBody().contains(".kibana_-900636979_kibanaro"));
}
 
Example #17
Source File: CreateIndexRequest.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
/**
 * Sets the aliases that will be associated with the index when it gets created
 */
public CreateIndexRequest aliases(BytesReference source) {
    try {
        XContentParser parser = XContentHelper.createParser(source);
        //move to the first alias
        parser.nextToken();
        while ((parser.nextToken()) != XContentParser.Token.END_OBJECT) {
            alias(Alias.fromXContent(parser));
        }
        return this;
    } catch(IOException e) {
        throw new ElasticsearchParseException("Failed to parse aliases", e);
    }
}
 
Example #18
Source File: DocIndexMetaData.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
private void updateTemplate(DocIndexMetaData md,
                            TransportPutIndexTemplateAction transportPutIndexTemplateAction,
                            Settings updateSettings) {
    String templateName = PartitionName.templateName(ident.schema(), ident.name());
    PutIndexTemplateRequest request = new PutIndexTemplateRequest(templateName)
            .mapping(Constants.DEFAULT_MAPPING_TYPE, md.defaultMappingMap)
            .create(false)
            .settings(updateSettings)
            .template(templateName + "*");
    for (String alias : md.aliases()) {
        request = request.alias(new Alias(alias));
    }
    transportPutIndexTemplateAction.execute(request);
}
 
Example #19
Source File: MultitenancyTests.java    From deprecated-security-advanced-modules with Apache License 2.0 5 votes vote down vote up
@Test
public void testKibanaAlias() throws Exception {
    final Settings settings = Settings.builder()
            .build();
    setup(settings);

    try (TransportClient tc = getInternalTransportClient()) {
        String body = "{\"buildNum\": 15460, \"defaultIndex\": \"humanresources\", \"tenant\": \"human_resources\"}";
        Map indexSettings = new HashMap();
        indexSettings.put("number_of_shards", 1);
        indexSettings.put("number_of_replicas", 0);
        tc.admin().indices().create(new CreateIndexRequest(".kibana-6")
            .alias(new Alias(".kibana"))
            .settings(indexSettings))
            .actionGet();

        tc.index(new IndexRequest(".kibana-6").type("doc").id("6.2.2").setRefreshPolicy(RefreshPolicy.IMMEDIATE).source(body, XContentType.JSON)).actionGet();
    }

    final RestHelper rh = nonSslRestHelper();

    HttpResponse res;
    Assert.assertEquals(HttpStatus.SC_OK, (res = rh.executeGetRequest(".kibana-6/doc/6.2.2?pretty", encodeBasicHeader("kibanaro", "kibanaro"))).getStatusCode());
    Assert.assertEquals(HttpStatus.SC_OK, (res = rh.executeGetRequest(".kibana/doc/6.2.2?pretty", encodeBasicHeader("kibanaro", "kibanaro"))).getStatusCode());

    System.out.println(res.getBody());

}
 
Example #20
Source File: TemplateElasticSearchIndexStrategy.java    From jetlinks-community with Apache License 2.0 5 votes vote down vote up
protected PutIndexTemplateRequest createIndexTemplateRequest(ElasticSearchIndexMetadata metadata) {
    String index = wrapIndex(metadata.getIndex());
    PutIndexTemplateRequest request = new PutIndexTemplateRequest(getTemplate(index));
    request.alias(new Alias(getAlias(index)));
    request.settings(properties.toSettings());
    Map<String, Object> mappingConfig = new HashMap<>();
    mappingConfig.put("properties", createElasticProperties(metadata.getProperties()));
    mappingConfig.put("dynamic_templates", createDynamicTemplates());
    request.mapping(mappingConfig);
    request.patterns(getIndexPatterns(index));
    return request;
}
 
Example #21
Source File: AnomalyDetectionIndices.java    From anomaly-detection with Apache License 2.0 5 votes vote down vote up
/**
 * Create anomaly detector index without checking exist or not.
 *
 * @param actionListener action called after create index
 * @throws IOException IOException from {@link AnomalyDetectionIndices#getAnomalyDetectorMappings}
 */
public void initAnomalyResultIndexDirectly(ActionListener<CreateIndexResponse> actionListener) throws IOException {
    String mapping = getAnomalyResultMappings();
    CreateIndexRequest request = new CreateIndexRequest(AD_RESULT_HISTORY_INDEX_PATTERN)
        .mapping(MAPPING_TYPE, mapping, XContentType.JSON)
        .alias(new Alias(AD_RESULT_HISTORY_WRITE_INDEX_ALIAS));
    adminClient.indices().create(request, actionListener);
}
 
Example #22
Source File: ElasticsearchIndexInitializer.java    From staccato with Apache License 2.0 5 votes vote down vote up
private boolean createInitialIndex(CollectionMetadata collection) throws Exception {
    String initialIndexName = collection.getId() + "-000001";
    String writeAlias = collection.getId();

    CreateIndexRequest request = new CreateIndexRequest(initialIndexName);
    request.alias(new Alias(writeAlias))
            .settings(Settings.builder()
                            .put("index.number_of_shards", configProps.getNumberOfShards())
                            .put("index.number_of_replicas", configProps.getNumberOfReplicas()));

    client.indices().create(request, RequestOptions.DEFAULT);
    log.info("Index '" + initialIndexName + "' for collection '" + collection.getId() + "' initialized");
    return true;
}
 
Example #23
Source File: ElasticSearchReader.java    From garmadon with Apache License 2.0 5 votes vote down vote up
private static void putGarmadonTemplate(RestHighLevelClient esClient, ElasticsearchConfiguration elasticsearch)
    throws IOException, GarmadonEsException {
    PutIndexTemplateRequest indexRequest = new PutIndexTemplateRequest("garmadon");
    indexRequest.patterns(Collections.singletonList(elasticsearch.getIndexPrefix() + "*"));

    // Create template settings with mandatory one
    Settings.Builder templateSettings = Settings.builder()
        .put("sort.field", "timestamp")
        .put("sort.order", "desc")
        .put("analysis.analyzer.path_analyzer.tokenizer", "path_tokenizer")
        .put("analysis.tokenizer.path_tokenizer.type", "path_hierarchy")
        .put("analysis.tokenizer.path_tokenizer.delimiter", "/")
        .put("index.lifecycle.name", "garmadon")
        .put("index.lifecycle.rollover_alias", "garmadon");

    // Add settings from config
    elasticsearch.getSettings().forEach(templateSettings::put);

    indexRequest.settings(templateSettings);

    // Add garmadon alias
    Alias alias = new Alias("garmadon");
    indexRequest.alias(alias);

    String template = IOUtils.toString(Objects.requireNonNull(ElasticSearchReader.class.getClassLoader()
        .getResourceAsStream("template.json")), "UTF-8");

    indexRequest.mapping(ES_TYPE, template, XContentType.JSON);

    if (!esClient.indices().putTemplate(indexRequest, RequestOptions.DEFAULT).isAcknowledged()) {
        throw new GarmadonEsException("Failed to insert garmadon template");
    }
}
 
Example #24
Source File: AliasValidator.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
/**
 * Allows to partially validate an alias, without knowing which index it'll get applied to.
 * Useful with index templates containing aliases. Checks also that it is possible to parse
 * the alias filter via {@link org.elasticsearch.common.xcontent.XContentParser},
 * without validating it as a filter though.
 * @throws IllegalArgumentException if the alias is not valid
 */
public void validateAliasStandalone(Alias alias) {
    validateAliasStandalone(alias.name(), alias.indexRouting());
    if (Strings.hasLength(alias.filter())) {
        try (XContentParser parser = XContentFactory.xContent(alias.filter()).createParser(alias.filter())) {
            parser.map();
        } catch (Throwable e) {
            throw new IllegalArgumentException("failed to parse filter for alias [" + alias.name() + "]", e);
        }
    }
}
 
Example #25
Source File: AlterTableOperation.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
private ListenableFuture<Long> updateTemplate(Map<String, Object> newMappings,
                                              Settings newSettings,
                                              TableIdent tableIdent,
                                              AbstractDDLAnalyzedStatement statement) {
    String templateName = PartitionName.templateName(tableIdent.schema(), tableIdent.name());
    IndexTemplateMetaData indexTemplateMetaData =
            clusterService.state().metaData().templates().get(templateName);
    if (indexTemplateMetaData == null) {
        return Futures.immediateFailedFuture(new RuntimeException("Template for partitioned table is missing"));
    }

    // merge mappings
    Map<String, Object> mapping = mergeTemplateMapping(indexTemplateMetaData, newMappings);

    // merge settings
    Settings.Builder settingsBuilder = Settings.builder();
    settingsBuilder.put(indexTemplateMetaData.settings());
    settingsBuilder.put(newSettings);

    PutIndexTemplateRequest request = new PutIndexTemplateRequest(templateName)
            .create(false)
            .mapping(Constants.DEFAULT_MAPPING_TYPE, mapping)
            .order(indexTemplateMetaData.order())
            .settings(settingsBuilder.build())
            .template(indexTemplateMetaData.template());

    request.putHeader(LoginUserContext.USER_INFO_KEY, statement.getParameterContext().getLoginUserContext());
    for (ObjectObjectCursor<String, AliasMetaData> container : indexTemplateMetaData.aliases()) {
        Alias alias = new Alias(container.key);
        request.alias(alias);
    }

    SettableFuture<Long> result = SettableFuture.create();
    transportActionProvider.transportPutIndexTemplateAction().execute(request,
            new SettableFutureToNullActionListener<PutIndexTemplateResponse>(result));

    return result;
}
 
Example #26
Source File: TableCreator.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
private PutIndexTemplateRequest createTemplateRequest(CreateTableAnalyzedStatement statement) {
    PutIndexTemplateRequest putIndexTemplateRequest = new PutIndexTemplateRequest(statement.templateName())
            .mapping(Constants.DEFAULT_MAPPING_TYPE, statement.mapping())
            .create(true)
            .settings(settings(statement))
            .template(statement.templatePrefix())
            .order(100)
            .alias(new Alias(statement.tableIdent().indexName()));
    putIndexTemplateRequest.putHeader(LoginUserContext.USER_INFO_KEY, statement.getParameterContext().getLoginUserContext());
    return putIndexTemplateRequest;
}
 
Example #27
Source File: ESCreateTemplateTask.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
private PutIndexTemplateRequest buildRequest(ESCreateTemplateNode node) {
    PutIndexTemplateRequest templateRequest = new PutIndexTemplateRequest(node.templateName())
            .mapping(Constants.DEFAULT_MAPPING_TYPE, node.mapping())
            .create(true)
            .settings(node.indexSettings())
            .template(node.indexMatch());
    if (node.alias() != null) {
        templateRequest.alias(new Alias(node.alias()));
    }

    templateRequest.putHeader(LoginUserContext.USER_INFO_KEY, getParamContext().getLoginUserContext());
    return templateRequest;
}
 
Example #28
Source File: CreateIndexClusterStateUpdateRequest.java    From crate with Apache License 2.0 4 votes vote down vote up
public Set<Alias> aliases() {
    return aliases;
}
 
Example #29
Source File: CreateIndexRequest.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
public Set<Alias> aliases() {
    return this.aliases;
}
 
Example #30
Source File: CreateIndexRequestBuilder.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
/**
 * Adds an alias that will be associated with the index when it gets created
 */
public CreateIndexRequestBuilder addAlias(Alias alias) {
    request.alias(alias);
    return this;
}