org.elasticsearch.ResourceAlreadyExistsException Java Examples

The following examples show how to use org.elasticsearch.ResourceAlreadyExistsException. 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: ElasticSearchDAOV5.java    From conductor with Apache License 2.0 6 votes vote down vote up
private void addIndex(String indexName) {
    try {
        elasticSearchClient.admin()
                .indices()
                .prepareGetIndex()
                .addIndices(indexName)
                .execute()
                .actionGet();
    } catch (IndexNotFoundException infe) {
        try {

            CreateIndexRequest createIndexRequest = new CreateIndexRequest(indexName);
            createIndexRequest.settings(Settings.builder()
                    .put("index.number_of_shards", config.getElasticSearchIndexShardCount())
                    .put("index.number_of_replicas", config.getElasticSearchIndexReplicationCount())
            );

            elasticSearchClient.admin()
                    .indices()
                    .create(createIndexRequest)
                    .actionGet();
        } catch (ResourceAlreadyExistsException done) {
            // no-op
        }
    }
}
 
Example #2
Source File: ElasticSearchDAOV5.java    From conductor with Apache License 2.0 6 votes vote down vote up
private void updateLogIndexName() {
    this.logIndexName = this.logIndexPrefix + "_" + SIMPLE_DATE_FORMAT.format(new Date());

    try {
        elasticSearchClient.admin()
            .indices()
            .prepareGetIndex()
            .addIndices(logIndexName)
            .execute()
            .actionGet();
    } catch (IndexNotFoundException infe) {
        try {
            elasticSearchClient.admin()
                .indices()
                .prepareCreate(logIndexName)
                .execute()
                .actionGet();
        } catch (ResourceAlreadyExistsException ilee) {
            // no-op
        } catch (Exception e) {
            logger.error("Failed to update log index name: {}", logIndexName, e);
        }
    }
}
 
Example #3
Source File: ElasticSearchDAOV6.java    From conductor with Apache License 2.0 6 votes vote down vote up
private void createIndex(String indexName) {
    try {
        elasticSearchClient.admin().indices().prepareGetIndex().addIndices(indexName).execute().actionGet();
    } catch (IndexNotFoundException infe) {
        try {
            CreateIndexRequest createIndexRequest = new CreateIndexRequest(indexName);
            createIndexRequest.settings(Settings.builder()
                    .put("index.number_of_shards", config.getElasticSearchIndexShardCount())
                    .put("index.number_of_replicas", config.getElasticSearchIndexReplicationCount())
            );

            elasticSearchClient.admin()
                    .indices()
                    .create(createIndexRequest)
                    .actionGet();
        } catch (ResourceAlreadyExistsException done) {
            LOGGER.error("Failed to update log index name: {}", indexName, done);
        }
    }
}
 
Example #4
Source File: ElasticsearchClientTransport.java    From c2mon with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public boolean createIndex(IndexMetadata indexMetadata, String mapping) {
  CreateIndexRequestBuilder builder = client.admin().indices().prepareCreate(indexMetadata.getName());
  builder.setSettings(Settings.builder()
      .put("number_of_shards", properties.getShardsPerIndex())
      .put("number_of_replicas", properties.getReplicasPerShard())
      .build());

  if (mapping != null) {
    builder.addMapping(TYPE, mapping, XContentType.JSON);
  }

  log.debug("Creating new index with name {}", indexMetadata.getName());

  try {
    CreateIndexResponse response = builder.get();
    return response.isAcknowledged();
  } catch (ResourceAlreadyExistsException e) {
    log.debug("Index already exists.", e);
  }

  return false;
}
 
Example #5
Source File: ClientFacadeTest.java    From molgenis with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
void testCreateIndexAlreadyExists() {
  Index index = Index.create("indexname");
  IndexSettings indexSettings = IndexSettings.create(1, 1);
  FieldMapping idField = FieldMapping.create("id", MappingType.TEXT, emptyList());
  Mapping mapping = Mapping.create("type", ImmutableList.of(idField));
  Stream<Mapping> mappings = Stream.of(mapping);

  when(indicesAdminClient.prepareCreate(any())).thenReturn(createIndexRequestBuilder);
  when(createIndexRequestBuilder.setSettings(any(Settings.class)))
      .thenReturn(createIndexRequestBuilder);
  when(createIndexRequestBuilder.addMapping(any(), any(XContentBuilder.class)))
      .thenReturn(createIndexRequestBuilder);

  when(createIndexRequestBuilder.get())
      .thenThrow(new ResourceAlreadyExistsException("Index already exists"));

  assertThrows(
      IndexAlreadyExistsException.class,
      () -> clientFacade.createIndex(index, indexSettings, mappings));
}
 
