Java Code Examples for org.elasticsearch.action.admin.indices.create.CreateIndexResponse#isAcknowledged()

The following examples show how to use org.elasticsearch.action.admin.indices.create.CreateIndexResponse#isAcknowledged() . 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: 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 2
Source File: IndexServiceImpl.java    From microservices-platform with Apache License 2.0 6 votes vote down vote up
@Override
public boolean create(IndexDto indexDto) throws IOException {
    CreateIndexRequest request = new CreateIndexRequest(indexDto.getIndexName());
    request.settings(Settings.builder()
            .put("index.number_of_shards", indexDto.getNumberOfShards())
            .put("index.number_of_replicas", indexDto.getNumberOfReplicas())
    );
    if (StrUtil.isNotEmpty(indexDto.getType()) && StrUtil.isNotEmpty(indexDto.getMappingsSource())) {
        //mappings
        request.mapping(indexDto.getType(), indexDto.getMappingsSource(), XContentType.JSON);
    }
    CreateIndexResponse response = elasticsearchRestTemplate.getClient()
            .indices()
            .create(request, RequestOptions.DEFAULT);
    return response.isAcknowledged();
}
 
Example 3
Source File: ElasticsearchClientRest.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) {
  CreateIndexRequest request = new CreateIndexRequest(indexMetadata.getName());

  request.settings(Settings.builder()
      .put("index.number_of_shards", properties.getShardsPerIndex())
      .put("index.number_of_replicas", properties.getReplicasPerShard())
  );

  if (properties.isAutoTemplateMapping()) {
    request.mapping(TYPE, mapping, XContentType.JSON);
  }

  try {
    CreateIndexResponse createIndexResponse = client.indices().create(request, RequestOptions.DEFAULT);
    return createIndexResponse.isAcknowledged();
  } catch (IOException e) {
    log.error("Error creating '{}' index on Elasticsearch.", indexMetadata.getName(), e);
  }

  return false;
}
 
Example 4
Source File: ElasticSearchSink.java    From pulsar with Apache License 2.0 6 votes vote down vote up
private void createIndexIfNeeded() throws IOException {
    GetIndexRequest request = new GetIndexRequest();
    request.indices(elasticSearchConfig.getIndexName());
    boolean exists = getClient().indices().exists(request);

    if (!exists) {
        CreateIndexRequest cireq = new CreateIndexRequest(elasticSearchConfig.getIndexName());

        cireq.settings(Settings.builder()
           .put("index.number_of_shards", elasticSearchConfig.getIndexNumberOfShards())
           .put("index.number_of_replicas", elasticSearchConfig.getIndexNumberOfReplicas()));

        CreateIndexResponse ciresp = getClient().indices().create(cireq);
        if (!ciresp.isAcknowledged() || !ciresp.isShardsAcknowledged()) {
            throw new RuntimeException("Unable to create index.");
        }
    }
}
 
Example 5
Source File: ElasticSearchIndex.java    From titan1withtp3.1 with Apache License 2.0 6 votes vote down vote up
/**
 * If ES already contains this instance's target index, then do nothing.
 * Otherwise, create the index, then wait {@link #CREATE_SLEEP}.
 * <p>
 * The {@code client} field must point to a live, connected client.
 * The {@code indexName} field must be non-null and point to the name
 * of the index to check for existence or create.
 *
 * @param config the config for this ElasticSearchIndex
 * @throws java.lang.IllegalArgumentException if the index could not be created
 */
private void checkForOrCreateIndex(Configuration config) {
    Preconditions.checkState(null != client);

    //Create index if it does not already exist
    IndicesExistsResponse response = client.admin().indices().exists(new IndicesExistsRequest(indexName)).actionGet();
    if (!response.isExists()) {

        ImmutableSettings.Builder settings = ImmutableSettings.settingsBuilder();

        ElasticSearchSetup.applySettingsFromTitanConf(settings, config, ES_CREATE_EXTRAS_NS);

        CreateIndexResponse create = client.admin().indices().prepareCreate(indexName)
                .setSettings(settings.build()).execute().actionGet();
        try {
            final long sleep = config.get(CREATE_SLEEP);
            log.debug("Sleeping {} ms after {} index creation returned from actionGet()", sleep, indexName);
            Thread.sleep(sleep);
        } catch (InterruptedException e) {
            throw new TitanException("Interrupted while waiting for index to settle in", e);
        }
        if (!create.isAcknowledged()) throw new IllegalArgumentException("Could not create index: " + indexName);
    }
}
 
