Indices Administration
要想访问indices JavaAPI,你需要从 AdminClient 类中调用 indices()
方法:
IndicesAdminClient indicesAdminClient = client.admin().indices();
在这篇文档的其余部分中,我们使用 client.admin() 来获取。
|
Create Index
使用 IndicesAdminClient, 你可以使用默认设置和空映射来创建index:
client.admin().indices().prepareCreate("twitter").get();
Index Settings
创建的每个index都有单独的设置。
client.admin().indices().prepareCreate("twitter")
.setSettings(Settings.builder() (1)
.put("index.number_of_shards", 3)
.put("index.number_of_replicas", 2)
)
.get(); (2)
1 | 该index的设置 |
2 | 执行操作并等待结果 |
Put Mapping
你可以在创建index的时候添加映射:
You can add mappings at index creation time:
client.admin().indices().prepareCreate("twitter") (1)
.addMapping("_doc", "message", "type=text") (2)
.get();
1 | Creates an index 名字是 twitter |
2 | 添加名为 message 类型为 _doc 的字段,该字段的数据类型为 text |
上面的 addMapping
方法有几种变体,有些采用 XContentBuilder
或带有映射定义的 Map
作为参数。
请在阅读javadocs后再选择适合你的最简单的方法。
PUT mapping API还允许在创建 index 后更新映射。 在这种情况下,您可以提供一个类似于REST API语法的String映射:
client.admin().indices().preparePutMapping("twitter") (1)
.setType("_doc")
.setSource("{\n" +
" \"properties\": {\n" +
" \"name\": {\n" + (2)
" \"type\": \"text\"\n" +
" }\n" +
" }\n" +
"}", XContentType.JSON)
.get();
// You can also provide the type in the source document
client.admin().indices().preparePutMapping("twitter")
.setType("_doc")
.setSource("{\n" +
" \"_doc\":{\n" + (3)
" \"properties\": {\n" +
" \"name\": {\n" +
" \"type\": \"text\"\n" +
" }\n" +
" }\n" +
" }\n" +
"}", XContentType.JSON)
.get();
1 | 修改名为 twitter 的 index 的映射 |
2 | 向映射中添加一个名为 name 的新字段 |
3 | 这中方式也可以在source中提供 |
Refresh
Refresh API允许显式地刷新一个或多个index:
client.admin().indices().prepareRefresh().get(); (1)
client.admin().indices()
.prepareRefresh("twitter") (2)
.get();
client.admin().indices()
.prepareRefresh("twitter", "company") (3)
.get();
1 | 刷新所有 indices |
2 | 刷新单个 index |
3 | 刷新多个 indices |
Get Settings
Get settings API 允许检索 index/indices 的设置:
GetSettingsResponse response = client.admin().indices()
.prepareGetSettings("company", "employee").get(); (1)
for (ObjectObjectCursor<String, Settings> cursor : response.getIndexToSettings()) { (2)
String index = cursor.key; (3)
Settings settings = cursor.value; (4)
Integer shards = settings.getAsInt("index.number_of_shards", null); (5)
Integer replicas = settings.getAsInt("index.number_of_replicas", null); (6)
}
1 | 获取 company 和 employee indices 的设置 |
2 | 遍历结果 |
3 | Index 名称 |
4 | Index 的设置 |
5 | Index 的 shards 数量 |
6 | Index 的 replicas 数量 |