Java Code Examples for org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsResponse#isExists()

The following examples show how to use org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsResponse#isExists() . 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: DKSearchOutputImpl.java    From dk-fitting with Apache License 2.0 6 votes vote down vote up
/**
 *
 * 获取ES某个索引下数据的总和
 * @param hostIps
 * @param clusterName
 * @param indexName
 * @param typeName
 * @param port
 * @return
 */
@Override
public long getESSum(String hostIps, String clusterName, String indexName, String typeName, int port) throws Exception {
    client=ESUtils.getClient( hostIps,port,clusterName );
    IndicesExistsResponse existsResponse = client.admin().indices().prepareExists( indexName ).execute().actionGet();
    if (!existsResponse.isExists()){
        System.out.println( "index Non-existent " );
        return -1;
    }
    TypesExistsResponse typesExistsResponse = client.admin().indices().prepareTypesExists( indexName ).setTypes( typeName ).execute().actionGet();
    if (!typesExistsResponse.isExists()){
        System.out.println( "type Non-existent " );
        return -1;
    }
    return client.prepareSearch( indexName ).setTypes( typeName ).get().getHits().totalHits;
}
 
Example 2
Source File: ElasticsearchTestUtils.java    From components with Apache License 2.0 6 votes vote down vote up
/**
 * Deletes an index and block until deletion is complete.
 *
 * @param index The index to delete
 * @param client The client which points to the Elasticsearch instance
 * @throws InterruptedException if blocking thread is interrupted or index existence check failed
 * @throws java.util.concurrent.ExecutionException if index existence check failed
 * @throws IOException if deletion failed
 */
static void deleteIndex(String index, Client client)
        throws InterruptedException, java.util.concurrent.ExecutionException, IOException {
    IndicesAdminClient indices = client.admin().indices();
    IndicesExistsResponse indicesExistsResponse =
            indices.exists(new IndicesExistsRequest(index)).get();
    if (indicesExistsResponse.isExists()) {
        indices.prepareClose(index).get();
        // delete index is an asynchronous request, neither refresh or upgrade
        // delete all docs before starting tests. WaitForYellow() and delete directory are too slow,
        // so block thread until it is done (make it synchronous!!!)
        AtomicBoolean indexDeleted = new AtomicBoolean(false);
        AtomicBoolean waitForIndexDeletion = new AtomicBoolean(true);
        indices.delete(
                Requests.deleteIndexRequest(index),
                new DeleteActionListener(indexDeleted, waitForIndexDeletion));
        while (waitForIndexDeletion.get()) {
            Thread.sleep(100);
        }
        if (!indexDeleted.get()) {
            throw new IOException("Failed to delete index " + index);
        }
    }
}
 
Example 3
Source File: ElasticsearchPersistWriterIT.java    From streams with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public void prepareTestPersistWriter() throws Exception {

  testConfiguration = new ComponentConfigurator<>(ElasticsearchWriterConfiguration.class).detectConfiguration("ElasticsearchPersistWriterIT");
  testClient = ElasticsearchClientManager.getInstance(testConfiguration).client();

  ClusterHealthRequest clusterHealthRequest = Requests.clusterHealthRequest();
  ClusterHealthResponse clusterHealthResponse = testClient.admin().cluster().health(clusterHealthRequest).actionGet();
  assertNotEquals(clusterHealthResponse.getStatus(), ClusterHealthStatus.RED);

  IndicesExistsRequest indicesExistsRequest = Requests.indicesExistsRequest(testConfiguration.getIndex());
  IndicesExistsResponse indicesExistsResponse = testClient.admin().indices().exists(indicesExistsRequest).actionGet();
  if(indicesExistsResponse.isExists()) {
    DeleteIndexRequest deleteIndexRequest = Requests.deleteIndexRequest(testConfiguration.getIndex());
    DeleteIndexResponse deleteIndexResponse = testClient.admin().indices().delete(deleteIndexRequest).actionGet();
    assertTrue(deleteIndexResponse.isAcknowledged());
  }

}
 
Example 4
Source File: TestUtils.java    From foxtrot with Apache License 2.0 6 votes vote down vote up
public static void ensureIndex(ElasticsearchConnection connection, final String table) {
    IndicesExistsRequest indicesExistsRequest = new IndicesExistsRequest().indices(table);
    IndicesExistsResponse indicesExistsResponse = connection.getClient()
            .admin()
            .indices()
            .exists(indicesExistsRequest)
            .actionGet();

    if(!indicesExistsResponse.isExists()) {
        Settings indexSettings = Settings.builder()
                .put("number_of_replicas", 0)
                .build();
        CreateIndexRequest createRequest = new CreateIndexRequest(table).settings(indexSettings);
        connection.getClient()
                .admin()
                .indices()
                .create(createRequest)
                .actionGet();
    }
}
 
