org.elasticsearch.indices.IndexAlreadyExistsException Java Examples

The following examples show how to use org.elasticsearch.indices.IndexAlreadyExistsException. 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: TableCreator.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
private void setException(SettableFuture<Long> result, Throwable e, CreateTableAnalyzedStatement statement) {
    e = Exceptions.unwrap(e);
    String message = e.getMessage();
    // sometimes message is empty
    if ("mapping [default]".equals(message) && e.getCause() != null) {
        // this is a generic mapping parse exception,
        // the cause has usually a better more detailed error message
        result.setException(e.getCause());
    } else if (statement.ifNotExists() &&
               (e instanceof IndexAlreadyExistsException
                || (e instanceof IndexTemplateAlreadyExistsException && statement.templateName() != null))) {
        result.set(null);
    } else {
        result.setException(e);
    }
}
 
Example #2
Source File: UpsertByIdTask.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
private void createIndexAndExecuteUpsertRequest(final UpsertByIdNode.Item item,
                                                final SettableFuture<TaskResult> futureResult) {
    transportCreateIndexAction.execute(
            new CreateIndexRequest(item.index()).cause("upsert single item"),
            new ActionListener<CreateIndexResponse>() {
        @Override
        public void onResponse(CreateIndexResponse createIndexResponse) {
            executeUpsertRequest(item, futureResult);
        }

        @Override
        public void onFailure(Throwable e) {
            e = ExceptionsHelper.unwrapCause(e);
            if (e instanceof IndexAlreadyExistsException) {
                executeUpsertRequest(item, futureResult);
            } else {
                futureResult.setException(e);
            }

        }
    });
}
 
Example #3
Source File: TransportDeleteAction.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
@Override
protected void doExecute(final Task task, final DeleteRequest request, final ActionListener<DeleteResponse> listener) {
    ClusterState state = clusterService.state();
    if (autoCreateIndex.shouldAutoCreate(request.index(), state)) {
        createIndexAction.execute(task, new CreateIndexRequest(request).index(request.index()).cause("auto(delete api)")
            .masterNodeTimeout(request.timeout()), new ActionListener<CreateIndexResponse>() {
            @Override
            public void onResponse(CreateIndexResponse result) {
                innerExecute(task, request, listener);
            }

            @Override
            public void onFailure(Throwable e) {
                if (ExceptionsHelper.unwrapCause(e) instanceof IndexAlreadyExistsException) {
                    // we have the index, do it
                    innerExecute(task, request, listener);
                } else {
                    listener.onFailure(e);
                }
            }
        });
    } else {
        innerExecute(task, request, listener);
    }
}
 
Example #4
Source File: TransportBaseSQLAction.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the cause throwable of a {@link org.elasticsearch.transport.RemoteTransportException}
 * and {@link org.elasticsearch.action.search.ReduceSearchPhaseException}.
 * Also transform throwable to {@link io.crate.exceptions.CrateException}.
 */
