HttpHost host=new HttpHost(“IP地址”, “端口号”, HttpHost.DEFAULT_SCHEME_NAME);
RestClientBuilder builder=RestClient.builder(host);
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(“用户名”, “密码”));
builder.setHttpClientConfigCallback(f -> f.setDefaultCredentialsProvider(credentialsProvider));
RestHighLevelClient restClient = new RestHighLevelClient( builder);

创建索引的例子说明:

//indexName 是索引的名称,务必小写。

public static void createIndexS(String indexName) throws IOException {
    //有使用账户密码
    HttpHost host = new HttpHost("127.0.0.1",  9200, HttpHost.DEFAULT_SCHEME_NAME);

    RestClientBuilder builder = RestClient.builder(host);

    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(USERNAME, PASSWORD));
    builder.setHttpClientConfigCallback(f -> f.setDefaultCredentialsProvider(credentialsProvider));
    RestHighLevelClient client = new RestHighLevelClient(builder);
    // ES 索引默认需要小写,故笔者将其转为小写
    CreateIndexRequest requestIndex = new CreateIndexRequest(indexName.toLowerCase());//创建新索引请求对象

    // 注: 设置副本数为0,索引刷新时间为-1对大批量索引数据效率的提升有不小的帮助
    requestIndex.settings(Settings.builder().put("index.number_of_shards", 5)
            .put("index.number_of_replicas", 0)
            .put("index.refresh_interval", "-1"));//通CreateIndexRequest对象设置分片,副本和映射
    //requestIndex.mapping(mappings, XContentType.JSON);

    CreateIndexResponse createIndexResponse = client.indices().create(requestIndex, RequestOptions.DEFAULT);
    boolean acknowledgee =createIndexResponse.isAcknowledged();//返回创建的所有状态
    client.close();
}

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