Elasticsearch7.x——High Level REST Client(三)Index APIs

SpringBoot知识体系(四)springboot整合Elasticsearch(4) suggest的自动补全与IK分词 AnalyzeRequestBuilder实现IK分词 Java代码 // 调用 IK 分词 AnalyzeRequestBuilder requestBuilder= new AnalyzeRequestBuilder(this.esClient,AnalyzeAction.INSTANCE,INDEX_NAME, “title”, ... 阅读详情

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);
}
【信息科学与工程学】计算机科学与自动化 第二百三十三篇 凤凰架构01 编号类型领域系统软件/硬件或系统集成方案及系统架构模块子模块函数名称/算法名称算法的数学分析及计算机体系架构及数据结构与算法详细设计及参数列表及数值范围设计关联知识1共识算法分布式基石状态机复制架构:Proposer/Acceptor/Learner 多节点角色模型,基于操作转移(Operation Transfer)分布式共识PaxosPaxos 协议(Prepare/Promise/Accept/Accepted 两阶段)数学基础:多数派(Quorum)投票,基于鸽巢原理保证 W+R>N 时读写集合必有 阅读详情

相关推荐

系统-等保三级-CentOS Linux 7合规基线检查 shell脚本

系统-等保三级-CentOS Linux 7合规基线检查 shell脚本

swindy博客 2409

Elasticsearch 查询分词结果新方法

Elasticsearch 查询分词结果新方法

xjj1314的专栏 4607

各种AI的调试日记——辅助工作篇

记录使用各种AI(语言大模型)的心得和总结

m0_73056986的博客 1392

5.索引APIS(一)Index APIs

1.Analyze API 分词器API 2. Index 索引API 创建 修改 删除 查找

折剑听雨落 1000

Vector CANoe VT2516A实战:从硬件连接到CAPL脚本的完整配置指南

本文详细介绍了Vector CANoe VT2516A板卡从硬件连接到CAPL脚本编写的完整配置指南。涵盖硬件接线原则、VT System配置避坑技巧、系统变量创建规范、可视化Panel设计、CAPL脚本调试及典型故障排查案例,帮助工程师快速掌握VT2516A板卡的应用实践,提升汽车电子测试效率。

weixin_30608503的博客 255

Python xlwings报错解决:从‘NoneType‘到完美运行WPS表格的完整指南

本文深入解析了使用Python xlwings库自动化WPS表格时遇到的经典'NoneType'报错(AttributeError: 'NoneType' object has no attribute 'apps')的根源与解决方案。核心在于pywin32版本与WPS的兼容性问题,文章提供了从版本降级、依赖管理到构建健壮自动化环境的完整实战指南,帮助开发者彻底解决兼容性难题,实现稳定运行。

n4o5p6q7r的博客 303

一个Json文件让你快速入门 ElasticSearch 7.9.1 API ,速度上手,慢慢了解

如题,ElasticSearch 实际上就是通过Http请求进行增删改查的数据库。 相信看到这篇文章的人都知道它是用来干啥的,但是很难快速入门,网上都是散乱粘贴的博客。 找起来、整合很费事,也不注明大小版本,经常版本不统一。 所以,我整理了一个postman的导出json,可以帮助未入门者,快速学会ES的增删改查、及常用的搜索代码。 使用方法:另存为静态文件,下载个postman,然后import即可,不多说。 静态文件地址:https://anyongliang.oss-cn-beijin...

巴休特的风之剑 378

在Jetson orin板卡上部署ocr模型遇到错误

摘要:安装ONNX Runtime GPU版本时遇到问题,直接pip install onnxruntime-gpu会报错。解决方案是从test.pypi.org下载对应的.whl文件(如ort_nightly-1.14.0...aarch64.whl),本地安装后还需降级NumPy版本(如pip install numpy==1.26),以解决NumPy版本兼容性问题。整个过程涉及三个关键步骤:下载正确架构的wheel文件、本地安装、调整NumPy版本。

xdxd3c的博客 1526

ElasticSearch实战之JAVA操作(六)