private Throwable esToCrateException(Throwable e) {
    e = Exceptions.unwrap(e);

    if (e instanceof IllegalArgumentException || e instanceof ParsingException) {
        return new SQLParseException(e.getMessage(), (Exception) e);
    } else if (e instanceof UnsupportedOperationException) {
        return new UnsupportedFeatureException(e.getMessage(), (Exception) e);
    } else if (e instanceof DocumentAlreadyExistsException) {
        return new DuplicateKeyException(
                "A document with the same primary key exists already", e);
    } else if (e instanceof IndexAlreadyExistsException) {
        return new TableAlreadyExistsException(((IndexAlreadyExistsException) e).getIndex(), e);
    } else if ((e instanceof InvalidIndexNameException)) {
        if (e.getMessage().contains("already exists as alias")) {
            // treat an alias like a table as aliases are not officially supported
            return new TableAlreadyExistsException(((InvalidIndexNameException) e).getIndex(),
                    e);
        }
        return new InvalidTableNameException(((InvalidIndexNameException) e).getIndex(), e);
    } else if (e instanceof InvalidIndexTemplateException) {
        PartitionName partitionName = PartitionName.fromIndexOrTemplate(((InvalidIndexTemplateException) e).name());
        return new InvalidTableNameException(partitionName.tableIdent().fqn(), e);
    } else if (e instanceof IndexNotFoundException) {
        return new TableUnknownException(((IndexNotFoundException) e).getIndex(), e);
    } else if (e instanceof org.elasticsearch.common.breaker.CircuitBreakingException) {
        return new CircuitBreakingException(e.getMessage());
    } else if (e instanceof InterruptedException) {
        return new JobKilledException();
    } else if (e instanceof RepositoryMissingException) {
        return new RepositoryUnknownException(((RepositoryMissingException) e).repository());
    } else if (e instanceof SnapshotMissingException) {
        return new SnapshotUnknownException(((SnapshotMissingException) e).snapshot(), e);
    } else if (e instanceof InvalidSnapshotNameException) {
        if (((InvalidSnapshotNameException) e).getDetailedMessage().contains("snapshot with such name already exists")) {
            return new SnapShotAlreadyExistsExeption(((InvalidSnapshotNameException) e).snapshot());
        }
    }
    return e;
}
 
Example #5
Source File: BaseElasticSearchIndexBuilder.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/**
 * creates a new index, does not check if the exist exists
 */
protected void createIndex() {
    try {
        CreateIndexResponse createResponse = client.admin().indices().create(new CreateIndexRequest(indexName)
                .settings(indexSettingsMerged).mapping(indexedDocumentType, mappingMerged)).actionGet();
        if (!createResponse.isAcknowledged()) {
            getLog().error("Index wasn't created for index builder [" + getName() + "], can't rebuild");
        }
    } catch (IndexAlreadyExistsException e) {
        getLog().warn("Index already created for index builder [" + getName() + "]");
    }
}
 
Example #6
Source File: EsIndexImpl.java    From io with Apache License 2.0 5 votes vote down vote up
@Override
CreateIndexResponse onParticularError(ElasticsearchException e) {
    if (e instanceof IndexAlreadyExistsException
            || e.getCause() instanceof IndexAlreadyExistsException) {
        throw new EsClientException.EsIndexAlreadyExistsException(e);
    }
    throw e;
}
 
Example #7
Source File: EsIndexImpl.java    From io with Apache License 2.0 5 votes vote down vote up
@Override
CreateIndexResponse onParticularError(ElasticsearchException e) {
    if (e instanceof IndexAlreadyExistsException
            || e.getCause() instanceof IndexAlreadyExistsException) {
        throw new EsClientException.EsIndexAlreadyExistsException(e);
    }
    throw e;
}
 
Example #8
Source File: BaseElasticSearchIndexBuilder.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/**
 * creates a new index, does not check if the exist exists
 */
protected void createIndex() {
    try {
        CreateIndexResponse createResponse = client.admin().indices().create(new CreateIndexRequest(indexName)
                .settings(indexSettingsMerged).mapping(indexedDocumentType, mappingMerged)).actionGet();
        if (!createResponse.isAcknowledged()) {
            getLog().error("Index wasn't created for index builder [" + getName() + "], can't rebuild");
        }
    } catch (IndexAlreadyExistsException e) {
        getLog().warn("Index already created for index builder [" + getName() + "]");
    }
}
 
Example #9
Source File: DayRotatedIndexManager.java    From cicada with MIT License 5 votes vote down vote up
private void createIndex(final String type, final String indexName) {
  // 加载配置文件
  final String indexConfig = indexConfigLoader.load(type);

  // 创建索引
  try {
    client.admin().indices().prepareCreate(indexName).setSource(indexConfig).execute().actionGet();
  } catch (IndexAlreadyExistsException ex) {
    log.error("conflict while create index: {}, it's not serious.", indexName);
  }
}
 
