作者简介:大家好,我是smart哥,前中兴通讯、美团架构师,现某互联网公司CTO
联系qq:184480602,加我进群,大家一起学习,一起进步,一起对抗互联网寒冬
学习必须往深处挖,挖的越深,基础越扎实!
阶段1、深入多线程
阶段2、深入多线程设计模式
阶段3、深入juc源码解析
码哥源码部分
码哥讲源码-原理源码篇【2024年最新大厂关于线程池使用的场景题】
码哥讲源码-原理源码篇【揭秘join方法的唤醒本质上决定于jvm的底层析构函数】
码哥源码-原理源码篇【Doug Lea为什么要将成员变量赋值给局部变量后再操作?】
码哥讲源码【谁再说Spring不支持多线程事务,你给我抽他!】
打脸系列【020-3小时讲解MESI协议和volatile之间的关系,那些将x86下的验证结果当作最终结果的水货们请闭嘴】
9、Index APIs
9.1、Analyze API
@Test
public void analyze() throws IOException {
//最简单的形式
AnalyzeRequest request1 = AnalyzeRequest.withGlobalAnalyzer("english",
"Some text to analyze", "Some more text to analyze");
//自定义配置
//自定义token filter
Map<String, Object> stopFilter = new HashMap<>();
stopFilter.put("type", "stop");
stopFilter.put("stopwords", new String[]{ "to" });
AnalyzeRequest request2 = AnalyzeRequest.buildCustomAnalyzer("standard")
.addCharFilter("html_strip")//字符过滤器
.addTokenFilter("lowercase")//添加一个内置的token filter
.addTokenFilter(stopFilter)
.build("<b>Some text to analyze</b>");
//也可以通过只包含字符过滤器和记号过滤器来构建一个自定义的规范化器:
AnalyzeRequest request3 = AnalyzeRequest.buildCustomNormalizer()
.addTokenFilter("lowercase")
.build("<b>BaR</b>");
//可以使用在现有索引中定义的分析器来分析文本:
AnalyzeRequest request4 = AnalyzeRequest.withIndexAnalyzer(
"my_index",
"my_analyzer",
"some text to analyze"
);
//可以使用索引中特定字段的映射来分析文本:
AnalyzeRequest request5 = AnalyzeRequest.withField("my_index", "my_field", "some text to analyze");
//可选参数
request1.explain(false);
request1.attributes("keyword", "type");
//同步请求
AnalyzeResponse response = client.indices().analyze(request1, RequestOptions.DEFAULT);
//异步请求
client.indices().analyzeAsync(request2, RequestOptions.DEFAULT, new ActionListener<AnalyzeResponse>() {
@Override
public void onResponse(AnalyzeResponse analyzeResponse) {
}
@Override
public void onFailure(Exception e) {
}
});
//响应
//获取Tokens
List<AnalyzeResponse.AnalyzeToken> tokens = response.getTokens();
//如果explain被设置为true,那么信息将从detail()方法返回:
DetailAnalyzeResponse detail = response.detail();
for (AnalyzeResponse.AnalyzeToken token : tokens) {
System.out.println(token.getTerm());
}
// System.out.println(detail.toString());
}
9.2、Create Index API
@Test
public void create_index() throws IOException {
//构建createIndex请求
//方式一:分段构建
CreateIndexRequest request = new CreateIndexRequest("twitter");
//settings
request.settings(Settings.builder()
.put("index.number_of_shards", 1)
.put("index.number_of_replicas", 1)
);
//mappings
//第一种方式:通过JSON字符串设置
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);
//第三种方式:通过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.mapping(builder);
//别名
request.alias(
new Alias("twitter_alias")
.filter(QueryBuilders.termQuery("user", "kimchy")));
//方式二:通过JSON字符串整体设置(包括settings,mappings,alias)
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);
//可选参数
request.setTimeout(TimeValue.timeValueMinutes(2));
request.setMasterTimeout(TimeValue.timeValueMinutes(1));
request.waitForActiveShards(ActiveShardCount.from(2));
request.waitForActiveShards(ActiveShardCount.DEFAULT);
//同步请求
CreateIndexResponse createIndexResponse = client.indices().create(request, RequestOptions.DEFAULT);
//异步请求
client.indices().createAsync(request, RequestOptions.DEFAULT, new ActionListener<CreateIndexResponse>() {
@Override
public void onResponse(CreateIndexResponse createIndexResponse) {
}
@Override
public void onFailure(Exception e) {
}
});
//响应
//是否所有节点都已确认请求
boolean acknowledged = createIndexResponse.isAcknowledged();
//索引中每个分片在超时前是否启动了所需数量的分片拷贝
boolean shardsAcknowledged = createIndexResponse.isShardsAcknowledged();
System.out.println(acknowledged);
System.out.println(shardsAcknowledged);
}
9.3、Delete Index API
@Test
public void delete_index() throws IOException {
DeleteIndexRequest request = new DeleteIndexRequest("twitter");
//可选参数
request.timeout(TimeValue.timeValueMinutes(2));
request.timeout("2m");
request.masterNodeTimeout(TimeValue.timeValueMinutes(1));
request.masterNodeTimeout("1m");
request.indicesOptions(IndicesOptions.lenientExpandOpen());
//同步请求
AcknowledgedResponse deleteIndexResponse = client.indices().delete(request, RequestOptions.DEFAULT);
//异步请求
client.indices().deleteAsync(request, RequestOptions.DEFAULT, new ActionListener<AcknowledgedResponse>() {
@Override
public void onResponse(AcknowledgedResponse acknowledgedResponse) {
}
@Override
public void onFailure(Exception e) {
}
});
//响应
boolean acknowledged = deleteIndexResponse.isAcknowledged();
//如果没有找到索引,将抛出ElasticsearchException
try {
DeleteIndexRequest request1 = new DeleteIndexRequest("does_not_exist");
client.indices().delete(request, RequestOptions.DEFAULT);
} catch (ElasticsearchException exception) {
if (exception.status() == RestStatus.NOT_FOUND) {
System.out.println("index not found!");
}
}
}
9.4、Index Exists API
@Test
public void index_exists() throws IOException {
//高级REST客户端使用GetIndexRequest for Index Exists API。索引名(或索引名)是必需的。
GetIndexRequest request = new GetIndexRequest("twitter");
//可选参数
request.local(false);
request.humanReadable(true);
request.includeDefaults(false);
request.indicesOptions(IndicesOptions.LENIENT_EXPAND_OPEN);
//同步请求
boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
//异步请求
client.indices().existsAsync(request, RequestOptions.DEFAULT, new ActionListener<Boolean>() {
@Override
public void onResponse(Boolean aBoolean) {
}
@Override
public void onFailure(Exception e) {
}
});
//响应
System.out.println(exists);
}
9.5、Open Index API
@Test
public void open_index() throws IOException {
OpenIndexRequest request = new OpenIndexRequest("bank");
//可选参数
request.timeout(TimeValue.timeValueMinutes(2));
request.timeout("2m");
request.masterNodeTimeout(TimeValue.timeValueMinutes(1));
request.masterNodeTimeout("1m");
request.waitForActiveShards(2);
request.waitForActiveShards(ActiveShardCount.DEFAULT);
request.indicesOptions(IndicesOptions.strictExpandOpen());
//同步请求
OpenIndexResponse openIndexResponse = client.indices().open(request, RequestOptions.DEFAULT);
//异步请求
client.indices().openAsync(request, RequestOptions.DEFAULT, new ActionListener<OpenIndexResponse>() {
@Override
public void onResponse(OpenIndexResponse openIndexResponse) {
}
@Override
public void onFailure(Exception e) {
}
});
//响应
//指示是否所有节点都已确认请求
boolean acknowledged = openIndexResponse.isAcknowledged();
//指示索引中每个分片在超时前是否启动了所需数量的分片拷贝
boolean shardsAcked = openIndexResponse.isShardsAcknowledged();
System.out.println(acknowledged);
System.out.println(shardsAcked);
}
9.6、Close Index API
@Test
public void close_index() throws IOException {
CloseIndexRequest request = new CloseIndexRequest("bank");
//可选参数
request.setTimeout(TimeValue.timeValueMinutes(2));
request.setMasterTimeout(TimeValue.timeValueMinutes(1));
request.indicesOptions(IndicesOptions.lenientExpandOpen());
//同步请求
AcknowledgedResponse closeIndexResponse = client.indices().close(request, RequestOptions.DEFAULT);
//异步请求
client.indices().closeAsync(request, RequestOptions.DEFAULT, new ActionListener<CloseIndexResponse>() {
@Override
public void onResponse(CloseIndexResponse closeIndexResponse) {
}
@Override
public void onFailure(Exception e) {
}
});
//响应
System.out.println(closeIndexResponse);
}
9.7、Shrink Index API
@Test
public void shrink_index() throws IOException {
//ResizeRequest需要两个字符串参数:源索引和目标索引
ResizeRequest request = new ResizeRequest("target_index","source_index");
//可选参数
request.setTimeout(TimeValue.timeValueMinutes(2));
request.setMasterTimeout(TimeValue.timeValueMinutes(1));
request.setWaitForActiveShards(2);
request.setWaitForActiveShards(ActiveShardCount.DEFAULT);
request.setSettings(Settings.builder()
.put("index.number_of_shards", 2)//目标索引上的分片数
.putNull("index.routing.allocation.require._name")//删除从源索引复制的分配需求
.build());
List<Alias> list = new ArrayList<>();
list.add(new Alias("target_alias"));
request.setAliases(list);//要与目标索引关联的别名
//同步请求
ResizeResponse resizeResponse = client.indices().shrink(request, RequestOptions.DEFAULT);
//异步请求
client.indices().shrinkAsync(request, RequestOptions.DEFAULT, new ActionListener<ResizeResponse>() {
@Override
public void onResponse(ResizeResponse resizeResponse) {
}
@Override
public void onFailure(Exception e) {
}
});
//响应
boolean acknowledged = resizeResponse.isAcknowledged();
boolean shardsAcked = resizeResponse.isShardsAcknowledged();
}
9.8、Split Index API
@Test
public void split_index() throws IOException {
//ResizeRequest需要两个字符串参数:目标索引和源索引
ResizeRequest request = new ResizeRequest("target_index","source_index");
//可选参数
request.setTimeout(TimeValue.timeValueMinutes(2));
request.setMasterTimeout(TimeValue.timeValueMinutes(1));
request.setWaitForActiveShards(2);
request.setWaitForActiveShards(ActiveShardCount.DEFAULT);
request.setSettings(Settings.builder()
.put("index.number_of_shards", 4).build());
List<Alias> list = new ArrayList<>();
list.add(new Alias("target_alias"));
request.setAliases(list);
//同步请求
ResizeResponse resizeResponse = client.indices().split(request, RequestOptions.DEFAULT);
//异步请求
client.indices().splitAsync(request, RequestOptions.DEFAULT, new ActionListener<ResizeResponse>() {
@Override
public void onResponse(ResizeResponse resizeResponse) {
}
@Override
public void onFailure(Exception e) {
}
});
//响应
boolean acknowledged = resizeResponse.isAcknowledged();
boolean shardsAcked = resizeResponse.isShardsAcknowledged();
}
9.9、Clone Index API
@Test
public void clone_index() throws IOException {
//ResizeRequest需要两个字符串参数:目标索引和源索引
ResizeRequest request = new ResizeRequest("target_index","source_index");
//可选参数
request.setTimeout(TimeValue.timeValueMinutes(2));
request.setMasterTimeout(TimeValue.timeValueMinutes(1));
request.setWaitForActiveShards(2);
request.setWaitForActiveShards(ActiveShardCount.DEFAULT);
request.setSettings(Settings.builder()
.put("index.number_of_shards", 4).build());
List<Alias> list = new ArrayList<>();
list.add(new Alias("target_alias"));
request.setAliases(list);
//同步请求
ResizeResponse resizeResponse = client.indices().clone(request, RequestOptions.DEFAULT);
//异步请求
client.indices().cloneAsync(request, RequestOptions.DEFAULT, new ActionListener<ResizeResponse>() {
@Override
public void onResponse(ResizeResponse resizeResponse) {
}
@Override
public void onFailure(Exception e) {
}
});
//响应
boolean acknowledged = resizeResponse.isAcknowledged();
boolean shardsAcked = resizeResponse.isShardsAcknowledged();
}
9.10、Refresh API
@Test
public void refresh_request() throws IOException {
//RefreshRequest可以应用于一个或多个索引,甚至可以应用于所有索引
RefreshRequest request = new RefreshRequest("bank");
RefreshRequest requestMultiple = new RefreshRequest("index1", "index2");
RefreshRequest requestAll = new RefreshRequest();
//可选参数
request.indicesOptions(IndicesOptions.lenientExpandOpen());
//同步请求
RefreshResponse refreshResponse = client.indices().refresh(request, RequestOptions.DEFAULT);
//异步请求
client.indices().refreshAsync(request, RequestOptions.DEFAULT, new ActionListener<RefreshResponse>() {
@Override
public void onResponse(RefreshResponse refreshResponse) {
}
@Override
public void onFailure(Exception e) {
}
});
//响应
//刷新请求命中的分片总数
int totalShards = refreshResponse.getTotalShards();
//刷新成功的分片数
int successfulShards = refreshResponse.getSuccessfulShards();
//刷新失败的分片数
int failedShards = refreshResponse.getFailedShards();
//如果在一个或多个分片上操作失败,则列出失败列表
DefaultShardOperationFailedException[] failures = refreshResponse.getShardFailures();
System.out.println(totalShards);
System.out.println(successfulShards);
System.out.println(failedShards);
}
9.11、Flush API
@Test
public void flush() throws IOException {
//FlushRequest可以应用于一个或多个索引,甚至可以应用于所有索引
FlushRequest request = new FlushRequest("bank");
FlushRequest requestMultiple = new FlushRequest("index1", "index2");
FlushRequest requestAll = new FlushRequest();
//可选参数
request.indicesOptions(IndicesOptions.lenientExpandOpen());
request.waitIfOngoing(true);
request.force(true);
//同步请求
FlushResponse flushResponse = client.indices().flush(request, RequestOptions.DEFAULT);
//异步请求
client.indices().flushAsync(request, RequestOptions.DEFAULT, new ActionListener<FlushResponse>() {
@Override
public void onResponse(FlushResponse flushResponse) {
}
@Override
public void onFailure(Exception e) {
}
});
//响应
//刷新请求命中的分片总数
int totalShards = flushResponse.getTotalShards();
//已成功刷新的分片数
int successfulShards = flushResponse.getSuccessfulShards();
//刷新失败的分片数
int failedShards = flushResponse.getFailedShards();
//如果在一个或多个分片上操作失败,则列出失败列表
DefaultShardOperationFailedException[] failures = flushResponse.getShardFailures();
System.out.println(totalShards);
System.out.println(successfulShards);
}
9.12、Flush Synced API
@Test
public void flush_synced() throws IOException {
//SyncedFlushRequest可以应用于一个或多个索引,甚至可以应用于所有索引
SyncedFlushRequest request = new SyncedFlushRequest("person");
SyncedFlushRequest requestMultiple = new SyncedFlushRequest("index1", "index2");
SyncedFlushRequest requestAll = new SyncedFlushRequest();
//可选参数
request.indicesOptions(IndicesOptions.lenientExpandOpen());
//同步请求
SyncedFlushResponse flushSyncedResponse = client.indices().flushSynced(request, RequestOptions.DEFAULT);
//异步请求
client.indices().flushSyncedAsync(request, RequestOptions.DEFAULT, new ActionListener<SyncedFlushResponse>() {
@Override
public void onResponse(SyncedFlushResponse syncedFlushResponse) {
}
@Override
public void onFailure(Exception e) {
}
});
//响应
//刷新请求命中的分片总数
int totalShards = flushSyncedResponse.totalShards();
//已成功刷新的分片数
int successfulShards = flushSyncedResponse.successfulShards();
//刷新失败的分片数
int failedShards = flushSyncedResponse.failedShards();
for (Map.Entry<String, SyncedFlushResponse.IndexResult> responsePerIndexEntry:
flushSyncedResponse.getIndexResults().entrySet()) {
//要计算其结果的索引的名称
String indexName = responsePerIndexEntry.getKey();
SyncedFlushResponse.IndexResult indexResult = responsePerIndexEntry.getValue();
//索引的分片总数
int totalShardsForIndex = indexResult.totalShards();
//成功的分片数
int successfulShardsForIndex = indexResult.successfulShards();
//失败的分片数
int failedShardsForIndex = indexResult.failedShards();
if (failedShardsForIndex > 0) {
//包含分片相关的信息,如id,状态,版本等,为失败的分片副本。如果整个分片失败,则返回一个空映射。
for (SyncedFlushResponse.ShardFailure failureEntry: indexResult.failures()) {
int shardId = failureEntry.getShardId();
String failureReason = failureEntry.getFailureReason();
Map<String, Object> routing = failureEntry.getRouting();
}
}
}
}
9.13、Clear Cache API
@Test
public void clear_cache() throws IOException {
//ClearIndicesCacheRequest可以应用于一个或多个索引,甚至可以应用于所有索引
ClearIndicesCacheRequest request = new ClearIndicesCacheRequest("person");
ClearIndicesCacheRequest requestMultiple = new ClearIndicesCacheRequest("index1", "index2");
ClearIndicesCacheRequest requestAll = new ClearIndicesCacheRequest();
//可选参数
request.indicesOptions(IndicesOptions.lenientExpandOpen());
request.queryCache(true);
request.fieldDataCache(true);
request.requestCache(true);
request.fields("field1", "field2", "field3");
//同步请求
ClearIndicesCacheResponse clearCacheResponse = client.indices().clearCache(request, RequestOptions.DEFAULT);
//异步请求
client.indices().clearCacheAsync(request, RequestOptions.DEFAULT, new ActionListener<ClearIndicesCacheResponse>() {
@Override
public void onResponse(ClearIndicesCacheResponse clearIndicesCacheResponse) {
}
@Override
public void onFailure(Exception e) {
}
});
//响应
//请求命中的分片总数
int totalShards = clearCacheResponse.getTotalShards();
//成功的分片数
int successfulShards = clearCacheResponse.getSuccessfulShards();
//失败的分片数
int failedShards = clearCacheResponse.getFailedShards();
//如果在一个或多个分片上操作失败,则列出失败列表
DefaultShardOperationFailedException[] failures = clearCacheResponse.getShardFailures();
//默认情况下,如果没有找到索引,将抛出ElasticsearchException:
// try {
// ClearIndicesCacheRequest request1 = new ClearIndicesCacheRequest("does_not_exist");
// client.indices().clearCache(request, RequestOptions.DEFAULT);
// } catch (ElasticsearchException exception) {
// if (exception.status() == RestStatus.NOT_FOUND) {
//
// }
// }
}
9.14、Force Merge API
@Test
public void force_merge() throws IOException {
//forcergerequest可以应用于一个或多个索引,甚至可以应用于所有索引
ForceMergeRequest request = new ForceMergeRequest("index1");
ForceMergeRequest requestMultiple = new ForceMergeRequest("index1", "index2");
ForceMergeRequest requestAll = new ForceMergeRequest();
//可选参数
request.indicesOptions(IndicesOptions.lenientExpandOpen());
request.maxNumSegments(1);
request.onlyExpungeDeletes(true);
request.flush(true);
//同步请求
ForceMergeResponse forceMergeResponse = client.indices().forcemerge(request, RequestOptions.DEFAULT);
//异步请求
client.indices().forcemergeAsync(request, RequestOptions.DEFAULT, new ActionListener<ForceMergeResponse>() {
@Override
public void onResponse(ForceMergeResponse forceMergeResponse) {
}
@Override
public void onFailure(Exception e) {
}
});
//响应
//命中的分片总数
int totalShards = forceMergeResponse.getTotalShards();
//成功的分片数
int successfulShards = forceMergeResponse.getSuccessfulShards();
//失败的分片数
int failedShards = forceMergeResponse.getFailedShards();
//如果在一个或多个分片上操作失败,则列出失败列表
DefaultShardOperationFailedException[] failures = forceMergeResponse.getShardFailures();
//默认情况下,如果没有找到索引,将抛出ElasticsearchException
// try {
// ForceMergeRequest request1 = new ForceMergeRequest("does_not_exist");
// client.indices().forcemerge(request, RequestOptions.DEFAULT);
// } catch (ElasticsearchException exception) {
// if (exception.status() == RestStatus.NOT_FOUND) {
//
// }
// }
}
9.15、Rollover Index API
@Test
public void rollover() throws IOException {
//RolloverRequest在构造时需要两个字符串参数(别名、新的索引),以及一个或多个决定何时滚转索引的条件
RolloverRequest request = new RolloverRequest("alias", "index-2");
//age
request.addMaxIndexAgeCondition(new TimeValue(7, TimeUnit.DAYS));
//docs
request.addMaxIndexDocsCondition(1000);
//size
request.addMaxIndexSizeCondition(new ByteSizeValue(5, ByteSizeUnit.GB));
//可选参数
request.dryRun(true);
request.timeout(TimeValue.timeValueMinutes(2));
request.masterNodeTimeout(TimeValue.timeValueMinutes(1));
request.getCreateIndexRequest().waitForActiveShards(ActiveShardCount.from(2));
request.getCreateIndexRequest().waitForActiveShards(ActiveShardCount.DEFAULT);
request.getCreateIndexRequest().settings(Settings.builder()
.put("index.number_of_shards", 4));
String mappings = "{\"properties\":{\"field-1\":{\"type\":\"keyword\"}}}";
request.getCreateIndexRequest().mapping(mappings, XContentType.JSON);
request.getCreateIndexRequest().alias(new Alias("another_alias"));
//同步请求
RolloverResponse rolloverResponse = client.indices().rollover(request, RequestOptions.DEFAULT);
//异步请求
client.indices().rolloverAsync(request, RequestOptions.DEFAULT, new ActionListener<RolloverResponse>() {
@Override
public void onResponse(RolloverResponse rolloverResponse) {
}
@Override
public void onFailure(Exception e) {
}
});
//响应
//是否所有节点都已确认请求
boolean acknowledged = rolloverResponse.isAcknowledged();
//索引中每个分片在超时前是否启动了所需数量的分片拷贝
boolean shardsAcked = rolloverResponse.isShardsAcknowledged();
String oldIndex = rolloverResponse.getOldIndex();
String newIndex = rolloverResponse.getNewIndex();
boolean isRolledOver = rolloverResponse.isRolledOver();
boolean isDryRun = rolloverResponse.isDryRun();
Map<String, Boolean> conditionStatus = rolloverResponse.getConditionStatus();
}
9.16、Put Mapping API
@Test
public void put_mapping() throws IOException {
PutMappingRequest request = new PutMappingRequest("twitter");
//提供mapping的源
//方式一:
request.source(
"{\n" +
" \"properties\": {\n" +
" \"message\": {\n" +
" \"type\": \"text\"\n" +
" }\n" +
" }\n" +
"}",
XContentType.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 builder = XContentFactory.jsonBuilder();
builder.startObject();
{
builder.startObject("properties");
{
builder.startObject("message");
{
builder.field("type", "text");
}
builder.endObject();
}
builder.endObject();
}
builder.endObject();
request.source(builder);
//可选参数
request.setTimeout(TimeValue.timeValueMinutes(2));
request.setMasterTimeout(TimeValue.timeValueMinutes(1));
//同步请求
AcknowledgedResponse putMappingResponse = client.indices().putMapping(request, RequestOptions.DEFAULT);
//异步请求
client.indices().putMappingAsync(request, RequestOptions.DEFAULT, new ActionListener<AcknowledgedResponse>() {
@Override
public void onResponse(AcknowledgedResponse acknowledgedResponse) {
}
@Override
public void onFailure(Exception e) {
}
});
//响应
boolean acknowledged = putMappingResponse.isAcknowledged();
System.out.println(acknowledged);
}
9.17、Get Mappings API
@Test
public void get_mappings() throws IOException {
GetMappingsRequest request = new GetMappingsRequest();
request.indices("twitter");
//可选参数
request.setMasterTimeout(TimeValue.timeValueMinutes(1));
request.indicesOptions(IndicesOptions.lenientExpandOpen());
//同步请求
GetMappingsResponse getMappingResponse = client.indices().getMapping(request, RequestOptions.DEFAULT);
//异步请求
client.indices().getMappingAsync(request, RequestOptions.DEFAULT, new ActionListener<GetMappingsResponse>() {
@Override
public void onResponse(GetMappingsResponse getMappingsResponse) {
}
@Override
public void onFailure(Exception e) {
}
});
//响应
Map<String, MappingMetadata> allMappings = getMappingResponse.mappings();
MappingMetadata indexMapping = allMappings.get("twitter");
Map<String, Object> mapping = indexMapping.sourceAsMap();
System.out.println(mapping);
//{properties={message={type=text}}}
}
9.18、Get Field Mappings API
@Test
public void get_field_mappings() throws IOException {
GetFieldMappingsRequest request = new GetFieldMappingsRequest();
request.indices("twitter");
request.fields("message", "timestamp");
//可选参数
request.indicesOptions(IndicesOptions.lenientExpandOpen());
request.local(true);
//同步请求
GetFieldMappingsResponse response = client.indices().getFieldMapping(request, RequestOptions.DEFAULT);
//异步请求
client.indices().getFieldMappingAsync(request, RequestOptions.DEFAULT, new ActionListener<GetFieldMappingsResponse>() {
@Override
public void onResponse(GetFieldMappingsResponse getFieldMappingsResponse) {
}
@Override
public void onFailure(Exception e) {
}
});
//响应
//返回所有请求的索引字段的映射
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();
System.out.println(source);
//{message={type=text}}
}
9.19、Index Aliases API
Index Aliases API允许使用名称对索引进行别名,所有API都会自动将别名转换为实际索引名称。
@Test
public void index_aliases() throws IOException {
//IndicesAliasesRequest必须至少有一个AliasActions
IndicesAliasesRequest request = new IndicesAliasesRequest();
//别名alias1指向index1
IndicesAliasesRequest.AliasActions aliasAction =
new IndicesAliasesRequest.AliasActions(IndicesAliasesRequest.AliasActions.Type.ADD)
.index("person")
.alias("p");
request.addAliasAction(aliasAction);
//支持以下操作类型:
//add:添加别名
//remove:删除别名
//remove_index:删除索引。
IndicesAliasesRequest.AliasActions addIndexAction =
new IndicesAliasesRequest.AliasActions(IndicesAliasesRequest.AliasActions.Type.ADD)
.index("index1")
.alias("alias1")
.filter("{\"term\":{\"year\":2016}}");//过滤器
IndicesAliasesRequest.AliasActions addIndicesAction =
new IndicesAliasesRequest.AliasActions(IndicesAliasesRequest.AliasActions.Type.ADD)
.indices("index1", "index2")
.alias("alias2")
.routing("1");//路由
IndicesAliasesRequest.AliasActions removeAction =
new IndicesAliasesRequest.AliasActions(IndicesAliasesRequest.AliasActions.Type.REMOVE)
.index("index3")
.alias("alias3");
IndicesAliasesRequest.AliasActions removeIndexAction =
new IndicesAliasesRequest.AliasActions(IndicesAliasesRequest.AliasActions.Type.REMOVE_INDEX)
.index("index4");
//可选参数
request.timeout(TimeValue.timeValueMinutes(2));
request.timeout("2m");
request.masterNodeTimeout(TimeValue.timeValueMinutes(1));
request.masterNodeTimeout("1m");
//同步请求
AcknowledgedResponse indicesAliasesResponse =
client.indices().updateAliases(request, RequestOptions.DEFAULT);
//异步请求
client.indices().updateAliasesAsync(request, RequestOptions.DEFAULT, new ActionListener<AcknowledgedResponse>() {
@Override
public void onResponse(AcknowledgedResponse acknowledgedResponse) {
}
@Override
public void onFailure(Exception e) {
}
});
//响应
boolean acknowledged = indicesAliasesResponse.isAcknowledged();
System.out.println(acknowledged);
}
9.20、Delete Alias API
@Test
public void delete_alias() throws IOException {
//DeleteAliasRequest需要一个索引和一个别名参数
DeleteAliasRequest request = new DeleteAliasRequest("person", "p");
//可选参数
request.setTimeout(TimeValue.timeValueMinutes(2));
request.setMasterTimeout(TimeValue.timeValueMinutes(1));
//同步请求
org.elasticsearch.client.core.AcknowledgedResponse deleteAliasResponse = client.indices().deleteAlias(request, RequestOptions.DEFAULT);
//异步请求
client.indices().deleteAliasAsync(request, RequestOptions.DEFAULT, new ActionListener<org.elasticsearch.client.core.AcknowledgedResponse>() {
@Override
public void onResponse(org.elasticsearch.client.core.AcknowledgedResponse acknowledgedResponse) {
}
@Override
public void onFailure(Exception e) {
}
});
//响应
boolean acknowledged = deleteAliasResponse.isAcknowledged();
System.out.println(acknowledged);
}
9.21、Exists Alias API
@Test
public void exists_alias() throws IOException {
//Exists 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");
request.indicesOptions(IndicesOptions.lenientExpandOpen());
request.local(true);
//同步请求
boolean exists = client.indices().existsAlias(request, RequestOptions.DEFAULT);
//异步请求
client.indices().existsAliasAsync(request, RequestOptions.DEFAULT, new ActionListener<Boolean>() {
@Override
public void onResponse(Boolean aBoolean) {
}
@Override
public void onFailure(Exception e) {
}
});
//响应
System.out.println(exists);
}
9.22、Get Alias API
@Test
public void get_alisa() throws IOException {
//获取别名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");
request.indicesOptions(IndicesOptions.lenientExpandOpen());
request.local(true);
//同步请求
GetAliasesResponse response = client.indices().getAlias(request, RequestOptions.DEFAULT);
//异步请求
client.indices().getAliasAsync(request, RequestOptions.DEFAULT, new ActionListener<GetAliasesResponse>() {
@Override
public void onResponse(GetAliasesResponse getAliasesResponse) {
}
@Override
public void onFailure(Exception e) {
}
});
//响应
Map<String, Set<AliasMetadata>> aliases = response.getAliases();
}
9.23、Update Indices Settings API
@Test
public void update_indices_settings() throws IOException {
UpdateSettingsRequest request = new UpdateSettingsRequest("index1");
UpdateSettingsRequest requestMultiple = new UpdateSettingsRequest("index1", "index2");
UpdateSettingsRequest requestAll = new UpdateSettingsRequest();
//settings
//第一种方式:
String settingKey = "index.number_of_replicas";
int settingValue = 0;
Settings settings = Settings.builder()
.put(settingKey, settingValue)
.build();
//第二种方式:
Settings.Builder settingsBuilder = Settings.builder()
.put(settingKey, settingValue);
request.settings(settingsBuilder);
//第三种方式:
request.settings(
"{\"index.number_of_replicas\": \"2\"}"
, XContentType.JSON);
//第四种方式:
Map<String, Object> map = new HashMap<>();
map.put(settingKey, settingValue);
request.settings(map);
//可选参数
request.setPreserveExisting(false);
request.timeout(TimeValue.timeValueMinutes(2));
request.timeout("2m");
request.masterNodeTimeout(TimeValue.timeValueMinutes(1));
request.masterNodeTimeout("1m");
request.indicesOptions(IndicesOptions.lenientExpandOpen());
//同步请求
AcknowledgedResponse updateSettingsResponse = client.indices().putSettings(request, RequestOptions.DEFAULT);
//异步请求
client.indices().putSettingsAsync(request, RequestOptions.DEFAULT, new ActionListener<AcknowledgedResponse>() {
@Override
public void onResponse(AcknowledgedResponse acknowledgedResponse) {
}
@Override
public void onFailure(Exception e) {
}
});
//响应
boolean acknowledged = updateSettingsResponse.isAcknowledged();
System.out.println(acknowledged);
}
9.24、Get Settings API
@Test
public void get_settings() throws IOException {
GetSettingsRequest request = new GetSettingsRequest().indices("person");
//可选参数
request.names("index.number_of_shards");
request.includeDefaults(true);
request.indicesOptions(IndicesOptions.lenientExpandOpen());
//同步请求
GetSettingsResponse getSettingsResponse = client.indices().getSettings(request, RequestOptions.DEFAULT);
//异步请求
client.indices().getSettingsAsync(request, RequestOptions.DEFAULT, new ActionListener<GetSettingsResponse>() {
@Override
public void onResponse(GetSettingsResponse getSettingsResponse) {
}
@Override
public void onFailure(Exception e) {
}
});
//响应
//可以直接从响应中以字符串的形式检索特定索引的设置值
String numberOfShardsString = getSettingsResponse.getSetting("person", "index.number_of_shards");
//可以检索特定索引的Settings对象,以便进一步检查
Settings indexSettings = getSettingsResponse.getIndexToSettings().get("person");
//返回的Settings对象为非String类型提供了方便的方法
Integer numberOfShards = indexSettings.getAsInt("index.number_of_shards", null);
System.out.println(numberOfShards);
}
9.25、Put Template API
@Test
public void put_template() throws IOException {
//PutIndexTemplateRequest指定模板和模式的名称,这些模式控制模板是否应该应用于新索引。
PutIndexTemplateRequest request = new PutIndexTemplateRequest("my-template");
request.patterns(Arrays.asList("pattern-1", "log-*"));
//settings
request.settings(Settings.builder()
.put("index.number_of_shards", 3)
.put("index.number_of_replicas", 1)
);
//mappings
request.mapping(
"{\n" +
" \"properties\": {\n" +
" \"message\": {\n" +
" \"type\": \"text\"\n" +
" }\n" +
" }\n" +
"}",
XContentType.JSON);
//aliases
request.alias(new Alias("twitter_alias").filter(QueryBuilders.termQuery("user", "kimchy")));
request.alias(new Alias("{index}_alias").searchRouting("xyz"));
//order
request.order(20);
//version
request.version(4);
//或者直接提供整个请求体
request.source("{\n" +
" \"index_patterns\": [\n" +
" \"log-*\",\n" +
" \"pattern-1\"\n" +
" ],\n" +
" \"order\": 1,\n" +
" \"settings\": {\n" +
" \"number_of_shards\": 1\n" +
" },\n" +
" \"mappings\": {\n" +
" \"properties\": {\n" +
" \"message\": {\n" +
" \"type\": \"text\"\n" +
" }\n" +
" }\n" +
" },\n" +
" \"aliases\": {\n" +
" \"alias-1\": {},\n" +
" \"{index}-alias\": {}\n" +
" }\n" +
"}", XContentType.JSON);
//可选参数
request.create(true);
request.masterNodeTimeout(TimeValue.timeValueMinutes(1));
request.masterNodeTimeout("1m");
//同步请求
AcknowledgedResponse putTemplateResponse = client.indices().putTemplate(request, RequestOptions.DEFAULT);
//异步请求
client.indices().putTemplateAsync(request, RequestOptions.DEFAULT, new ActionListener<AcknowledgedResponse>() {
@Override
public void onResponse(AcknowledgedResponse acknowledgedResponse) {
}
@Override
public void onFailure(Exception e) {
}
});
//响应
boolean acknowledged = putTemplateResponse.isAcknowledged();
System.out.println(acknowledged);
}
9.26、Validate Query API
@Test
public void validate_query() throws IOException {
//ValidateQueryRequest需要对查询进行验证的一个或多个索引。如果没有提供索引,则在所有索引上执行请求。
ValidateQueryRequest request = new ValidateQueryRequest("bank");
//添加请求
QueryBuilder builder = QueryBuilders
.boolQuery()
.must(QueryBuilders.queryStringQuery("*:*"))
.filter(QueryBuilders.termQuery("user", "kimchy"));
request.query(builder);
//可选参数
request.explain(true);
request.allShards(true);
request.rewrite(true);
//同步请求
ValidateQueryResponse response = client.indices().validateQuery(request, RequestOptions.DEFAULT);
//异步请求
client.indices().validateQueryAsync(request, RequestOptions.DEFAULT, new ActionListener<ValidateQueryResponse>() {
@Override
public void onResponse(ValidateQueryResponse validateQueryResponse) {
}
@Override
public void onFailure(Exception e) {
}
});
//响应
boolean isValid = response.isValid();
int totalShards = response.getTotalShards();
int successfulShards = response.getSuccessfulShards();
int failedShards = response.getFailedShards();
if (failedShards > 0) {
for(DefaultShardOperationFailedException failure: response.getShardFailures()) {
String failedIndex = failure.index();
int shardId = failure.shardId();
String reason = failure.reason();
}
}
for(QueryExplanation explanation: response.getQueryExplanation()) {
String explanationIndex = explanation.getIndex();
int shardId = explanation.getShard();
String explanationString = explanation.getExplanation();
}
}
9.27、Get Templates API
@Test
public void get_template() throws IOException {
GetIndexTemplatesRequest request = new GetIndexTemplatesRequest("my-template");
request = new GetIndexTemplatesRequest("template-1", "template-2");
request = new GetIndexTemplatesRequest("my-*");
//可选参数
request.setMasterNodeTimeout(TimeValue.timeValueMinutes(1));
request.setMasterNodeTimeout("1m");
//同步请求
GetIndexTemplatesResponse getTemplatesResponse = client.indices().getIndexTemplate(request, RequestOptions.DEFAULT);
//异步请求
client.indices().getIndexTemplateAsync(request, RequestOptions.DEFAULT, new ActionListener<GetIndexTemplatesResponse>() {
@Override
public void onResponse(GetIndexTemplatesResponse getIndexTemplatesResponse) {
}
@Override
public void onFailure(Exception e) {
}
});
//响应
List<IndexTemplateMetadata> templates = getTemplatesResponse.getIndexTemplates();
for (IndexTemplateMetadata metadata : templates) {
System.out.println(metadata.toString());
}
}
9.28、Templates Exist API
@Test
public void templates_exist() throws IOException {
IndexTemplatesExistRequest request;
request = new IndexTemplatesExistRequest("my-template");
request = new IndexTemplatesExistRequest("template-1", "template-2");
request = new IndexTemplatesExistRequest("my-*");
//可选参数
request.setLocal(true);
request.setMasterNodeTimeout(TimeValue.timeValueMinutes(1));
request.setMasterNodeTimeout("1m");
//同步请求
boolean exists = client.indices().existsTemplate(request, RequestOptions.DEFAULT);
//异步请求
client.indices().existsTemplateAsync(request, RequestOptions.DEFAULT, new ActionListener<Boolean>() {
@Override
public void onResponse(Boolean aBoolean) {
}
@Override
public void onFailure(Exception e) {
}
});
//响应
System.out.println(exists);
}
9.29、Get Index API
@Test
public void get_index() throws IOException {
GetIndexRequest request = new GetIndexRequest("person");
//可选参数
request.includeDefaults(true);
request.indicesOptions(IndicesOptions.lenientExpandOpen());
//同步请求
GetIndexResponse getIndexResponse = client.indices().get(request, RequestOptions.DEFAULT);
//异步请求
client.indices().getAsync(request, RequestOptions.DEFAULT, new ActionListener<GetIndexResponse>() {
@Override
public void onResponse(GetIndexResponse getIndexResponse) {
}
@Override
public void onFailure(Exception e) {
}
});
//响应
//person的mapping设置
MappingMetadata indexMappings = getIndexResponse.getMappings().get("person");
Map<String, Object> indexTypeMappings = indexMappings.getSourceAsMap();
//person的别名设置
List<AliasMetadata> indexAliases = getIndexResponse.getAliases().get("person");
//person分片数
String numberOfShardsString = getIndexResponse.getSetting("person", "index.number_of_shards");
//index的settings设置
Settings indexSettings = getIndexResponse.getSettings().get("person");
Integer numberOfShards = indexSettings.getAsInt("index.number_of_shards", null);
TimeValue time = getIndexResponse.getDefaultSettings().get("person")
.getAsTime("index.refresh_interval", null);
}
9.30、Freeze Index API
@Test
public void freeze_index() throws IOException {
FreezeIndexRequest request = new FreezeIndexRequest("person");
//可选参数
request.setTimeout(TimeValue.timeValueMinutes(2));
request.setMasterTimeout(TimeValue.timeValueMinutes(1));
request.setWaitForActiveShards(ActiveShardCount.DEFAULT);
request.setIndicesOptions(IndicesOptions.strictExpandOpen());
//同步请求
ShardsAcknowledgedResponse openIndexResponse = client.indices().freeze(request, RequestOptions.DEFAULT);
//异步请求
client.indices().freezeAsync(request, RequestOptions.DEFAULT, new ActionListener<ShardsAcknowledgedResponse>() {
@Override
public void onResponse(ShardsAcknowledgedResponse shardsAcknowledgedResponse) {
}
@Override
public void onFailure(Exception e) {
}
});
//响应
boolean acknowledged = openIndexResponse.isAcknowledged();
boolean shardsAcked = openIndexResponse.isShardsAcknowledged();
System.out.println(acknowledged);
System.out.println(shardsAcked);
}
9.31、Unfreeze Index API
@Test
public void unfreeze_inex() throws IOException {
UnfreezeIndexRequest request = new UnfreezeIndexRequest("person");
//可选参数
request.setTimeout(TimeValue.timeValueMinutes(2));
request.setMasterTimeout(TimeValue.timeValueMinutes(1));
request.setWaitForActiveShards(ActiveShardCount.DEFAULT);
request.setIndicesOptions(IndicesOptions.strictExpandOpen());
//同步请求
ShardsAcknowledgedResponse openIndexResponse = client.indices().unfreeze(request, RequestOptions.DEFAULT);
//异步请求
client.indices().unfreezeAsync(request, RequestOptions.DEFAULT, new ActionListener<ShardsAcknowledgedResponse>() {
@Override
public void onResponse(ShardsAcknowledgedResponse shardsAcknowledgedResponse) {
}
@Override
public void onFailure(Exception e) {
}
});
//响应
boolean acknowledged = openIndexResponse.isAcknowledged();
boolean shardsAcked = openIndexResponse.isShardsAcknowledged();
System.out.println(acknowledged);
System.out.println(shardsAcked);
}
9.32、Delete Template API
@Test
public void delete_template() throws IOException {
DeleteIndexTemplateRequest request = new DeleteIndexTemplateRequest();
request.name("my-template");
//同步请求
AcknowledgedResponse deleteTemplateAcknowledge = client.indices().deleteTemplate(request, RequestOptions.DEFAULT);
//异步请求
client.indices().deleteTemplateAsync(request, RequestOptions.DEFAULT, new ActionListener<AcknowledgedResponse>() {
@Override
public void onResponse(AcknowledgedResponse acknowledgedResponse) {
}
@Override
public void onFailure(Exception e) {
}
});
//响应
boolean acknowledged = deleteTemplateAcknowledge.isAcknowledged();
System.out.println(acknowledged);
}
9.33、Reload Search Analyzers API
@Test
public void reload_serach_analyzers() throws IOException {
ReloadAnalyzersRequest request = new ReloadAnalyzersRequest("person");
//可选参数
request.setIndicesOptions(IndicesOptions.strictExpandOpen());
//同步请求
ReloadAnalyzersResponse reloadResponse = client.indices().reloadAnalyzers(request, RequestOptions.DEFAULT);
//异步请求
client.indices().reloadAnalyzersAsync(request, RequestOptions.DEFAULT, new ActionListener<ReloadAnalyzersResponse>() {
@Override
public void onResponse(ReloadAnalyzersResponse reloadAnalyzersResponse) {
}
@Override
public void onFailure(Exception e) {
}
});
//响应
//碎片的统计数据。请注意,重新加载不是发生在索引的每个分片上,而是发生在索引上有分片的每个节点上。因此,报告的碎片计数可能与索引碎片的数量不同
BroadcastResponse.Shards shards = reloadResponse.shards();
//重新加载执行请求的所有索引的详细信息
Map<String, ReloadAnalyzersResponse.ReloadDetails> reloadDetails = reloadResponse.getReloadedDetails();
//可以通过索引名称检索详细信息
ReloadAnalyzersResponse.ReloadDetails details = reloadDetails.get("index");
//重新加载的索引名
String indexName = details.getIndexName();
//重新加载索引的节点
Set<String> indicesNodes = details.getReloadedIndicesNodes();
//重新加载的分析器名称
Set<String> analyzers = details.getReloadedAnalyzers();
}
9.34、Get Composable Index Templates API
Get Index Templates API允许检索一个或多个索引模板的信息。
@Test
public void get_composable_index_templates() throws IOException {
//GetComposableIndexTemplateRequest需要指定一个,或要获取的索引模板名称的通配符表达式。若要返回所有索引模板,请完全省略名称或使用值*。
GetComposableIndexTemplateRequest request = new GetComposableIndexTemplateRequest("my-template");
request = new GetComposableIndexTemplateRequest("my-*");
//可选参数
request.setMasterNodeTimeout(TimeValue.timeValueMinutes(1));
request.setMasterNodeTimeout("1m");
//同步请求
GetComposableIndexTemplatesResponse getTemplatesResponse = client.indices().getIndexTemplate(request, RequestOptions.DEFAULT);
//异步请求
client.indices().getIndexTemplateAsync(request, RequestOptions.DEFAULT, new ActionListener<GetComposableIndexTemplatesResponse>() {
@Override
public void onResponse(GetComposableIndexTemplatesResponse getComposableIndexTemplatesResponse) {
}
@Override
public void onFailure(Exception e) {
}
});
//响应
Map<String, ComposableIndexTemplate> templates = getTemplatesResponse.getIndexTemplates();
ComposableIndexTemplate composableIndexTemplate = templates.get("my-template");
System.out.println(composableIndexTemplate.toString());
}
9.35、Put Composable Index Template API
@Test
public void put_composable_index_template() throws IOException {
//PutComposableIndexTemplateRequest指定模板的名称和索引模板配置,
//其中包括控制模板是否应应用于新索引的模式,以及可选的映射、设置和别名配置。
PutComposableIndexTemplateRequest request = new PutComposableIndexTemplateRequest()
.name("my-template");
//创建一个组件模板,指定此模板将匹配的索引名称模式的索引模板配置
ComposableIndexTemplate composableIndexTemplate = new ComposableIndexTemplate(Arrays.asList("pattern-1", "log-*"), null, null, null, null, null);
request.indexTemplate(composableIndexTemplate);
//settings
PutComposableIndexTemplateRequest request1 = new PutComposableIndexTemplateRequest()
.name("my-template");
Settings settings = Settings.builder()
.put("index.number_of_shards", 3)
.put("index.number_of_replicas", 1)
.build();
Template template1 = new Template(settings, null, null);
ComposableIndexTemplate composableIndexTemplate1 = new ComposableIndexTemplate(Arrays.asList("pattern-1", "log-*"),
template1, null, null, null, null);
request1.indexTemplate(composableIndexTemplate);
//mappings
String mappingJson = "{\n" +
" \"properties\": {\n" +
" \"message\": {\n" +
" \"type\": \"text\"\n" +
" }\n" +
" }\n" +
"}";
PutComposableIndexTemplateRequest request2 = new PutComposableIndexTemplateRequest()
.name("my-template");
Template template2 = new Template(null, new CompressedXContent(mappingJson), null);
ComposableIndexTemplate composableIndexTemplate2 = new ComposableIndexTemplate(Arrays.asList("pattern-1", "log-*"),
template2, null, null, null, null);
request2.indexTemplate(composableIndexTemplate);
//aliases
PutComposableIndexTemplateRequest request3 = new PutComposableIndexTemplateRequest()
.name("my-template");
AliasMetadata twitterAlias3 = AliasMetadata.builder("twitter_alias").build();
AliasMetadata placeholderAlias3 = AliasMetadata.builder("{index}_alias").searchRouting("xyz").build();
Map<String, AliasMetadata> aliases3 = new HashMap<>();
aliases3.put("twitter_alias", twitterAlias3);
aliases3.put("{index}_alias", placeholderAlias3);
Template template3 = new Template(null, null, aliases3);
ComposableIndexTemplate composableIndexTemplate3 = new ComposableIndexTemplate(Arrays.asList("pattern-1", "log-*"),
template3, null, null, null, null);
request3.indexTemplate(composableIndexTemplate);
//组件模板可以用作指定映射、设置或别名配置的构建块,但它们不适用于索引本身。
//要应用于索引,组件模板必须在IndexTemplateV2索引模板定义对象的componentTemplates列表中指定。
//它们在列表中指定的顺序就是应用组件模板的顺序。
PutComposableIndexTemplateRequest request4 = new PutComposableIndexTemplateRequest()
.name("my-template");
ComposableIndexTemplate composableIndexTemplate4 =
new ComposableIndexTemplate(Arrays.asList("pattern-1", "log-*"), null,
Collections.singletonList("ct1"), null, null, null);
request4.indexTemplate(composableIndexTemplate);
//当多个模板匹配一个索引时,匹配模板的优先级决定将应用哪个索引模板。
//优先级高的索引模板“胜过”优先级低的索引模板。
PutComposableIndexTemplateRequest request5 = new PutComposableIndexTemplateRequest()
.name("my-template");
ComposableIndexTemplate composableIndexTemplate5 = new ComposableIndexTemplate(Arrays.asList("pattern-1", "log-*"),
null, null, 20L, null, null);
request5.indexTemplate(composableIndexTemplate);
//version
//模板可以选择指定版本号,该版本号可用于简化外部系统对模板的管理。
PutComposableIndexTemplateRequest request6 = new PutComposableIndexTemplateRequest()
.name("my-template");
ComposableIndexTemplate composableIndexTemplate6 = new ComposableIndexTemplate(Arrays.asList("pattern-1", "log-*"),
null, null, null, 3L, null);
request6.indexTemplate(composableIndexTemplate);
//可选参数
request.create(true);
request.setMasterTimeout(TimeValue.timeValueMinutes(1));
//同步请求
AcknowledgedResponse putTemplateResponse = client.indices().putIndexTemplate(request, RequestOptions.DEFAULT);
//异步请求
client.indices().putIndexTemplateAsync(request, RequestOptions.DEFAULT, new ActionListener<AcknowledgedResponse>() {
@Override
public void onResponse(AcknowledgedResponse acknowledgedResponse) {
}
@Override
public void onFailure(Exception e) {
}
});
//响应
boolean acknowledged = putTemplateResponse.isAcknowledged();
System.out.println(acknowledged);
}
9.36、Delete Composable Index Template API
@Test
public void delete_composable_index_template() throws IOException {
DeleteComposableIndexTemplateRequest deleteRequest = new DeleteComposableIndexTemplateRequest("my-template");
//同步请求
AcknowledgedResponse acknowledgedResponse = client.indices().deleteIndexTemplate(deleteRequest, RequestOptions.DEFAULT);
//异步提交
client.indices().deleteIndexTemplateAsync(deleteRequest, RequestOptions.DEFAULT, new ActionListener<AcknowledgedResponse>() {
@Override
public void onResponse(AcknowledgedResponse acknowledgedResponse) {
}
@Override
public void onFailure(Exception e) {
}
});
//响应
boolean acknowledged = acknowledgedResponse.isAcknowledged();
System.out.println(acknowledged);
}