Example #6
Source File: MetaDataCreateIndexService.java    From crate with Apache License 2.0 6 votes vote down vote up
/**
 * Validate the name for an index against some static rules and a cluster state.
 */
public static void validateIndexName(String index, ClusterState state) {
    validateIndexOrAliasName(index, InvalidIndexNameException::new);
    if (!index.toLowerCase(Locale.ROOT).equals(index)) {
        throw new InvalidIndexNameException(index, "must be lowercase");
    }
    if (state.routingTable().hasIndex(index)) {
        throw new ResourceAlreadyExistsException(state.routingTable().index(index).getIndex());
    }
    if (state.metaData().hasIndex(index)) {
        throw new ResourceAlreadyExistsException(state.metaData().index(index).getIndex());
    }
    if (state.metaData().hasAlias(index)) {
        throw new InvalidIndexNameException(index, "already exists as alias");
    }
}
 
Example #7
Source File: AnomalyResultHandlerTests.java    From anomaly-detection with Apache License 2.0 5 votes vote down vote up
private void setInitAnomalyResultIndexException(boolean indexExistException) throws IOException {
    Exception e = indexExistException ? mock(ResourceAlreadyExistsException.class) : mock(RuntimeException.class);
    doAnswer(invocation -> {
        Object[] args = invocation.getArguments();
        assertTrue(String.format("The size of args is %d.  Its content is %s", args.length, Arrays.toString(args)), args.length >= 1);
        ActionListener<CreateIndexResponse> listener = invocation.getArgument(0);
        assertTrue(listener != null);
        listener.onFailure(e);
        return null;
    }).when(anomalyDetectionIndices).initAnomalyResultIndexDirectly(any());
}
 
Example #8
Source File: SQLExceptions.java    From crate with Apache License 2.0 5 votes vote down vote up
private static Throwable esToCrateException(Throwable unwrappedError) {
    if (unwrappedError instanceof IllegalArgumentException || unwrappedError instanceof ParsingException) {
        return new SQLParseException(unwrappedError.getMessage(), (Exception) unwrappedError);
    } else if (unwrappedError instanceof UnsupportedOperationException) {
        return new UnsupportedFeatureException(unwrappedError.getMessage(), (Exception) unwrappedError);
    } else if (isDocumentAlreadyExistsException(unwrappedError)) {
        return new DuplicateKeyException(
            ((EngineException) unwrappedError).getIndex().getName(),
            "A document with the same primary key exists already", unwrappedError);
    } else if (unwrappedError instanceof ResourceAlreadyExistsException) {
        return new RelationAlreadyExists(((ResourceAlreadyExistsException) unwrappedError).getIndex().getName(), unwrappedError);
    } else if ((unwrappedError instanceof InvalidIndexNameException)) {
        if (unwrappedError.getMessage().contains("already exists as alias")) {
            // treat an alias like a table as aliases are not officially supported
            return new RelationAlreadyExists(((InvalidIndexNameException) unwrappedError).getIndex().getName(),
                unwrappedError);
        }
        return new InvalidRelationName(((InvalidIndexNameException) unwrappedError).getIndex().getName(), unwrappedError);
    } else if (unwrappedError instanceof InvalidIndexTemplateException) {
        PartitionName partitionName = PartitionName.fromIndexOrTemplate(((InvalidIndexTemplateException) unwrappedError).name());
        return new InvalidRelationName(partitionName.relationName().fqn(), unwrappedError);
    } else if (unwrappedError instanceof IndexNotFoundException) {
        return new RelationUnknown(((IndexNotFoundException) unwrappedError).getIndex().getName(), unwrappedError);
    } else if (unwrappedError instanceof org.elasticsearch.common.breaker.CircuitBreakingException) {
        return new CircuitBreakingException(unwrappedError.getMessage());
    } else if (unwrappedError instanceof InterruptedException) {
        return JobKilledException.of(unwrappedError.getMessage());
    } else if (unwrappedError instanceof RepositoryMissingException) {
        return new RepositoryUnknownException(((RepositoryMissingException) unwrappedError).repository());
    } else if (unwrappedError instanceof InvalidSnapshotNameException) {
        return new SnapshotNameInvalidException(unwrappedError.getMessage());
    } else if (unwrappedError instanceof SnapshotMissingException) {
        SnapshotMissingException snapshotException = (SnapshotMissingException) unwrappedError;
        return new SnapshotUnknownException(snapshotException.getRepositoryName(), snapshotException.getSnapshotName(), unwrappedError);
    } else if (unwrappedError instanceof SnapshotCreationException) {
        SnapshotCreationException creationException = (SnapshotCreationException) unwrappedError;
        return new SnapshotAlreadyExistsException(creationException.getRepositoryName(), creationException.getSnapshotName());
    }
    return unwrappedError;
}
 