Example #10
Source File: TransportIndexAction.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
protected void doExecute(final Task task, final IndexRequest request, final ActionListener<IndexResponse> listener) {
    // if we don't have a master, we don't have metadata, that's fine, let it find a master using create index API
    ClusterState state = clusterService.state();
    if (autoCreateIndex.shouldAutoCreate(request.index(), state)) {
        CreateIndexRequest createIndexRequest = new CreateIndexRequest(request);
        createIndexRequest.index(request.index());
        createIndexRequest.mapping(request.type());
        createIndexRequest.cause("auto(index api)");
        createIndexRequest.masterNodeTimeout(request.timeout());
        createIndexAction.execute(task, createIndexRequest, new ActionListener<CreateIndexResponse>() {
            @Override
            public void onResponse(CreateIndexResponse result) {
                innerExecute(task, request, listener);
            }

            @Override
            public void onFailure(Throwable e) {
                if (ExceptionsHelper.unwrapCause(e) instanceof IndexAlreadyExistsException) {
                    // we have the index, do it
                    try {
                        innerExecute(task, request, listener);
                    } catch (Throwable e1) {
                        listener.onFailure(e1);
                    }
                } else {
                    listener.onFailure(e);
                }
            }
        });
    } else {
        innerExecute(task, request, listener);
    }
}
 
Example #11
Source File: TransportUpdateAction.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
protected void doExecute(final UpdateRequest request, final ActionListener<UpdateResponse> listener) {
    // if we don't have a master, we don't have metadata, that's fine, let it find a master using create index API
    if (autoCreateIndex.shouldAutoCreate(request.index(), clusterService.state())) {
        createIndexAction.execute(new CreateIndexRequest(request).index(request.index()).cause("auto(update api)").masterNodeTimeout(request.timeout()), new ActionListener<CreateIndexResponse>() {
            @Override
            public void onResponse(CreateIndexResponse result) {
                innerExecute(request, listener);
            }

            @Override
            public void onFailure(Throwable e) {
                if (ExceptionsHelper.unwrapCause(e) instanceof IndexAlreadyExistsException) {
                    // we have the index, do it
                    try {
                        innerExecute(request, listener);
                    } catch (Throwable e1) {
                        listener.onFailure(e1);
                    }
                } else {
                    listener.onFailure(e);
                }
            }
        });
    } else {
        innerExecute(request, listener);
    }
}
 
Example #12
Source File: TransportCreateIndexAction.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
protected void masterOperation(final CreateIndexRequest request, final ClusterState state, final ActionListener<CreateIndexResponse> listener) {
    String cause = request.cause();
    if (cause.length() == 0) {
        cause = "api";
    }

    final String indexName = indexNameExpressionResolver.resolveDateMathExpression(request.index());
    final CreateIndexClusterStateUpdateRequest updateRequest = new CreateIndexClusterStateUpdateRequest(request, cause, indexName, request.updateAllTypes())
            .ackTimeout(request.timeout()).masterNodeTimeout(request.masterNodeTimeout())
            .settings(request.settings()).mappings(request.mappings())
            .aliases(request.aliases()).customs(request.customs());

    createIndexService.createIndex(updateRequest, new ActionListener<ClusterStateUpdateResponse>() {

        @Override
        public void onResponse(ClusterStateUpdateResponse response) {
            listener.onResponse(new CreateIndexResponse(response.isAcknowledged()));
        }

        @Override
        public void onFailure(Throwable t) {
            if (t instanceof IndexAlreadyExistsException) {
                logger.trace("[{}] failed to create", t, request.index());
            } else {
                logger.debug("[{}] failed to create", t, request.index());
            }
            listener.onFailure(t);
        }
    });
}
 