Example 6
Source File: FessEsClient.java    From fess with Apache License 2.0 5 votes vote down vote up
public boolean createIndex(final String index, final String indexName, final String numberOfShards, final String autoExpandReplicas,
        final boolean uploadConfig) {
    final FessConfig fessConfig = ComponentUtil.getFessConfig();

    if (uploadConfig) {
        waitForConfigSyncStatus();
        sendConfigFiles(index);
    }

    final String indexConfigFile = indexConfigPath + "/" + index + ".json";
    try {
        String source = FileUtil.readUTF8(indexConfigFile);
        String dictionaryPath = System.getProperty("fess.dictionary.path", StringUtil.EMPTY);
        if (StringUtil.isNotBlank(dictionaryPath) && !dictionaryPath.endsWith("/")) {
            dictionaryPath = dictionaryPath + "/";
        }
        source = source.replaceAll(Pattern.quote("${fess.dictionary.path}"), dictionaryPath);
        source = source.replaceAll(Pattern.quote("${fess.index.codec}"), fessConfig.getIndexCodec());
        source = source.replaceAll(Pattern.quote("${fess.index.number_of_shards}"), numberOfShards);
        source = source.replaceAll(Pattern.quote("${fess.index.auto_expand_replicas}"), autoExpandReplicas);
        final CreateIndexResponse indexResponse =
                client.admin().indices().prepareCreate(indexName).setSource(source, XContentType.JSON).execute()
                        .actionGet(fessConfig.getIndexIndicesTimeout());
        if (indexResponse.isAcknowledged()) {
            logger.info("Created {} index.", indexName);
            return true;
        } else if (logger.isDebugEnabled()) {
            logger.debug("Failed to create {} index.", indexName);
        }
    } catch (final Exception e) {
        logger.warn("{} is not found.", indexConfigFile, e);
    }

    return false;
}
 
Example 7
Source File: ElasticsearchUtil.java    From SpringBootLearn with Apache License 2.0 5 votes vote down vote up
/**
 * 创建索引
 * @param index
 * @return
 */
public static boolean createIndex(String index) {
    if (!isIndexExist(index)) {
        log.info("Index is not exits!");
    }
    CreateIndexResponse indexresponse = client.admin().indices().prepareCreate(index).execute().actionGet();
    log.info("执行建立成功?" + indexresponse.isAcknowledged());
    return indexresponse.isAcknowledged();
}
 
Example 8
Source File: IndexCreator.java    From Siamese with GNU General Public License v3.0 5 votes vote down vote up
public boolean execute(final Client client) throws ElasticsearchException {
boolean status = false;
try {
	CreateIndexResponse response = client.admin().indices().create(request).get();
	status = response.isAcknowledged();
} catch (InterruptedException | ExecutionException e) {
	e.printStackTrace();
}
return status;
  }
 
Example 9
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 10
Source File: EsIndex.java    From AsuraFramework with Apache License 2.0 5 votes vote down vote up
/**
 * 创建索引
 *
 * @param indexName
 *
 * @return
 */
public boolean createIndex(String indexName) {
    TransportClient client = esClientFactory.getClient();
    CreateIndexResponse response = null;
    // 如果存在返回true
    if (client.admin().indices().prepareExists(esClientFactory.getIndexs(indexName)).get().isExists()) {
        return true;
    } else {
        response = client.admin().indices().prepareCreate(esClientFactory.getIndexs(indexName)).execute().actionGet();
    }
    return response.isAcknowledged();
}
 
Example 11
Source File: ElasticIndexer.java    From Stargraph with MIT License 5 votes vote down vote up
private void createIndex() {
    Settings settings = Settings.builder()
            .put("index.refresh_interval", "-1")
            .put("index.translog.sync_interval", "10s")
            .put("index.translog.durability", "async")
            .put("index.number_of_replicas", "0")
            .build();

    CreateIndexResponse res = esClient.prepareCreate().setSettings(settings).get();

    if (!res.isAcknowledged()) {
        throw new IndexingException("Fail to create index for " + this.kbId);
    }
}
 
Example 12
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 13
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 14
Source File: ElasticSearchComponent.java    From metron with Apache License 2.0 5 votes vote down vote up
public void createIndexWithMapping(String indexName, String mappingType, String mappingSource)
    throws IOException {
  CreateIndexResponse cir = client.admin().indices().prepareCreate(indexName)
      .addMapping(mappingType, mappingSource)
      .get();

  if (!cir.isAcknowledged()) {
    throw new IOException("Create index was not acknowledged");
  }
}
 
Example 15
Source File: AnomalyResultHandler.java    From anomaly-detection with Apache License 2.0 5 votes vote down vote up
private void onCreateAnomalyResultIndexResponse(CreateIndexResponse response, AnomalyResult anomalyResult) {
    if (response.isAcknowledged()) {
        saveDetectorResult(anomalyResult);
    } else {
        throw new AnomalyDetectionException(
            anomalyResult.getDetectorId(),
            "Creating anomaly result index with mappings call not acknowledged."
        );
    }
}
 