Example 5
Source File: ElasticIndexer.java    From Stargraph with MIT License 6 votes vote down vote up
@Override
protected void beforeLoad(boolean reset) {
    try {
        IndicesExistsResponse res = esClient.prepareExists().get();

        if (!res.isExists()) {
            createIndex();
        } else {
            if (reset) {
               deleteAll();
            }
        }
    } catch (Exception e) {
        throw new IndexingException(e);
    }
}
 
Example 6
Source File: HdfsElasticsearchIT.java    From streams with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public void prepareTest() throws Exception {

  testConfiguration = new StreamsConfigurator<>(HdfsElasticsearchConfiguration.class).detectCustomConfiguration("HdfsElasticsearchIT");
  testClient = ElasticsearchClientManager.getInstance(testConfiguration.getDestination()).client();

  ClusterHealthRequest clusterHealthRequest = Requests.clusterHealthRequest();
  ClusterHealthResponse clusterHealthResponse = testClient.admin().cluster().health(clusterHealthRequest).actionGet();
  assertNotEquals(clusterHealthResponse.getStatus(), ClusterHealthStatus.RED);

  IndicesExistsRequest indicesExistsRequest = Requests.indicesExistsRequest(testConfiguration.getDestination().getIndex());
  IndicesExistsResponse indicesExistsResponse = testClient.admin().indices().exists(indicesExistsRequest).actionGet();
  if(indicesExistsResponse.isExists()) {
    DeleteIndexRequest deleteIndexRequest = Requests.deleteIndexRequest(testConfiguration.getDestination().getIndex());
    DeleteIndexResponse deleteIndexResponse = testClient.admin().indices().delete(deleteIndexRequest).actionGet();
    assertTrue(deleteIndexResponse.isAcknowledged());
  };
}
 
Example 7
Source File: ESClient.java    From uavstack with Apache License 2.0 5 votes vote down vote up
/**
 * existIndex
 * 
 * @param index
 * @return
 */
public boolean existIndex(String index) {

    IndicesExistsRequest request = new IndicesExistsRequest(index);
    IndicesExistsResponse response = client.admin().indices().exists(request).actionGet();
    if (response.isExists()) {
        return true;
    }
    return false;
}
 
Example 8
Source File: UserRequestHandler.java    From elasticsearch-taste with Apache License 2.0 5 votes vote down vote up
private void doUserIndexExists(final Params params,
        final RequestHandler.OnErrorListener listener,
        final Map<String, Object> requestMap,
        final Map<String, Object> paramMap, final RequestHandlerChain chain) {
    final String index = params.param(
            TasteConstants.REQUEST_PARAM_USER_INDEX, params.param("index"));

    try {
        indexCreationLock.lock();
        final IndicesExistsResponse indicesExistsResponse = client.admin()
                .indices().prepareExists(index).execute().actionGet();
        if (indicesExistsResponse.isExists()) {
            doUserMappingCreation(params, listener, requestMap, paramMap,
                    chain);
        } else {
            doUserIndexCreation(params, listener, requestMap, paramMap,
                    chain, index);
        }
    } catch (final Exception e) {
        final List<Throwable> errorList = getErrorList(paramMap);
        if (errorList.size() >= maxRetryCount) {
            listener.onError(e);
        } else {
            sleep(e);
            errorList.add(e);
            fork(() -> execute(params, listener, requestMap, paramMap,
                    chain));
        }
    } finally {
        indexCreationLock.unlock();
    }
}
 
Example 9
Source File: BaseElasticSearchIndexBuilder.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/**
 * removes any existing index and creates a new one
 */
protected void recreateIndex() {
    IndicesExistsResponse response = client.admin().indices().exists(new IndicesExistsRequest(indexName)).actionGet();
    if (response.isExists()) {
        client.admin().indices().delete(new DeleteIndexRequest(indexName)).actionGet();
    }

    // create index
    createIndex();
}
 