Example #13
Source File: MetaDataCreateIndexService.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
public void validateIndexName(String index, ClusterState state) {
    if (state.routingTable().hasIndex(index)) {
        throw new IndexAlreadyExistsException(new Index(index));
    }
    if (state.metaData().hasIndex(index)) {
        throw new IndexAlreadyExistsException(new Index(index));
    }
    if (!Strings.validFileName(index)) {
        throw new InvalidIndexNameException(new Index(index), index, "must not contain the following characters " + Strings.INVALID_FILENAME_CHARS);
    }
    if (index.contains("#")) {
        throw new InvalidIndexNameException(new Index(index), index, "must not contain '#'");
    }
    if (index.charAt(0) == '_') {
        throw new InvalidIndexNameException(new Index(index), index, "must not start with '_'");
    }
    if (!index.toLowerCase(Locale.ROOT).equals(index)) {
        throw new InvalidIndexNameException(new Index(index), index, "must be lowercase");
    }
    int byteCount = 0;
    try {
        byteCount = index.getBytes("UTF-8").length;
    } catch (UnsupportedEncodingException e) {
        // UTF-8 should always be supported, but rethrow this if it is not for some reason
        throw new ElasticsearchException("Unable to determine length of index name", e);
    }
    if (byteCount > MAX_INDEX_NAME_BYTES) {
        throw new InvalidIndexNameException(new Index(index), index,
                "index name is too long, (" + byteCount +
                " > " + MAX_INDEX_NAME_BYTES + ")");
    }
    if (state.metaData().hasAlias(index)) {
        throw new InvalidIndexNameException(new Index(index), index, "already exists as alias");
    }
    if (index.equals(".") || index.equals("..")) {
        throw new InvalidIndexNameException(new Index(index), index, "must not be '.' or '..'");
    }
}
 
Example #14
Source File: TransportBulkCreateIndicesAction.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
private void validateAndFilterExistingIndices(ClusterState currentState,
                                              List<String> indicesToCreate,
                                              BulkCreateIndicesRequest request) {
    for (String index : request.indices()) {
        try {
            createIndexService.validateIndexName(index, currentState);
            indicesToCreate.add(index);
        } catch (IndexAlreadyExistsException e) {
            // ignore
        }
    }
}
 
Example #15
Source File: ElasticSearchSerializerWithMapping.java    From ingestion with Apache License 2.0 3 votes vote down vote up
/**
 * Creates the index if no exists with the mapping defined by the user
 * 
 * @param client
 *       	  ElasticSearch {@link Client}
 * @param indexName
 *            Index name to use -- as per
 *            {@link #getIndexName(String, long)}
 * @param indexType
 *            Index type to use -- as configured on the sink
 */
private void createIndexWithMapping(Client client, String indexName, String indexType) {
	try {
		client.admin().indices().create(new CreateIndexRequest(indexName).mapping(indexType, jsonMapping)).actionGet();
		indexCache.add(indexName);
	} catch (IndexAlreadyExistsException e) {
		logger.info("The index " + indexName + " already exists");
	}
}
 
Example #16
Source File: EsIndexImpl.java    From io with Apache License 2.0 2 votes vote down vote up
/**
 * リトライ時、引数に指定された例外を特別扱いする場合、trueを返すようにオーバーライドすること.
 * これにより、#onParticularErrorメソッドが呼び出される.
 * 標準実装では, 常に falseを返す.
 * @param e 検査対象の例外
 * @return true: 正常終了として扱う場合, false: 左記以外の場合
 */
@Override
boolean isParticularError(ElasticsearchException e) {
    return e instanceof IndexAlreadyExistsException || e.getCause() instanceof IndexAlreadyExistsException;
}
 
Example #17
Source File: EsIndexImpl.java    From io with Apache License 2.0 2 votes vote down vote up
/**
 * リトライ時、引数に指定された例外を特別扱いする場合、trueを返すようにオーバーライドすること.
 * これにより、#onParticularErrorメソッドが呼び出される.
 * 標準実装では, 常に falseを返す.
 * @param e 検査対象の例外
 * @return true: 正常終了として扱う場合, false: 左記以外の場合
 */
@Override
boolean isParticularError(ElasticsearchException e) {
    return e instanceof IndexAlreadyExistsException || e.getCause() instanceof IndexAlreadyExistsException;
}