Java操作ES 1.1 引入maven依赖 <dependency> <groupId>org.elasticsearch</groupId> <artifactId>elasticsearch</artifactId> <version>6.2.4</version> ...

小陈之JAVA 1027

华为OD机试 - 打印机队列 - 优先队列(Python/JS/C/C++ 双机位C卷 200分)

这个问题要求模拟打印机的文件调度过程,关键在于正确处理每个打印机队列中的文件优先级和文件进入队列的顺序。优先级处理:每个文件有一个 1 到 10 的优先级,数字越大优先级越高,打印机应首先处理优先级最高的文件。在打印机 1 的队列中插入了 3 个文件,分别有不同的优先级,其中编号 3 的文件优先级最高,先被取出。因为打印的文件内容有轻重缓急之分,所以队列中的文件有1~10 不同的 优先级,其中数字越大优先级越高。在打印机 2 的队列中插入了 1 个文件,优先级为 1,因此它被首先取出。

学Java,找哪吒 1079

车载网络测试实操源码_使用CAPL脚本实现安全访问解锁,并模拟各种测试场景

在车载诊断中,我们经常会使用到安全访问解锁,常见的场景包括软件刷写前、通过2E服务写入某个DID前、通过31服务执行某个例程前等,都必须先通过27服务进行安全访问,解锁相应安全等级后才能执行上述操作。在开发调试或测试时,有时候需要模拟正常的安全解锁、安全访问秘钥错误、连续多次请求安全访问等,手动操作极为不便。本文将介绍如何使用CAPL脚本实现安全访问解锁,并模拟各种测试场景。

文章主要涉及嵌入式软件开发、测试、项目管理等,欢迎交流,共同进步。 1201

ElasticSearch 使用Java High Level REST Client API实现搜索功能-笔记

我使用ElasticSearch-7.5.2基于springboot开发。 7.x算是比较新的版本,网上关于es的api更多是transport API的说明。所以在这里记录一下,仅供参考。 Java REST客户端有两种版本: Java Low Level REST Client:Elasticsearch的官方低级客户端。它允许通过http与Elasticsearch集群进行通信。将请求编组和对用户取消编组的响应离开。它与所有Elasticsearch版本兼容。 Java High Level REST

DraGon_HooRay的博客 949

人形机器人硬件电路设计入门

人形机器人属于。

blotemj.blog.youkuaiyun.com 231

Elastic:开发者上手指南

你们好,我是Elastic的刘晓国。如果大家想开始学习Elastic的话,那么这里将是你理想的学习园地。在我的博客几乎涵盖了你想学习的许多方面。在这里,我来讲述一下作为一个菜鸟该如何阅读我的这些博客文章。 我们可以按照如下的步骤来学习: 1)Elasticsearch简介:对Elasticsearch做了一个简单的介绍 2)Elasticsearch中的一些重要概念:cluster,n..........................................................

Elastic 中国社区官方博客 17万+

WINCC7.3破解文件

WINCC7.3硬件够破解文件,有需要的下载!WINCC7.3硬件够破解文件,有需要的下载!

pscad IEEE标准系统搭建说明

pscad IEEE标准系统搭建说明,包含典型的IEEE 9节点、14节点、30节点、39节点和118节点系统。内含标准测试系统的原始数据和潮流结果。

工作中使用到的单词(软件开发)

1.エイリアス   alias 别名 powershell使用 get-help 命令时,会得到与此命令 相关(别名)的命令 2.プロキシ proxy 代 理 3.プロモート   promote 促进,提升   开发的系统新功能上线发布,有时会使用到这个词,比如 STプロモート 还有使用リリース这个词的。比如STリリース。个人认为两者含义相同。 4.見逃し み................................................................

sun0322 6万+

IDEA的使用指南

IDEA基于java的使用手册,可以最快速的上手,在使用中不断的丰富自己的使用技巧.

java es7 RestHighLevelClient 查看ik分词结果 方法

【代码】java es7 RestHighLevelClient 查看ik分词结果 方法。

mengqudoh的博客 755

IEM模型,地表粗糙度模拟

利用微波反演土壤水分时候,利用IEM模型可以实现对随机地表的模拟

elasticsearch获取分词结果