Example 10
Source File: ItemRequestHandler.java    From elasticsearch-taste with Apache License 2.0 5 votes vote down vote up
private void doItemIndexExists(final Params params,
        final RequestHandler.OnErrorListener listener,
        final Map<String, Object> requestMap,
        final Map<String, Object> paramMap, final RequestHandlerChain chain) {
    final String index = params.param(
            TasteConstants.REQUEST_PARAM_ITEM_INDEX, params.param("index"));

    try {
        indexCreationLock.lock();
        final IndicesExistsResponse indicesExistsResponse = client.admin()
                .indices().prepareExists(index).execute().actionGet();
        if (indicesExistsResponse.isExists()) {
            doItemMappingCreation(params, listener, requestMap, paramMap,
                    chain);
        } else {
            doItemIndexCreation(params, listener, requestMap, paramMap,
                    chain, index);
        }
    } catch (final Exception e) {
        final List<Throwable> errorList = getErrorList(paramMap);
        if (errorList.size() >= maxRetryCount) {
            listener.onError(e);
        } else {
            sleep(e);
            errorList.add(e);
            fork(() -> execute(params, listener, requestMap, paramMap,
                    chain));
        }
    } finally {
        indexCreationLock.unlock();
    }
}
 
Example 11
Source File: AbstractWriter.java    From elasticsearch-taste with Apache License 2.0 5 votes vote down vote up
public void open() {
    final IndicesExistsResponse existsResponse = client.admin().indices()
            .prepareExists(index).execute().actionGet();
    if (!existsResponse.isExists()) {
        final CreateIndexResponse createIndexResponse = client.admin()
                .indices().prepareCreate(index).execute().actionGet();
        if (!createIndexResponse.isAcknowledged()) {
            throw new TasteException("Failed to create " + index
                    + " index.");
        }
    }

    if (mappingBuilder != null) {
        final GetMappingsResponse response = client.admin().indices()
                .prepareGetMappings(index).setTypes(type).execute()
                .actionGet();
        if (response.mappings().isEmpty()) {
            final PutMappingResponse putMappingResponse = client.admin()
                    .indices().preparePutMapping(index).setType(type)
                    .setSource(mappingBuilder).execute().actionGet();
            if (!putMappingResponse.isAcknowledged()) {
                throw new TasteException("Failed to create a mapping of"
                        + index + "/" + type);
            }
        }
    }
}
 
Example 12
Source File: BaseElasticSearchIndexBuilder.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/**
 * removes any existing index and creates a new one
 */
protected void recreateIndex() {
    IndicesExistsResponse response = client.admin().indices().exists(new IndicesExistsRequest(indexName)).actionGet();
    if (response.isExists()) {
        client.admin().indices().delete(new DeleteIndexRequest(indexName)).actionGet();
    }

    // create index
    createIndex();
}
 
Example 13
Source File: BaseElasticSearchIndexBuilder.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/**
 * creates a new index if one does not exist
 */
protected void assureIndex() {
    IndicesExistsResponse response = client.admin().indices().exists(new IndicesExistsRequest(indexName)).actionGet();
    if (!response.isExists()) {
        createIndex();
    }
}
 
Example 14
Source File: ElasticsearchClient.java    From hawkular-apm with Apache License 2.0 5 votes vote down vote up
/**
 * Check if index is created. if not it will created it
 *
 * @param index The index
 * @return returns true if it just created the index. False if the index already existed
 */
private boolean createIndex(String index, Map<String, Object> defaultSettings) {
    IndicesExistsResponse res = client.admin().indices().prepareExists(index).execute().actionGet();
    boolean created = false;
    if (!res.isExists()) {
        CreateIndexRequestBuilder req = client.admin().indices().prepareCreate(index);
        req.setSettings(defaultSettings);
        created = req.execute().actionGet().isAcknowledged();
        if (!created) {
            throw new RuntimeException("Could not create index [" + index + "]");
        }
    }

    return created;
}
 
Example 15
Source File: ElasticsearchUtil.java    From SpringBootLearn with Apache License 2.0 5 votes vote down vote up
/**
 * 判断索引是否存在
 * @param index
 * @return
 */
public static boolean isIndexExist(String index) {
    IndicesExistsResponse inExistsResponse = client
            .admin()
            .indices()
            .exists(new IndicesExistsRequest(index))
            .actionGet();
    if (inExistsResponse.isExists()) {
        log.info("Index [" + index + "] is exist!");
    } else {
        log.info("Index [" + index + "] is not exist!");
    }
    return inExistsResponse.isExists();
}
 
Example 16
Source File: ModelsAction.java    From zentity with Apache License 2.0 5 votes vote down vote up
/**
 * Check if the .zentity-models index exists, and if it doesn't, then create it.
 *
 * @param client The client that will communicate with Elasticsearch.
 * @throws ForbiddenException
 */