Example #9
Source File: TransportCreatePartitionsAction.java    From crate with Apache License 2.0 5 votes vote down vote up
private void validateAndFilterExistingIndices(ClusterState currentState,
                                              List<String> indicesToCreate,
                                              CreatePartitionsRequest request) {
    for (String index : request.indices()) {
        try {
            MetaDataCreateIndexService.validateIndexName(index, currentState);
            indicesToCreate.add(index);
        } catch (ResourceAlreadyExistsException e) {
            // ignore
        }
    }
}
 
Example #10
Source File: MetaDataCreateIndexService.java    From crate with Apache License 2.0 5 votes vote down vote up
static IndexMetaData validateResize(ClusterState state, String sourceIndex,
                                       Set<String> targetIndexMappingsTypes, String targetIndexName,
                                       Settings targetIndexSettings) {
    if (state.metaData().hasIndex(targetIndexName)) {
        throw new ResourceAlreadyExistsException(state.metaData().index(targetIndexName).getIndex());
    }
    final IndexMetaData sourceMetaData = state.metaData().index(sourceIndex);
    if (sourceMetaData == null) {
        throw new IndexNotFoundException(sourceIndex);
    }
    // ensure index is read-only
    if (state.blocks().indexBlocked(ClusterBlockLevel.WRITE, sourceIndex) == false) {
        throw new IllegalStateException("index " + sourceIndex + " must be read-only to resize index. use \"index.blocks.write=true\"");
    }

    if ((targetIndexMappingsTypes.size() > 1 ||
        (targetIndexMappingsTypes.isEmpty() || targetIndexMappingsTypes.contains(MapperService.DEFAULT_MAPPING)) == false)) {
        throw new IllegalArgumentException("mappings are not allowed when resizing indices" +
            ", all mappings are copied from the source index");
    }

    if (IndexMetaData.INDEX_NUMBER_OF_SHARDS_SETTING.exists(targetIndexSettings)) {
        // this method applies all necessary checks ie. if the target shards are less than the source shards
        // of if the source shards are divisible by the number of target shards
        IndexMetaData.getRoutingFactor(sourceMetaData.getNumberOfShards(),
            IndexMetaData.INDEX_NUMBER_OF_SHARDS_SETTING.get(targetIndexSettings));
    }
    return sourceMetaData;
}
 
Example #11
Source File: MetaDataCreateIndexService.java    From crate with Apache License 2.0 5 votes vote down vote up
@Override
public void onFailure(String source, Exception e) {
    if (e instanceof ResourceAlreadyExistsException) {
        logger.trace(() -> new ParameterizedMessage("[{}] failed to create", request.index()), e);
    } else {
        logger.debug(() -> new ParameterizedMessage("[{}] failed to create", request.index()), e);
    }
    super.onFailure(source, e);
}
 
Example #12
Source File: IndicesService.java    From crate with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new {@link IndexService} for the given metadata.
 *
 * @param indexMetaData          the index metadata to create the index for
 * @param builtInListeners       a list of built-in lifecycle {@link IndexEventListener} that should should be used along side with the
 *                               per-index listeners
 * @throws ResourceAlreadyExistsException if the index already exists.
 */
@Override
public synchronized IndexService createIndex(
        final IndexMetaData indexMetaData, final List<IndexEventListener> builtInListeners) throws IOException {
    ensureChangesAllowed();
    if (indexMetaData.getIndexUUID().equals(IndexMetaData.INDEX_UUID_NA_VALUE)) {
        throw new IllegalArgumentException("index must have a real UUID found value: [" + indexMetaData.getIndexUUID() + "]");
    }
    final Index index = indexMetaData.getIndex();
    if (hasIndex(index)) {
        throw new ResourceAlreadyExistsException(index);
    }
    List<IndexEventListener> finalListeners = new ArrayList<>(builtInListeners);
    final IndexEventListener onStoreClose = new IndexEventListener() {
        @Override
        public void onStoreClosed(ShardId shardId) {
            indicesQueryCache.onClose(shardId);
        }
    };
    finalListeners.add(onStoreClose);
    final IndexService indexService = createIndexService(
        "create index",
        indexMetaData,
        indicesQueryCache,
        finalListeners,
        indexingMemoryController
    );
    boolean success = false;
    try {
        indexService.getIndexEventListener().afterIndexCreated(indexService);
        indices = newMapBuilder(indices).put(index.getUUID(), indexService).immutableMap();
        success = true;
        return indexService;
    } finally {
        if (success == false) {
            indexService.close("plugins_failed", true);
        }
    }
}
 
