private void addIndex(String indexName) { try { elasticSearchClient.admin() .indices() .prepareGetIndex() .addIndices(indexName) .execute() .actionGet(); } catch (IndexNotFoundException infe) { try { elasticSearchClient.admin() .indices() .prepareCreate(indexName) .execute() .actionGet(); } catch (ResourceAlreadyExistsException done) { // no-op } } }
semaphore.acquire(); logger.trace("dropRecreateMapping index[{}] - type[{}]", index, type); client.admin().indices().prepareRefresh(index).get(); ImmutableOpenMap<String, MappingMetaData> mappings = client.admin().cluster().prepareState().get().getState().getMetaData() .index(index).mappings(); logger.trace("mappings contains type {}: {}", type, mappings.containsKey(type)); if (client.admin().indices().prepareDeleteMapping(index).setType(type).get().isAcknowledged()) { PutMappingResponse pmr = client.admin().indices().preparePutMapping(index).setType(type) .setSource(mapping.getSourceAsMap()).get(); if (!pmr.isAcknowledged()) {
public static long getIndexCount(Client client, MongoDBRiverDefinition definition) { if (client.admin().indices().prepareExists(definition.getIndexName()).get().isExists()) { if (definition.isImportAllCollections()) { return client.prepareCount(definition.getIndexName()).execute().actionGet().getCount(); } else { if (client.admin().indices().prepareTypesExists(definition.getIndexName()).setTypes(definition.getTypeName()).get() .isExists()) { return client.prepareCount(definition.getIndexName()).setTypes(definition.getTypeName()).get().getCount(); } } } return 0; }
client.admin().indices() .exists(Requests.indicesExistsRequest(indexKey)).actionGet() .isExists(); if (exists && newdb) { client.admin().indices().prepareDelete(indexKey).execute().actionGet(); client.admin().indices().create( new CreateIndexRequest(indexKey) .settings( .put("index.number_of_replicas", numberOfReplicas) .put("index.mapping._id.indexed", true) )).actionGet(); client.admin().cluster().health(new ClusterHealthRequest().waitForGreenStatus()).actionGet();
@Override public void clearStorage() throws BackendException { try { try { client.admin().indices() .delete(new DeleteIndexRequest(indexName)).actionGet(); // We wait for one second to let ES delete the river Thread.sleep(1000); } catch (IndexMissingException e) { // Index does not exist... Fine } } catch (Exception e) { throw new PermanentBackendException("Could not delete index " + indexName, e); } finally { close(); } }
public Observable<IndexRefreshCommandInfo> refreshAsync() { refreshIndexMeter.mark(); final long start = System.currentTimeMillis(); String[] indexes = getIndexes(); if (indexes.length == 0) { if (logger.isTraceEnabled()) { logger.trace("Not refreshing indexes. none found"); } } //Added For Graphite Metrics RefreshResponse response = esProvider.getClient().admin().indices().prepareRefresh(indexes).execute().actionGet(); int failedShards = response.getFailedShards(); int successfulShards = response.getSuccessfulShards(); ShardOperationFailedException[] sfes = response.getShardFailures(); if (sfes != null) { for (ShardOperationFailedException sfe : sfes) { logger.error("Failed to refresh index:{} reason:{}", sfe.index(), sfe.reason()); } } if (logger.isTraceEnabled()) { logger.trace("Refreshed indexes: {},success:{} failed:{} ", StringUtils.join(indexes, ", "), successfulShards, failedShards); } IndexRefreshCommandInfo refreshResults = new IndexRefreshCommandInfo(failedShards == 0, System.currentTimeMillis() - start); return ObservableTimer.time(Observable.just(refreshResults), refreshTimer); }
/** Prepares Elastic index, by adding rows. */ private static void prepareElasticIndex() { CreateIndexRequest indexRequest = new CreateIndexRequest(ELASTIC_INDEX_NAME); node.client().admin().indices().create(indexRequest).actionGet(); for (int i = 0; i < TEST_DATA_ROW_COUNT; i++) { node.client() .prepareIndex(ELASTIC_INDEX_NAME, ELASTIC_TYPE_NAME, String.valueOf(i)) .setSource(createElasticRow(ELASTIC_TYPE_ID_PREFIX + i, "Faraday" + i)) .execute() .actionGet(); } node.client().admin().indices().prepareRefresh(ELASTIC_INDEX_NAME).get(); } /**
public synchronized void deleteIndex() { DeleteIndexResponse response = client.admin().indices().delete(new DeleteIndexRequest(index)).actionGet(); if (!response.isAcknowledged()) { throw new RuntimeException("cannot delete index " + index); } client.admin().cluster().prepareHealth().setWaitForYellowStatus().execute().actionGet(); }
IndicesExistsResponse response = client.admin().indices() .exists(new IndicesExistsRequest(indexName)).actionGet(); client.admin().indices().prepareDelete(this.indexName).execute() .actionGet(); forceCreate = true; CreateIndexResponse create = client.admin().indices() .prepareCreate(indexName).execute().actionGet(); try { Thread.sleep(200); .settingsBuilder(); indexSettings.put("refresh_interval", -1); this.client.admin().indices().prepareUpdateSettings(this.indexName) .setSettings(indexSettings).execute().actionGet(); this.bulkRequest = this.client.prepareBulk();
tc.admin().indices().create(new CreateIndexRequest("copysf")).actionGet(); tc.index(new IndexRequest("vulcangov").type("kolinahr").setRefreshPolicy(RefreshPolicy.IMMEDIATE).source("{\"content\":1}", XContentType.JSON)).actionGet(); tc.index(new IndexRequest("starfleet").type("ships").setRefreshPolicy(RefreshPolicy.IMMEDIATE).source("{\"content\":1}", XContentType.JSON)).actionGet(); tc.index(new IndexRequest("starfleet_academy").type("students").setRefreshPolicy(RefreshPolicy.IMMEDIATE).source("{\"content\":1}", XContentType.JSON)).actionGet(); tc.index(new IndexRequest("starfleet_library").type("public").setRefreshPolicy(RefreshPolicy.IMMEDIATE).source("{\"content\":1}", XContentType.JSON)).actionGet(); tc.index(new IndexRequest("role01_role02").type("type01").setRefreshPolicy(RefreshPolicy.IMMEDIATE).source("{\"content\":1}", XContentType.JSON)).actionGet(); tc.admin().indices().aliases(new IndicesAliasesRequest().addAliasAction(AliasActions.add().indices("starfleet","starfleet_academy","starfleet_library").alias("sf"))).actionGet(); tc.admin().indices().aliases(new IndicesAliasesRequest().addAliasAction(AliasActions.add().indices("klingonempire","vulcangov").alias("nonsf"))).actionGet(); tc.admin().indices().aliases(new IndicesAliasesRequest().addAliasAction(AliasActions.add().indices("public").alias("unrestricted"))).actionGet();
private void deleteIndex(String indexName) { client.nativeClient().admin().indices().prepareDelete(indexName).get(); }
private synchronized void createIndex() { CreateIndexResponse response = client.admin().indices().create(new CreateIndexRequest(index)).actionGet(); if (!response.isAcknowledged()) { throw new RuntimeException("cannot create index " + index); } client.admin().cluster().prepareHealth().setWaitForYellowStatus().execute().actionGet(); }
try { String newIndexName = request.param("index"); if (newIndexName.isEmpty()) { channel.sendResponse(new BytesRestResponse(RestStatus.EXPECTATION_FAILED, "parameter index missing")); return; String searchIndexName = request.param("searchIndex"); if (searchIndexName.isEmpty()) { channel.sendResponse(new BytesRestResponse(RestStatus.EXPECTATION_FAILED, "parameter searchIndex missing")); int newShards = request.paramAsInt("newIndexShards", -1); try { if(client.admin().indices().exists(new IndicesExistsRequest(newIndexName)).actionGet().isExists()) { logger.info("target index already exists, skip creation: " + newIndexName); IndexMetaData indexData = client.admin().cluster().state(new ClusterStateRequest()). actionGet().getState().metaData().indices().get(searchIndexName); Settings searchIndexSettings = indexData.settings(); client.admin().indices().refresh(new RefreshRequest(newIndexName)).actionGet(); long oldCount = client.count(new CountRequest(searchIndexName)).actionGet().getCount(); if (oldCount == newCount) { logger.info("deleting " + searchIndexName); client.admin().indices().delete(new DeleteIndexRequest(searchIndexName)).actionGet();
@Override public RestChannelConsumer prepareRequest(final RestRequest request, final NodeClient client) throws IOException { CreateIndexRequest createIndexRequest = new CreateIndexRequest(request.param("index")); if (request.hasContent()) { createIndexRequest.source(request.content(), request.getXContentType()); } if (request.hasParam("update_all_types")) { DEPRECATION_LOGGER.deprecated("[update_all_types] is deprecated since indices may not have more than one type anymore"); } createIndexRequest.updateAllTypes(request.paramAsBoolean("update_all_types", false)); createIndexRequest.timeout(request.paramAsTime("timeout", createIndexRequest.timeout())); createIndexRequest.masterNodeTimeout(request.paramAsTime("master_timeout", createIndexRequest.masterNodeTimeout())); createIndexRequest.waitForActiveShards(ActiveShardCount.parseString(request.param("wait_for_active_shards"))); return channel -> client.admin().indices().create(createIndexRequest, new RestToXContentListener<>(channel)); } }
private void deleteAllIndices() { ImmutableOpenMap<String, IndexMetaData> indices = elasticSearchClient.admin().cluster() .prepareState().get().getState() .getMetaData().getIndices(); indices.forEach(cursor -> { try { elasticSearchClient.admin() .indices() .delete(new DeleteIndexRequest(cursor.value.getIndex().getName())) .get(); } catch (InterruptedException | ExecutionException e) { throw new RuntimeException(e); } }); }
client.admin().indices() .exists(Requests.indicesExistsRequest(indexKey)).actionGet() .isExists(); if (exists && newIndex) { client.admin().indices().prepareDelete(indexKey).get(); client.admin().indices().create( new CreateIndexRequest(indexKey) .settings( .put("index.number_of_shards", numberOfShards) .put("index.number_of_replicas", numberOfReplicas) )).actionGet(); client.admin().cluster().health(new ClusterHealthRequest().waitForGreenStatus()).actionGet();
void initNestedIndexAndPercolation(Client client) throws IOException, ExecutionException, InterruptedException { XContentBuilder mapping = XContentFactory.jsonBuilder(); mapping.startObject().startObject("properties").startObject("companyname").field("type", "string").endObject() .startObject("employee").field("type", "nested").startObject("properties") .startObject("name").field("type", "string").endObject().endObject().endObject().endObject() .endObject(); client.admin().indices().prepareCreate("nestedindex").addMapping("company", mapping).execute().actionGet(); waitForYellowStatus(client); client.prepareIndex("nestedindex", BatchPercolatorService.TYPE_NAME, "Q").setSource(jsonBuilder().startObject() .field("query", QueryBuilders.nestedQuery("employee", QueryBuilders.matchQuery("employee.name", "virginia potts").operator(MatchQueryBuilder.Operator.AND)).scoreMode("avg")).endObject()).get(); client.admin().indices().prepareRefresh().execute().actionGet(); }
CreateIndexResponse indexResponse = SHARED_NODE.client().admin().indices() .prepareCreate(index.getName()) .setSettings(settings) .get(); throw new IllegalStateException("Failed to create index " + index.getName()); SHARED_NODE.client().admin().cluster().prepareHealth(index.getName()).setWaitForStatus(ClusterHealthStatus.YELLOW).get(); PutMappingResponse mappingResponse = SHARED_NODE.client().admin().indices().preparePutMapping(index.getName()) .setType(entry.getKey()) .setSource(entry.getValue().getAttributes())
final WhoAmIResponse whoAmIRes = tc.execute(WhoAmIAction.INSTANCE, new WhoAmIRequest()).actionGet(); System.out.println("Connected as "+whoAmIRes.getDn()); tc.execute(ConfigUpdateAction.INSTANCE, new ConfigUpdateRequest(new String[]{"config","roles","rolesmapping","internalusers","actiongroups"})).actionGet(); final AcknowledgedResponse response = tc.admin().indices().updateSettings((new UpdateSettingsRequest(index).settings(indexSettings))).actionGet(); System.out.println("Reload config on all nodes"); System.out.println("Update number of replicas to "+(updateSettings) +" with result: "+response.isAcknowledged()); .build(); tc.execute(ConfigUpdateAction.INSTANCE, new ConfigUpdateRequest(new String[]{"config","roles","rolesmapping","internalusers","actiongroups"})).actionGet(); final AcknowledgedResponse response = tc.admin().indices().updateSettings((new UpdateSettingsRequest(index).settings(indexSettings))).actionGet(); System.out.println("Reload config on all nodes"); System.out.println("Auto-expand replicas "+(replicaAutoExpand?"enabled":"disabled")); final boolean successful = tc.admin().cluster() .updateSettings(new ClusterUpdateSettingsRequest() .transientSettings(ENABLE_ALL_ALLOCATIONS_SETTINGS) sgIndex = tc.admin().indices().getIndex(new GetIndexRequest().indices(index).addFeatures(Feature.MAPPINGS)).actionGet(); } catch (IndexNotFoundException e1) { success = tc.admin().indices().delete(new DeleteIndexRequest(index)).actionGet().isAcknowledged(); System.out.print("Deleted index '"+index+"'"); } else { final boolean indexCreated = tc.admin().indices().create(new CreateIndexRequest(index) .settings(indexSettings)) .actionGet().isAcknowledged();
@Override public void recreateIndex(String indexName) throws IOException { DeleteIndexRequestBuilder dirBuilder = transportClient.admin().indices().prepareDelete(indexName); try { DeleteIndexResponse diResponse = dirBuilder.execute().actionGet(); } catch (IndexNotFoundException ie) { System.out.println("Index not found... that's ok"); } CreateIndexRequestBuilder cirBuilder = transportClient.admin().indices().prepareCreate(indexName); CreateIndexResponse ciResponse = cirBuilder.execute().actionGet(); Assert.assertTrue(ciResponse.isAcknowledged(), "Create index succeeeded"); }