public static void ensureIndex(NodeClient client) throws ForbiddenException {
    try {
        IndicesExistsRequestBuilder request = client.admin().indices().prepareExists(INDEX_NAME);
        IndicesExistsResponse response = request.get();
        if (!response.isExists())
            SetupAction.createIndex(client);
    } catch (ElasticsearchSecurityException se) {
        throw new ForbiddenException("The .zentity-models index does not exist and you do not have the 'create_index' privilege. An authorized user must create the index by submitting: POST _zentity/_setup");
    }
}
 
Example 17
Source File: IndexController.java    From blog-sample with Apache License 2.0 5 votes vote down vote up
/**
 * 判断索引是否存在
 * @param index 索引名
 * @author jitwxs
 * @since 2018/10/9 15:08
 */
@PostMapping("/index/hasExist")
public ResultBean hasExist(String index) {
    IndicesExistsRequest inExistsRequest = new IndicesExistsRequest(index);
    IndicesExistsResponse inExistsResponse = transportClient.admin().indices().exists(inExistsRequest).actionGet();

    return inExistsResponse.isExists() ? ResultBean.success("索引存在!") : ResultBean.error("索引不存在!");
}
 
Example 18
Source File: DKSearchOutputImpl.java    From dk-fitting with Apache License 2.0 4 votes vote down vote up
/**
 * 从es导出数据,导出为xls
 * @param hostIps
 * @param clusterName
 * @param indexName
 * @param typeName
 * @param port
 * @param start
 * @param size
 * @return
 * @throws TException
 */
@Override
public String ES2XLS(String hostIps, String clusterName, String indexName, String typeName, int port, int start, int size) throws Exception {
    String type=".xlsx";
    client=ESUtils.getClient( hostIps,port,clusterName );
    IndicesExistsResponse existsResponse = client.admin().indices().prepareExists( indexName ).execute().actionGet();
    if (!existsResponse.isExists()){
        return "index Non-existent ";
    }
    TypesExistsResponse typesExistsResponse = client.admin().indices().prepareTypesExists( indexName ).setTypes( typeName ).execute().actionGet();
    if (!typesExistsResponse.isExists()){
        return "type Non-existent";
    }
    //把导出的数据以json格式写到文件里,
    BufferedOutputStream out=new BufferedOutputStream( new FileOutputStream( indexName+"_"+typeName+"_"+System.currentTimeMillis()+type,true) );
    SearchResponse response=null;

    long totalHits = client.prepareSearch( indexName ).setTypes( typeName ).get().getHits().totalHits;
    //setSearchType(SearchType.Scan) 告诉ES不需要排序只要结果返回即可 setScroll(new TimeValue(600000)) 设置滚动的时间
    //每次返回数据10000条。一直循环查询直到所有的数据都查询出来
    //setTerminateAfter(10000)    //如果达到这个数量,提前终止
    SearchRequestBuilder requestBuilder = client.prepareSearch( indexName ).setTypes( typeName ).setQuery( QueryBuilders.matchAllQuery() ).setScroll( new TimeValue(600000) );
    response=requestBuilder.setFrom( start ).setSize( size ).execute().actionGet();
    String title="ES导出";
    title=URLEncoder.encode( title,"UTF-8" );
    SearchHits searchHits = response.getHits();
    if (searchHits==null){return "no searchHit";}
    String[] keys=null;
    ArrayList<Object[]> list=new ArrayList<>(  );
    for (int i = 0; i <searchHits.getHits().length ; i++) {
        Set<String> keySet = searchHits.getHits()[i].getSource().keySet();
        keys = keySet.toArray( new String[keySet.size()] );
        Collection<Object> values = searchHits.getHits()[i].getSource().values();
        Object[] object = values.toArray( new Object[values.size()] );
        list.add( object );
    }
     ExportExcelUtils.exportExcelXSSF( title, keys, list, out );

    out.close();
    return "SUCCESS";
}
 
Example 19
Source File: IndexUtils.java    From search-spring-boot-starter with Apache License 2.0 4 votes vote down vote up
public static boolean isExistsIndex(Client client, String index) throws InterruptedException, ExecutionException {
    IndicesExistsResponse response = client.admin().indices().exists(new IndicesExistsRequest(index)).get();
    return response.isExists();
}
 
Example 20
Source File: ElasticsearchClusterRunner.java    From elasticsearch-cluster-runner with Apache License 2.0 4 votes vote down vote up
public boolean indexExists(final String index, final BuilderCallback<IndicesExistsRequestBuilder> builder) {
    final IndicesExistsResponse actionGet = builder.apply(client().admin().indices().prepareExists(index)).execute().actionGet();
    return actionGet.isExists();
}