Java Code Examples for org.elasticsearch.action.admin.indices.create.CreateIndexResponse
The following examples show how to use
org.elasticsearch.action.admin.indices.create.CreateIndexResponse. These examples are extracted from open source projects.
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 Project: usergrid Source File: SetupDao.java License: Apache License 2.0 | 7 votes |
public void setup() throws IOException, NoSuchFieldException, IllegalAccessException { String key; CreateIndexResponse ciResp; Reflections reflections = new Reflections("org.apache.usergrid.chop.webapp.dao"); Set<Class<? extends Dao>> daoClasses = reflections.getSubTypesOf(Dao.class); IndicesAdminClient client = elasticSearchClient.getClient().admin().indices(); for (Class<? extends Dao> daoClass : daoClasses) { key = daoClass.getDeclaredField("DAO_INDEX_KEY").get(null).toString(); if (!client.exists(new IndicesExistsRequest(key)).actionGet().isExists()) { ciResp = client.create(new CreateIndexRequest(key)).actionGet(); if (ciResp.isAcknowledged()) { LOG.debug("Index for key {} didn't exist, now created", key); } else { LOG.debug("Could not create index for key: {}", key); } } else { LOG.debug("Key {} already exists", key); } } }
Example 2
Source Project: microservices-platform Source File: IndexServiceImpl.java License: Apache License 2.0 | 6 votes |
@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 Project: crate Source File: CreateBlobTablePlan.java License: Apache License 2.0 | 6 votes |
@Override public void executeOrFail(DependencyCarrier dependencies, PlannerContext plannerContext, RowConsumer consumer, Row params, SubQueryResults subQueryResults) throws Exception { RelationName relationName = analyzedBlobTable.relationName(); Settings settings = buildSettings( analyzedBlobTable.createBlobTable(), plannerContext.transactionContext(), plannerContext.functions(), params, subQueryResults, numberOfShards); CreateIndexRequest createIndexRequest = new CreateIndexRequest(fullIndexName(relationName.name()), settings); OneRowActionListener<CreateIndexResponse> listener = new OneRowActionListener<>(consumer, r -> new Row1(1L)); dependencies.createIndexAction().execute(createIndexRequest, listener); }
Example 4
Source Project: streams Source File: TwitterUserstreamElasticsearchIT.java License: Apache License 2.0 | 6 votes |
@BeforeClass public void prepareTest() throws Exception { testConfiguration = new StreamsConfigurator<>(TwitterUserstreamElasticsearchConfiguration.class).detectCustomConfiguration(); testClient = ElasticsearchClientManager.getInstance(testConfiguration.getElasticsearch()).client(); ClusterHealthRequest clusterHealthRequest = Requests.clusterHealthRequest(); ClusterHealthResponse clusterHealthResponse = testClient.admin().cluster().health(clusterHealthRequest).actionGet(); assertNotEquals(clusterHealthResponse.getStatus(), ClusterHealthStatus.RED); IndicesExistsRequest indicesExistsRequest = Requests.indicesExistsRequest(testConfiguration.getElasticsearch().getIndex()); IndicesExistsResponse indicesExistsResponse = testClient.admin().indices().exists(indicesExistsRequest).actionGet(); if(indicesExistsResponse.isExists()) { DeleteIndexRequest deleteIndexRequest = Requests.deleteIndexRequest(testConfiguration.getElasticsearch().getIndex()); DeleteIndexResponse deleteIndexResponse = testClient.admin().indices().delete(deleteIndexRequest).actionGet(); assertTrue(deleteIndexResponse.isAcknowledged()); }; CreateIndexRequest createIndexRequest = Requests.createIndexRequest(testConfiguration.getElasticsearch().getIndex()); CreateIndexResponse createIndexResponse = testClient.admin().indices().create(createIndexRequest).actionGet(); assertTrue(createIndexResponse.isAcknowledged()); }
Example 5
Source Project: Elasticsearch Source File: TransportDeleteAction.java License: Apache License 2.0 | 6 votes |
@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 6
Source Project: uavstack Source File: ESClient.java License: Apache License 2.0 | 6 votes |
public boolean creatIndex(String index, String type, Map<String, String> set, Map<String, Map<String, Object>> mapping) throws IOException { CreateIndexRequestBuilder createIndexRequestBuilder = client.admin().indices().prepareCreate(index); if (type != null && mapping != null) { createIndexRequestBuilder.addMapping(type, createMapping(type, mapping)); } if (set != null) { createIndexRequestBuilder.setSettings(createSetting(set)); } CreateIndexResponse resp = createIndexRequestBuilder.execute().actionGet(); if (resp.isAcknowledged()) { return true; } return false; }
Example 7
Source Project: javabase Source File: CrudDemo.java License: Apache License 2.0 | 6 votes |
/** * http://es.xiaoleilu.com/010_Intro/25_Tutorial_Indexing.html * http://es.xiaoleilu.com/070_Index_Mgmt/05_Create_Delete.html * 索引相关的 */ private static void index() throws IOException, InterruptedException { // cluster(),产生一个允许从集群中执行action或操作的client; IndicesAdminClient indicesAdminClient = client.admin().indices(); //创建索引 if (checkExistsIndex(indicesAdminClient, INDEX_NAME)) { deleteIndex(indicesAdminClient, INDEX_NAME); } // String settings = getIndexSetting(); // CreateIndexResponse createIndexResponse = indicesAdminClient.prepareCreate(INDEX_NAME).setSettings(settings).execute().actionGet(); CreateIndexResponse createIndexResponse = indicesAdminClient.prepareCreate(INDEX_NAME).setSettings().execute().actionGet(); // log.info("创建索引{}:{}", INDEX_NAME, createIndexResponse.getContext()); //索引的相关配置操作 indexConfig(indicesAdminClient, INDEX_NAME); // indexMapping(indicesAdminClient, INDEX_NAME, TYPE_NAME); }
Example 8
Source Project: c2mon Source File: ElasticsearchClientTransport.java License: GNU Lesser General Public License v3.0 | 6 votes |
@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 9
Source Project: c2mon Source File: ElasticsearchClientRest.java License: GNU Lesser General Public License v3.0 | 6 votes |
@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 10
Source Project: vertx-elasticsearch-service Source File: DefaultElasticSearchAdminService.java License: Apache License 2.0 | 6 votes |
@Override public void createIndex(String index, JsonObject source, CreateIndexOptions options, Handler<AsyncResult<Void>> resultHandler) { final CreateIndexRequestBuilder builder = CreateIndexAction.INSTANCE.newRequestBuilder(service.getClient()) .setIndex(index) .setSource(source.encode(), XContentType.JSON); builder.execute(new ActionListener<CreateIndexResponse>() { @Override public void onResponse(CreateIndexResponse createIndexResponse) { resultHandler.handle(Future.succeededFuture()); } @Override public void onFailure(Exception e) { resultHandler.handle(Future.failedFuture(e)); } }); }
Example 11
Source Project: pulsar Source File: ElasticSearchSink.java License: Apache License 2.0 | 6 votes |
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 12
Source Project: openshift-elasticsearch-plugin Source File: PluginClient.java License: Apache License 2.0 | 6 votes |
public CreateIndexResponse copyIndex(final String index, final String target, Settings settings, String... types) throws InterruptedException, ExecutionException, IOException { return execute(new Callable<CreateIndexResponse>() { @Override public CreateIndexResponse call() throws Exception { LOGGER.trace("Copying {} index to {} for types {}", index, target, types); GetIndexResponse response = getIndices(index); CreateIndexRequestBuilder builder = client.admin().indices().prepareCreate(target); if(settings != null) { builder.setSettings(settings); } for (String type : types) { builder.addMapping(type, response.mappings().get(index).get(type).getSourceAsMap()); } return builder.get(); } }); }
Example 13
Source Project: titan1withtp3.1 Source File: ElasticSearchIndex.java License: Apache License 2.0 | 6 votes |
/** * 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 14
Source Project: test-data-generator Source File: AbstractEsTest.java License: Apache License 2.0 | 6 votes |
@Before public void setUp() throws Exception { if (client.admin().indices().prepareExists(getIndexName()).execute().actionGet().isExists()) { DeleteIndexResponse deleteIndexResponse = client.admin().indices().prepareDelete(getIndexName()) .execute().actionGet(); Assert.assertTrue(deleteIndexResponse.isAcknowledged()); } CreateIndexResponse createIndexResponse = client.admin().indices().prepareCreate(getIndexName()) .execute().actionGet(); Assert.assertTrue(createIndexResponse.isAcknowledged()); for (Map.Entry<String, String> esMapping : getEsMappings().entrySet()) { String esMappingSource = IOUtils.toString( AbstractEsTest.class.getClassLoader().getResourceAsStream(esMapping.getValue())); PutMappingResponse putMappingResponse = client.admin().indices().preparePutMapping(getIndexName()) .setType(esMapping.getKey()).setSource(esMappingSource).execute().actionGet(); Assert.assertTrue(putMappingResponse.isAcknowledged()); } }
Example 15
Source Project: io Source File: InternalEsClient.java License: Apache License 2.0 | 6 votes |
/** * インデックスを作成する. * @param index インデックス名 * @param mappings マッピング情報 * @return 非同期応答 */ public ActionFuture<CreateIndexResponse> createIndex(String index, Map<String, JSONObject> mappings) { this.fireEvent(Event.creatingIndex, index); CreateIndexRequestBuilder cirb = new CreateIndexRequestBuilder(esTransportClient.admin().indices(), CreateIndexAction.INSTANCE, index); // cjkアナライザ設定 Settings.Builder indexSettings = Settings.settingsBuilder(); indexSettings.put("analysis.analyzer.default.type", "cjk"); cirb.setSettings(indexSettings); if (mappings != null) { for (Map.Entry<String, JSONObject> ent : mappings.entrySet()) { cirb = cirb.addMapping(ent.getKey(), ent.getValue().toString()); } } return cirb.execute(); }
Example 16
Source Project: streams Source File: PercolateTagProcessor.java License: Apache License 2.0 | 6 votes |
/** * createIndexIfMissing. * @param indexName indexName */ public void createIndexIfMissing(String indexName) { if (!this.manager.client() .admin() .indices() .exists(new IndicesExistsRequest(indexName)) .actionGet() .isExists()) { // It does not exist... So we are going to need to create the index. // we are going to assume that the 'templates' that we have loaded into // elasticsearch are sufficient to ensure the index is being created properly. CreateIndexResponse response = this.manager.client().admin().indices().create(new CreateIndexRequest(indexName)).actionGet(); if (response.isAcknowledged()) { LOGGER.info("Index {} did not exist. The index was automatically created from the stored ElasticSearch Templates.", indexName); } else { LOGGER.error("Index {} did not exist. While attempting to create the index from stored ElasticSearch Templates we were unable to get an acknowledgement.", indexName); LOGGER.error("Error Message: {}", response.toString()); throw new RuntimeException("Unable to create index " + indexName); } } }
Example 17
Source Project: io Source File: InternalEsClient.java License: Apache License 2.0 | 6 votes |
/** * インデックスを作成する. * @param index インデックス名 * @param mappings マッピング情報 * @return 非同期応答 */ public ActionFuture<CreateIndexResponse> createIndex(String index, Map<String, JSONObject> mappings) { this.fireEvent(Event.creatingIndex, index); CreateIndexRequestBuilder cirb = new CreateIndexRequestBuilder(esTransportClient.admin().indices()).setIndex(index); // cjkアナライザ設定 ImmutableSettings.Builder indexSettings = ImmutableSettings.settingsBuilder(); indexSettings.put("analysis.analyzer.default.type", "cjk"); cirb.setSettings(indexSettings); if (mappings != null) { for (Map.Entry<String, JSONObject> ent : mappings.entrySet()) { cirb = cirb.addMapping(ent.getKey(), ent.getValue().toString()); } } return cirb.execute(); }
Example 18
Source Project: SpringBootLearn Source File: ElasticsearchUtil.java License: Apache License 2.0 | 5 votes |
/** * 创建索引 * @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 19
Source Project: fess Source File: FessEsClient.java License: Apache License 2.0 | 5 votes |
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 20
Source Project: anomaly-detection Source File: AnomalyDetectionIndices.java License: Apache License 2.0 | 5 votes |
/** * 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 21
Source Project: anomaly-detection Source File: AnomalyDetectionIndices.java License: Apache License 2.0 | 5 votes |
/** * Create anomaly detector job index. * * @param actionListener action called after create index * @throws IOException IOException from {@link AnomalyDetectionIndices#getAnomalyDetectorJobMappings} */ public void initAnomalyDetectorJobIndex(ActionListener<CreateIndexResponse> actionListener) throws IOException { // TODO: specify replica setting CreateIndexRequest request = new CreateIndexRequest(AnomalyDetectorJob.ANOMALY_DETECTOR_JOB_INDEX) .mapping(AnomalyDetector.TYPE, getAnomalyDetectorJobMappings(), XContentType.JSON); adminClient.indices().create(request, actionListener); }
Example 22
Source Project: anomaly-detection Source File: IndexAnomalyDetectorJobActionHandler.java License: Apache License 2.0 | 5 votes |
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 23
Source Project: anomaly-detection Source File: AnomalyResultHandler.java License: Apache License 2.0 | 5 votes |
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 24
Source Project: anomaly-detection Source File: AnomalyResultHandlerTests.java License: Apache License 2.0 | 5 votes |
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 25
Source Project: anomaly-detection Source File: AnomalyResultHandlerTests.java License: Apache License 2.0 | 5 votes |
@SuppressWarnings("unchecked") private void setUpSavingAnomalyResultIndex(boolean anomalyResultIndexExists) throws IOException { 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.onResponse(new CreateIndexResponse(true, true, AnomalyResult.ANOMALY_RESULT_INDEX) { }); return null; }).when(anomalyDetectionIndices).initAnomalyResultIndexDirectly(any()); when(anomalyDetectionIndices.doesAnomalyResultIndexExist()).thenReturn(anomalyResultIndexExists); }
Example 26
Source Project: summerframework Source File: ElasticsearchTemplate.java License: Apache License 2.0 | 5 votes |
public boolean createIndex(String index) { if (isExistedIndex(index)) { return false; } CreateIndexResponse indexResponse = esClient.admin().indices().prepareCreate(index).get(); return indexResponse.isAcknowledged(); }
Example 27
Source Project: summerframework Source File: ElasticsearchTemplate.java License: Apache License 2.0 | 5 votes |
public boolean createIndex(String index) { if (isExistedIndex(index)) { return false; } CreateIndexResponse indexResponse = esClient.admin().indices().prepareCreate(index).get(); return indexResponse.isAcknowledged(); }
Example 28
Source Project: foxtrot Source File: InitializerCommand.java License: Apache License 2.0 | 5 votes |
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 29
Source Project: elasticsearch-cluster-runner Source File: ElasticsearchClusterRunner.java License: Apache License 2.0 | 5 votes |
public CreateIndexResponse createIndex(final String index, final BuilderCallback<CreateIndexRequestBuilder> builder) { final CreateIndexResponse actionGet = builder.apply(client().admin().indices().prepareCreate(index)).execute().actionGet(); if (!actionGet.isAcknowledged()) { onFailure("Failed to create " + index + ".", actionGet); } return actionGet; }
Example 30
Source Project: common-project Source File: ESOpt.java License: Apache License 2.0 | 5 votes |
/** * 创建索引+映射 * @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; }