如何使用ES Java API创建新类型的索引

时间:2017-08-24 01:35:45

标签: elasticsearch

我已成功创建索引使用客户端,代码如下:

public static boolean addIndex(Client client,String index) throws Exception {
    if(client == null){
        client = getSettingClient();
    }
    CreateIndexRequestBuilder requestBuilder = client.admin().indices().prepareCreate(index);
    CreateIndexResponse response = requestBuilder.execute().actionGet();
    return response.isAcknowledged();  
    //client.close();
}

public static boolean addIndexType(Client client, String index, String type) throws Exception {
    if (client == null) {
        client = getSettingClient();
    }
    TypesExistsAction action = TypesExistsAction.INSTANCE;
    TypesExistsRequestBuilder requestBuilder = new TypesExistsRequestBuilder(client, action, index);
    requestBuilder.setTypes(type);
    TypesExistsResponse response = requestBuilder.get();
    return response.isExists();
}

但是,addIndexType的方法不受影响,类型不是create。

我不知道如何创建类型?

2 个答案:

答案 0 :(得分:0)

通过提供正确的映射配置,可以在创建索引时创建类型。或者,在索引某种类型的文档时会创建一个类型。然而,第一个建议是更好的建议,因为那时你可以控制该类型的完整映射,而不是依赖于动态映射。

答案 1 :(得分:0)

您可以通过以下方式设置类型:

// JSON schema is the JSON mapping which you want to give for the index.

JSONObject builder = new JSONObject().put(type, JSONSchema);

// And then just fire the below command

client.admin().indices().preparePutMapping(indexName)
                        .setType(type)
                        .setSource(builder.toString(), XContentType.JSON)
                        .execute()
                        .actionGet();