1. Refresh API 刷新API
// RefreshRequest可以应用于一个或多个索引,甚至可以应用于_all索引:
// Refresh one index Refresh multiple indices Refresh all the indices
RefreshRequest request = new RefreshRequest("index1");
RefreshRequest requestMultiple = new RefreshRequest("index1", "index2");
RefreshRequest requestAll = new RefreshRequest();
RefreshResponse refreshResponse = client.indices().refresh(request, RequestOptions.DEFAULT);
int totalShards = refreshResponse.getTotalShards();
int successfulShards = refreshResponse.getSuccessfulShards();
int failedShards = refreshResponse.getFailedShards();
DefaultShardOperationFailedException[] failures = refreshResponse.getShardFailures();
2. Flush API
FlushRequest可以应用于一个或多个索引,甚至可以应用于_all索引:
FlushRequest request = new FlushRequest("index1");
FlushRequest requestMultiple = new FlushRequest("index1", "index2");
FlushRequest requestAll = new FlushRequest();
FlushResponse flushResponse = client.indices().flush(request, RequestOptions.DEFAULT);
// 刷新请求命中的分片总数 刷新成功的分片数 刷新失败的分片数 如果操作在一个或多个分片上失败,则失败列表
int totalShards = flushResponse.getTotalShards();
int successfulShards = flushResponse.getSuccessfulShards();
int failedShards = flushResponse.getFailedShards();
DefaultShardOperationFailedException[] failures = flushResponse.getShardFailures();
3. Clear Cache API 清除缓存API
ClearIndicesCacheRequest可以应用于一个或多个索引,甚至可以应用于_all索引:
ClearIndicesCacheRequest request = new ClearIndicesCacheRequest("index1");
ClearIndicesCacheRequest requestMultiple = new ClearIndicesCacheRequest("index1", "index2");
ClearIndicesCacheRequest requestAll = new ClearIndicesCacheRequest();
ClearIndicesCacheResponse clearCacheResponse = client.indices().clearCache(request, RequestOptions.DEFAULT);
// 清除缓存请求命中的分片总数 成功清除缓存的分片数 清除缓存失败的分片数 如果操作在一个或多个分片上失败,则失败列表
int totalShards = clearCacheResponse.getTotalShards();
int successfulShards = clearCacheResponse.getSuccessfulShards();
int failedShards = clearCacheResponse.getFailedShards();
DefaultShardOperationFailedException[] failures = clearCacheResponse.getShardFailures();
4. Put Mapping API 设置mapping
// PutMappingRequest需要一个索引参数:
PutMappingRequest request = new PutMappingRequest("twitter");
// 对要在映射上创建的字段的描述;如果未定义,则映射将默认为空。
// jsonString
request.source(
"{\n" +
" \"properties\": {\n" +
" \"message\": {\n" +
" \"type\": \"text\"\n" +
" }\n" +
" }\n" +
"}",
XContentType.JSON);
// 作为Map提供的映射源,它会自动转换为JSON格式
Map<String, Object> jsonMap = new HashMap<>();
Map<String, Object> message = new HashMap<>();
message.put("type", "text");
Map<String, Object> properties = new HashMap<>();
properties.put("message", message);
jsonMap.put("properties", properties);
request.source(jsonMap);
// 作为XContentBuilder对象提供的映射源,Elasticsearch内置帮助器可生成JSON内容
XContentBuilder builder = XContentFactory.jsonBuilder();
builder.startObject();
{
builder.startObject("properties");
{
builder.startObject("message");
{
builder.field("type", "text");
}
builder.endObject();
}
builder.endObject();
}
builder.endObject();
request.source(builder);
AcknowledgedResponse putMappingResponse = client.indices().putMapping(request, RequestOptions.DEFAULT);
// 指示是否所有节点都已确认请求
boolean acknowledged = putMappingResponse.isAcknowledged();
{
"gurp_test2" : {
"mappings" : {
"news" : {
"properties" : {
"content" : {
"type" : "text",
"analyzer" : "ik_max_word"
},
"title" : {
"type" : "text",
"fields" : {
"suggest" : {
"type" : "completion",
"analyzer" : "ik_max_word",
// 默认值
"preserve_separators" : true,
"preserve_position_increments" : true,
"max_input_length" : 50
}
},
"analyzer" : "ik_max_word"
}
}
}
}
}
}
----------------------------------
private static final Logger LOG = LoggerFactory.getLogger(MappingPutByBuilder.class);
private static void mappingPutByBuilder(RestHighLevelClient highLevelClient, String index){
try {
PutMappingRequest putMappingRequest = new PutMappingRequest(index);
XContentBuilder builder = XContentFactory.jsonBuilder();
builder.startObject();
{
builder.startObject("properties");
{
builder.startObject("title");
{
builder.field("type", "text").field("analyzer", "ik_max_word");
builder.startObject("fields");
{
builder.startObject("suggest");
{
builder.field("type", "completion").field("analyzer", "ik_max_word");
}
builder.endObject();
}
builder.endObject();
}
builder.endObject();
builder.startObject("content");
{
builder.field("type", "text").field("analyzer", "ik_max_word");
}
builder.endObject();
}
builder.endObject();
}
builder.endObject();
putMappingRequest.source(builder);
AcknowledgedResponse putMappingResponse = highLevelClient.indices().putMapping(putMappingRequest, RequestOptions.DEFAULT);
LOG.info("mappingByBuilder response is :{},acknowledged:{}" ,putMappingResponse.toString(), putMappingResponse.isAcknowledged());
} catch (Exception e) {
LOG.error("mappingByBuilder error" ,e);
}
}
/**
* Create a index by XContentBuilder
*/
private static void indexByXContentBuilder(RestHighLevelClient highLevelClient, String index, String type,String id) {
try {
// 删除索引
try {
DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest(index);
AcknowledgedResponse deleteIndexResponse = highLevelClient.indices().delete(deleteIndexRequest, RequestOptions.DEFAULT);
// 指示是否所有节点都已确认请求
LOG.info("deleteIndexResponse :{}",deleteIndexResponse.toString());
} catch (ElasticsearchException exception) {
if (exception.status() == RestStatus.NOT_FOUND) {
LOG.info("deleteIndexResponse not such index");
}
}
XContentBuilder builder = XContentFactory.jsonBuilder();
builder.startObject();
builder.endObject();
IndexRequest indexRequest = new IndexRequest(index, type,id).source(builder);
IndexResponse indexResponse = highLevelClient.index(indexRequest, RequestOptions.DEFAULT);
LOG.info("IndexByXContentBuilder response is {}", indexResponse.toString());
// 删除默认生成的一条记录
DeleteRequest request = new DeleteRequest(index, type,id);
DeleteResponse deleteResponse = highLevelClient.delete( request, RequestOptions.DEFAULT);
LOG.info("deleResponse index {},id{}",deleteResponse.getIndex(),deleteResponse.getId());
} catch (Exception e) {
LOG.error("IndexByXContentBuilder is failed,exception occurred.", e);
}
}
5. Get Mappings API 获取mapping
// GetMappingsRequest可以传入索引的可选列表:
GetMappingsRequest request = new GetMappingsRequest();
request.indices("twitter");
GetMappingsResponse getMappingResponse = client.indices().getMapping(request, RequestOptions.DEFAULT);
// 返回所有索引的映射 检索特定索引的映射 将映射作为Java Map获取
Map<String, MappingMetaData> allMappings = getMappingResponse.mappings();
MappingMetaData indexMapping = allMappings.get("twitter");
Map<String, Object> mapping = indexMapping.sourceAsMap();
6. Get Field Mappings API 获取字段mapping
GetFieldMappingsRequest可以传入索引的可选列表,类型的可选列表和字段列表:
GetFieldMappingsRequest request = new GetFieldMappingsRequest();
request.indices("twitter");
request.fields("message", "timestamp");
GetFieldMappingsResponse response =
client.indices().getFieldMapping(request, RequestOptions.DEFAULT);
// 返回所有请求的索引字段的映射 检索特定索引的映射 获取消息字段的映射元数据 获取字段的全名 获取字段的映射源
final Map<String, Map<String, GetFieldMappingsResponse.FieldMappingMetaData>> mappings =
response.mappings();
final Map<String, GetFieldMappingsResponse.FieldMappingMetaData> fieldMappings =
mappings.get("twitter");
final GetFieldMappingsResponse.FieldMappingMetaData metaData =
fieldMappings.get("message");
final String fullName = metaData.fullName();
final Map<String, Object> source = metaData.sourceAsMap();
7. Index Aliases API 索引别名
// 索引别名API 使用名称进行别名,所有API都会自动将别名转换为实际的索引名称。
// 一个IndicesAliasesRequest必须至少具有一个AliasAction:
IndicesAliasesRequest request = new IndicesAliasesRequest();
AliasActions aliasAction =
new AliasActions(AliasActions.Type.ADD)
.index("index1")
.alias("alias1");
request.addAliasAction(aliasAction);
// 支持以下操作类型:add-为索引添加别名,remove-删除与索引关联的别名,remove_index-删除索引。
// 创建一个别名alias1,并在字段年份上使用可选的过滤器
AliasActions addIndexAction =
new AliasActions(AliasActions.Type.ADD)
.index("index1")
.alias("alias1")
.filter("{\"term\":{\"year\":2016}}");
// 创建与两个索引和可选路由关联的别名alias2
AliasActions addIndicesAction =
new AliasActions(AliasActions.Type.ADD)
.indices("index1", "index2")
.alias("alias2")
.routing("1");
// 删除关联的别名alias3
AliasActions removeAction =
new AliasActions(AliasActions.Type.REMOVE)
.index("index3")
.alias("alias3");
AliasActions removeIndexAction =
new AliasActions(AliasActions.Type.REMOVE_INDEX)
.index("index4");
AcknowledgedResponse indicesAliasesResponse =
client.indices().updateAliases(request, RequestOptions.DEFAULT);
boolean acknowledged = indicesAliasesResponse.isAcknowledged();
8. Delete Alias API 删除别名
// DeleteAliasRequest需要一个索引和一个别名参数:
DeleteAliasRequest request = new DeleteAliasRequest("index1", "alias1");
org.elasticsearch.client.core.AcknowledgedResponse deleteAliasResponse =
client.indices().deleteAlias(request, RequestOptions.DEFAULT);
9. Exists Alias API 别名是否存在
Exists Alias API使用GetAliasesRequest作为其请求对象。可以在构造时或以后通过相关的setter方法可选地提供一个或多个别名。
GetAliasesRequest request = new GetAliasesRequest();
GetAliasesRequest requestWithAlias = new GetAliasesRequest("alias1");
GetAliasesRequest requestWithAliases =
new GetAliasesRequest(new String[]{"alias1", "alias2"});
boolean exists = client.indices().existsAlias(request, RequestOptions.DEFAULT);
10. Get Alias API 获取别名
Get Alias API使用GetAliasesRequest作为其请求对象。可以在构造时或以后通过相关的setter方法可选地提供一个或多个别名。
GetAliasesRequest request = new GetAliasesRequest();
GetAliasesRequest requestWithAlias = new GetAliasesRequest("alias1");
GetAliasesRequest requestWithAliases =
new GetAliasesRequest(new String[]{"alias1", "alias2"});
// 可选参数
request.aliases("alias"); 要检索的一个或多个别名
request.indices("index"); 别名与之相关的一个或多个索引
GetAliasesResponse response = client.indices().getAlias(request, RequestOptions.DEFAULT);
Map<String, Set<AliasMetaData>> aliases = response.getAliases();
GetAliasesResponse类包含有关错误(如果发生)的信息。此信息可能在字段中,错误或异常取决于情况。
RestStatus status = response.status();
ElasticsearchException exception = response.getException();
String error = response.getError();
11. Get Settings API 获取设置
一个GetSettingsRequest需要一个或多个索引参数:
GetSettingsRequest request = new GetSettingsRequest().indices("index");
一个或多个设置是唯一检索到的设置。如果未设置,将检索所有设置
request.names("index.number_of_shards");
GetSettingsResponse getSettingsResponse = client.indices().getSettings(request, RequestOptions.DEFAULT);
///我们可以直接从响应中检索特定索引的设置值作为字符串
//我们还可以检索特定索引的Settings对象以进行进一步检查
//返回的Settings对象为非String类型提供了便捷方法
String numberOfShardsString = getSettingsResponse.getSetting("index", "index.number_of_shards");
Settings indexSettings = getSettingsResponse.getIndexToSettings().get("index");
Integer numberOfShards = indexSettings.getAsInt("index.number_of_shards", null);
// 如果在GetSettingsRequest中将includeDefaults标志设置为true,则GetSettingsResponse的行为将有所不同。
String refreshInterval = getSettingsResponse.getSetting("index", "index.refresh_interval");
Settings indexDefaultSettings = getSettingsResponse.getIndexToDefaultSettings().get("index");
12. Get Index API 索引信息获取
GetIndexRequest request = new GetIndexRequest("index");
GetIndexResponse getIndexResponse = client.indices().get(request, RequestOptions.DEFAULT);
MappingMetaData indexMappings = getIndexResponse.getMappings().get("index");
Map<String, Object> indexTypeMappings = indexMappings.getSourceAsMap();
List<AliasMetaData> indexAliases = getIndexResponse.getAliases().get("index");
String numberOfShardsString = getIndexResponse.getSetting("index", "index.number_of_shards");
Settings indexSettings = getIndexResponse.getSettings().get("index");
Integer numberOfShards = indexSettings.getAsInt("index.number_of_shards", null);
TimeValue time = getIndexResponse.getDefaultSettings().get("index")
.getAsTime("index.refresh_interval", null);