Example #13
Source File: BaseElasticSearchSink.java    From FlinkExperiments with MIT License 5 votes vote down vote up
private void createIndexAndMapping(Client client) {
    // Create the Index and Mappings before indexing the entities:
    try {
        createIndex(client, getIndexName());
        createMapping(client, getIndexName(), getMapping());
    } catch (ResourceAlreadyExistsException e) {
        // The Index already exists! We shouldn't exit here, because we can
        // (more or less) safely assume, that the index has already been
        // created by some of the other worker processes.
        System.err.println(e.getMessage());
    }
}
 
Example #14
Source File: ESOpt.java    From common-project with Apache License 2.0 5 votes vote down vote up
/**
 * 创建索引+映射
 * @param indexName
 * @param type
 * @param c         模型class
 * @return
 * @throws Exception
 */
public static boolean createIndexAndMapping(String indexName, String type, Class c) throws IOException {
    Map<String, String> fieldType = ClassUtil.getClassFieldTypeMapping(c);
    CreateIndexRequestBuilder cib = client.admin().indices().prepareCreate(indexName);
    XContentBuilder mapping = XContentFactory.jsonBuilder()
            .startObject()
            .startObject("properties");
    fieldType.forEach((k, v) -> {
        if (v.equals("int")) {
            v = "integer";
        }
        if (v.equals("double")) {
            v = "float";
        }
        if (v.equals("String")) {
            v = "text";
        }

        //设置之定义字段
        try {
            mapping.startObject(k).field("type", v.toLowerCase()).endObject();
        } catch (IOException e) {
            e.printStackTrace();
        }
    });
    mapping.endObject().endObject();
    cib.addMapping(type, mapping);
    try {
        CreateIndexResponse createIndexResponse = cib.execute().actionGet();
        logger.info("----------添加映射成功----------");
        return createIndexResponse.isAcknowledged();
    } catch (ResourceAlreadyExistsException existsException) {
        logger.error("index name : " + indexName + " already exists");
    }
    return false;
}
 
Example #15
Source File: ESOpt.java    From common-project with Apache License 2.0 5 votes vote down vote up
/**
 * 创建索引
 * @param index
 * @return
 */
public static boolean createIndex(String index) {
    if (!isIndexExist(index)) {
        logger.info("Index is not exits!");
    }
    try {
        CreateIndexResponse indexresponse = client.admin().indices().prepareCreate(index).execute().actionGet();
        logger.info("执行建立成功?" + indexresponse.isAcknowledged());
        return indexresponse.isAcknowledged();
    } catch (ResourceAlreadyExistsException existsException) {
        logger.error("index name : " + index + " already exists");
    }
    return false;
}
 
Example #16
Source File: AnomalyResultHandler.java    From anomaly-detection with Apache License 2.0 5 votes vote down vote up
public void indexAnomalyResult(AnomalyResult anomalyResult) {
    try {
        if (checkIndicesBlocked(clusterService.state(), ClusterBlockLevel.WRITE, AnomalyResult.ANOMALY_RESULT_INDEX)) {
            LOG.warn(CANNOT_SAVE_ERR_MSG);
            return;
        }
        if (!anomalyDetectionIndices.doesAnomalyResultIndexExist()) {
            anomalyDetectionIndices
                .initAnomalyResultIndexDirectly(
                    ActionListener.wrap(initResponse -> onCreateAnomalyResultIndexResponse(initResponse, anomalyResult), exception -> {
                        if (ExceptionsHelper.unwrapCause(exception) instanceof ResourceAlreadyExistsException) {
                            // It is possible the index has been created while we sending the create request
                            saveDetectorResult(anomalyResult);
                        } else {
                            throw new AnomalyDetectionException(
                                anomalyResult.getDetectorId(),
                                "Unexpected error creating anomaly result index",
                                exception
                            );
                        }
                    })
                );
        } else {
            saveDetectorResult(anomalyResult);
        }
    } catch (Exception e) {
        throw new AnomalyDetectionException(
            anomalyResult.getDetectorId(),
            String
                .format(
                    Locale.ROOT,
                    "Error in saving anomaly index for ID %s from %s to %s",
                    anomalyResult.getDetectorId(),
                    anomalyResult.getDataStartTime(),
                    anomalyResult.getDataEndTime()
                ),
            e
        );
    }
}
 
Example #17
Source File: TableCreator.java    From crate with Apache License 2.0 4 votes vote down vote up
private static boolean isTableExistsError(Throwable e, @Nullable String templateName) {
    return e instanceof ResourceAlreadyExistsException
           || (templateName != null && isTemplateAlreadyExistsException(e));
}