Example 16
Source File: IndexAnomalyDetectorJobActionHandler.java    From anomaly-detection with Apache License 2.0 5 votes vote down vote up
private void onCreateMappingsResponse(CreateIndexResponse response) throws IOException {
    if (response.isAcknowledged()) {
        logger.info("Created {} with mappings.", ANOMALY_DETECTORS_INDEX);
        prepareAnomalyDetectorJobIndexing();
    } else {
        logger.warn("Created {} with mappings call not acknowledged.", ANOMALY_DETECTORS_INDEX);
        channel
            .sendResponse(
                new BytesRestResponse(RestStatus.INTERNAL_SERVER_ERROR, response.toXContent(channel.newErrorBuilder(), EMPTY_PARAMS))
            );
    }
}
 
Example 17
Source File: InitializerCommand.java    From foxtrot with Apache License 2.0 5 votes vote down vote up
private void createMetaIndex(final ElasticsearchConnection connection, final String indexName, int replicaCount) {
    try {
        logger.info("'{}' creation started", indexName);
        Settings settings = Settings.builder()
                .put("number_of_shards", 1)
                .put("number_of_replicas", replicaCount)
                .build();
        CreateIndexRequest createIndexRequest = new CreateIndexRequest().index(indexName)
                .settings(settings);
        CreateIndexResponse response = connection.getClient()
                .admin()
                .indices()
                .create(createIndexRequest)
                .actionGet();
        logger.info("'{}' creation acknowledged: {}", indexName, response.isAcknowledged());
        if(!response.isAcknowledged()) {
            logger.error("Index {} could not be created.", indexName);
        }
    } catch (Exception e) {
        if(null != e.getCause()) {
            logger.error("Index {} could not be created: {}", indexName, e.getCause()
                    .getLocalizedMessage());
        } else {
            logger.error("Index {} could not be created: {}", indexName, e.getLocalizedMessage());
        }
    }
}
 
Example 18
Source File: ElasticsearchDataModelTest.java    From elasticsearch-taste with Apache License 2.0 4 votes vote down vote up
@Before
public void setup() throws Exception {
    clusterName = "es-taste-" + System.currentTimeMillis();
    runner = new ElasticsearchClusterRunner();
    runner.onBuild(new ElasticsearchClusterRunner.Builder() {
        @Override
        public void build(final int number, final Builder settingsBuilder) {
            settingsBuilder.put("http.cors.enabled", true);
            settingsBuilder.put("http.cors.allow-origin", "*");
            settingsBuilder.put("index.number_of_shards", 3);
            settingsBuilder.put("index.number_of_replicas", 0);
            settingsBuilder.putArray("discovery.zen.ping.unicast.hosts", "localhost:9301-9310");
            settingsBuilder.put("plugin.types",
                    "org.codelibs.elasticsearch.taste.TastePlugin");
            settingsBuilder.put("index.unassigned.node_left.delayed_timeout", "0");
        }
    }).build(newConfigs().clusterName(clusterName).numOfNode(numOfNode));

    runner.ensureYellow();
    Client client = runner.client();

    // Wait for Yellow status
    client.admin().cluster().prepareHealth().setWaitForYellowStatus()
            .setTimeout(TimeValue.timeValueMinutes(1)).execute()
            .actionGet();

    final CreateIndexResponse response = client.admin().indices()
            .prepareCreate(TEST_INDEX).execute().actionGet();
    if (!response.isAcknowledged()) {
        throw new TasteException("Failed to create index: " + TEST_INDEX);
    }

    final XContentBuilder userBuilder = XContentFactory.jsonBuilder()//
            .startObject()//
            .startObject(TasteConstants.USER_TYPE)//
            .startObject("properties")//

            // @timestamp
            .startObject(TasteConstants.TIMESTAMP_FIELD)//
            .field("type", "date")//
            .field("format", "date_optional_time")//
            .endObject()//

            // user_id
            .startObject(TasteConstants.USER_ID_FIELD)//
            .field("type", "long")//
            .endObject()//

            // id
            .startObject("id")//
            .field("type", "string")//
            .field("index", "not_analyzed")//
            .endObject()//

            .endObject()//
            .endObject()//
            .endObject();

    final PutMappingResponse userResponse = client.admin().indices()
            .preparePutMapping(TEST_INDEX)
            .setType(TasteConstants.USER_TYPE).setSource(userBuilder)
            .execute().actionGet();
    if (!userResponse.isAcknowledged()) {
        throw new TasteException("Failed to create user mapping.");
    }

    final XContentBuilder itemBuilder = XContentFactory.jsonBuilder()//
            .startObject()//
            .startObject(TasteConstants.ITEM_TYPE)//
            .startObject("properties")//

            // @timestamp
            .startObject(TasteConstants.TIMESTAMP_FIELD)//
            .field("type", "date")//
            .field("format", "date_optional_time")//
            .endObject()//

            // item_id
            .startObject(TasteConstants.ITEM_ID_FIELD)//
            .field("type", "long")//
            .endObject()//

            // id
            .startObject("id")//
            .field("type", "string")//
            .field("index", "not_analyzed")//
            .endObject()//

            .endObject()//
            .endObject()//
            .endObject();

    final PutMappingResponse itemResponse = client.admin().indices()
            .preparePutMapping(TEST_INDEX)
            .setType(TasteConstants.ITEM_TYPE).setSource(itemBuilder)
            .execute().actionGet();
    if (!itemResponse.isAcknowledged()) {
        throw new TasteException("Failed to create item mapping.");
    }
}
 