原创于 【模棱博客】ES 中默认配置 IK 后,通过 Rest HTTP 的方式我们可以进行得到分词结果。那么在 Spring Boot 和提供的客户端依赖 spring-data-elasticsearch 中如何获取到分词结果。加入依赖 pom.xmlorg.springframework.bootspring-boot-starter-data-elasticsearch在 applicat...

【模棱博客】 – Java技术博客 9438

ElasticSearch构建分词与自动补全功能

standard analyzer是ElasticSearch自带的分词器,可以看出该分词器对大小写不敏感,你输入大写最后也会被转换成小写。我们举一个很常见的例子:当我们在百度中输入字符时,会有一个下拉列表来给出用户提示,这个功能就是自动补全。1. 目前我们只能通过原生API的方式赖进行分词功能的实现,过程比较繁琐,但编写方式统一。实现自动补全功能,该功能同分词一样,使用的是原生API的方式,过程较繁琐,但比较统一。在发送分词请求的时候会抛出一个异常,这里选择lombok下的。接下来就是分词功能的实现了。

m0_73414953的博客 485

Elasticsearch-RestHighLevelClient基础操作

*** 更新索引结构//你已经创建好的索引名称 PutMappingRequest putMappingRequest = new PutMappingRequest(idx);

会走的鱼 2905

Java操作ElasticSearch

一、环境说明 需要添加下面的maven依赖 <dependencies> <dependency> <groupId>org.elasticsearch</groupId> <artifactId>elasticsearch</artifactId> <version>7.13.4</version> &lt

JAVA领域优秀创作者 1111

java 使用RestHighLevelClient获取ES的所有索引名

工作有个业务需求是需要获取ES中的所有索引名,之前是使用TransportClent去获取,但是ES加密了,而且TransportClient官方也不推荐使用,所以用了RestHighLevelClient去获取。 版本如下: jdk版本:1.8 elasticsearch.client版本:6.4.0 附上代码: 这是获取高级客户端的方法 @Getter @Setter private static RestHighLevelClient restClient = null; pu.

qq_35164294的博客 1万+

Es7.x 获取分词结果

@SpringBootTest class DemoApplicationTests { @Autowired private RestHighLevelClient restHighLevelClient; @Test void contextLoads() throws IOException { String text="xxxxx"; AnalyzeRequest request=AnalyzeRequest.withIndexAnalyzer("mao", "ik-max-w.

大佛拈花的博客 1099

SpringBoot整合ElasticSearch

关于springboot整合elasticSearch操作

weixin_45818966的博客 1237

原生语言操作和spring data中RestHighLevelClient操作Elasticsearch,索引,文档的基本操作,es的高级查询.查询结果处理. 数据聚合.相关性系数打分

​ Elasticsearch 是一个分布式、高扩展、高实时的搜索与数据分析引擎。它能很方便的使大量数据具有搜索、分析和探索的能力。充分利用Elasticsearch的水平伸缩性,能使数据在生产环境变得更有价值。Elasticsearch 的实现原理主要分为以下几个步骤,首先用户将数据提交到Elasticsearch 数据库中,再通过分词控制器去将对应的语句分词,将其权重和分词结果一并存入数据,当用户搜索数据时候,再根据权重将结果排名,打分,再将返回结果呈现给用户。​ RestHighLevelClient

qq_62357662的博客 5223

ElasticSearch学习;RestClient 操作索引库;RestClient 查询文档

docker 中安装 elasticsearch 和 kibana;安装 IK 分词器;正向索引和倒排索引;mapping常见属性有哪些?;索引操作;文档操作;RestClient 操作索引库;RestClient 操作索引;RestClient 操作文档

時間的博客 3500

springboot 操作es 之elasticsearch-rest-high-level-client

springboot 操作es 之elasticsearch-rest-high-level-client

爱钻研的小张 1万+
上一篇: Elasticsearch7.x——High Level REST Client(二)Search/Sync Search APIs
下一篇: Elasticsearch7.x——spring-boot-starter-data-elasticsearch详解
吴声子夜歌
博客等级 码龄9年 2688粉丝 2272原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值