Java High Level REST Client 之 创建索引

1. 创建索引请求

CreateIndexRequest request = new CreateIndexRequest("twitter");

2.设置

2.1 分别设置

2.1.1 索引设置

request.settings(Settings.builder()
.put("index.number_of_shards", 3)
.put("index.number_of_replicas", 2)
);

2.1.2 映射表

request.mapping(
"{\n" +
" \"properties\": {\n" +
" \"message\": {\n" +
" \"type\": \"text\"\n" +
" }\n" +
" }\n" +
"}",
XContentType.JSON);

也可以用map:

Map<String, Object> message = new HashMap<>();
message.put("type", "text");
Map<String, Object> properties = new HashMap<>();
properties.put("message", message);
Map<String, Object> mapping = new HashMap<>();
mapping.put("properties", properties);
request.mapping(mapping);

或者XContentBuilder :

XContentBuilder builder = XContentFactory.jsonBuilder();
builder.startObject();
{
builder.startObject("properties");
{
builder.startObject("message");
{
builder.field("type", "text");
}
builder.endObject();
}
builder.endObject();
}
builder.endObject();
request.mapping(builder);

2.1.3 索引别名

request.alias(new Alias("twitter_alias").filter(QueryBuilders.termQuery("user", "kimchy")));

别名不仅仅可以关联一个索引,它能聚合多个索引。

例如我们为索引my_index_1 和 my_index_2 创建一个别名my_index_alias,这样对my_index_alias的操作(仅限读操作),会操作my_index_1和my_index_2,类似于聚合了my_index_1和my_index_2.但是我们是不能对my_index_alias进行写操作,当有多个索引时alias,不能区分到底操作哪一个。

2.2 整体设置

request.source("{\n" +
" \"settings\" : {\n" +
" \"number_of_shards\" : 1,\n" +
" \"number_of_replicas\" : 0\n" +
" },\n" +
" \"mappings\" : {\n" +
" \"properties\" : {\n" +
" \"message\" : { \"type\" : \"text\" }\n" +
" }\n" +
" },\n" +
" \"aliases\" : {\n" +
" \"twitter_alias\" : {}\n" +
" }\n" +
"}", XContentType.JSON);

3.其他参数

超时 (Timeout to wait for the all the nodes to acknowledge the index creation as a TimeValue):

request.setTimeout(TimeValue.timeValueMinutes(2));

连接主节点超时(Timeout to connect to the master node as a TimeValue):

request.setMasterTimeout(TimeValue.timeValueMinutes(1));
Java High Level REST Client  之 创建索引

4.执行请求

4.1 同步执行

CreateIndexResponse createIndexResponse = client.indices().create(request, RequestOptions.DEFAULT);

4.2 异步执行

client.indices().createAsync(request, RequestOptions.DEFAULT, listener);

其中listener:

ActionListener<CreateIndexResponse> listener =
new ActionListener<CreateIndexResponse>() { @Override
public void onResponse(CreateIndexResponse createIndexResponse) { } @Override
public void onFailure(Exception e) { }
};

5.响应

boolean acknowledged = createIndexResponse.isAcknowledged();
boolean shardsAcknowledged = createIndexResponse.isShardsAcknowledged();

上一篇:C/C++中的空类及抽象类大小


下一篇:ftk学习记录(IME文章)