Example 19
Source File: ElasticsearchMailDestination.java    From elasticsearch-imap with Apache License 2.0 4 votes vote down vote up
private synchronized void createIndexIfNotExists() throws IOException {
    if (isError()) {
        if (logger.isTraceEnabled()) {
            logger.trace("error, not creating index");
        }
        return;
    }

    if(initialized) {
        return;
    }
    
    
    IMAPImporter.waitForYellowCluster(client);
    
    // create index if it doesn't already exist
    if (!client.admin().indices().prepareExists(index).execute().actionGet().isExists()) {

        final CreateIndexRequestBuilder createIndexRequestBuilder = client.admin().indices().prepareCreate(index);
        if (settings != null) {
            logger.debug("index settings are provided, will apply them {}", settings);
            createIndexRequestBuilder.setSettings(settings);
        } else {
            logger.debug("no settings given for index '{}'",index);
        }
        
        
        if (mapping != null) {
            logger.warn("mapping for type '{}' is provided, will apply {}", type, mapping);
            createIndexRequestBuilder.addMapping(type, mapping);
        } else {
            logger.debug("no mapping given for type '{}', will apply default mapping",type);
            createIndexRequestBuilder.addMapping(type, getDefaultTypeMapping());
        }
        
        final CreateIndexResponse res = createIndexRequestBuilder.get();
        
        if (!res.isAcknowledged()) {
            throw new IOException("Could not create index " + index);
        }
        
        IMAPImporter.waitForYellowCluster(client);
        
        logger.info("Index {} created", index);
        
    } else {
        logger.debug("Index {} already exists", index);
    }
    
    initialized = true;
}
 
Example 20
Source File: EsHighLevelRestTest1.java    From java-study with Apache License 2.0 4 votes vote down vote up
/**
 * 创建索引
 * 
 * @throws IOException
 */
private static void createIndex() throws IOException {

	// 类型
	String type = "_doc";
	String index = "test1";
	// setting 的值
	Map<String, Object> setmapping = new HashMap<>();
	// 分区数、副本数、缓存刷新时间
	setmapping.put("number_of_shards", 10);
	setmapping.put("number_of_replicas", 1);
	setmapping.put("refresh_interval", "5s");
	Map<String, Object> keyword = new HashMap<>();
	//设置类型
	keyword.put("type", "keyword");
	Map<String, Object> lon = new HashMap<>();
	//设置类型
	lon.put("type", "long");
	Map<String, Object> date = new HashMap<>();
	//设置类型
	date.put("type", "date");
	date.put("format", "yyyy-MM-dd HH:mm:ss");

	Map<String, Object> jsonMap2 = new HashMap<>();
	Map<String, Object> properties = new HashMap<>();
	//设置字段message信息
	properties.put("uid", lon);
	properties.put("phone", lon);
	properties.put("msgcode", lon);
	properties.put("message", keyword);
	properties.put("sendtime", date);
	Map<String, Object> mapping = new HashMap<>();
	mapping.put("properties", properties);
	jsonMap2.put(type, mapping);

	GetIndexRequest getRequest = new GetIndexRequest();
	getRequest.indices(index);
	getRequest.types(type);
	getRequest.local(false);
	getRequest.humanReadable(true);
	boolean exists2 = client.indices().exists(getRequest, RequestOptions.DEFAULT);
	//如果存在就不创建了
	if(exists2) {
		System.out.println(index+"索引库已经存在!");
		return;
	}
	// 开始创建库
	CreateIndexRequest request = new CreateIndexRequest(index);
	try {
		// 加载数据类型
		request.settings(setmapping);
		//设置mapping参数
		request.mapping(type, jsonMap2);
		//设置别名
		request.alias(new Alias("pancm_alias"));
		CreateIndexResponse createIndexResponse = client.indices().create(request, RequestOptions.DEFAULT);
		boolean falg = createIndexResponse.isAcknowledged();
		if(falg){
			System.out.println("创建索引库:"+index+"成功!" );
		}
	} catch (IOException e) {
		e.printStackTrace();
	}

}