You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

使用Java High Level Rest Client创建ES索引遇方法弃用问题求助

嘿,我来帮你理清这个问题!首先得纠正一个小误区:你当前用的IndexRequest其实是用来向索引写入文档的,而非专门创建空索引的API——当然,如果目标索引不存在,ES默认会自动帮你创建它,但这是自动生成的默认配置,可能不符合你的实际需求。另外你提到的client.index()方法弃用,是因为新版ES High Level Client要求所有请求都必须传入RequestOptions参数啦。

下面分两种场景给你解决方案:

场景1:手动创建带自定义配置的索引

如果你想主动创建一个索引,并配置自己的mapping、settings(这是生产环境更推荐的方式),应该用CreateIndexRequest

@GetMapping("/createIndex")
public boolean createIndex() throws IOException {
    // 初始化创建索引的请求,指定索引名muviuser
    CreateIndexRequest request = new CreateIndexRequest("muviuser");
    
    // 自定义索引的mapping,根据你的文档结构定义字段类型
    String customMapping = "{\n" +
            "  \"mappings\": {\n" +
            "    \"properties\": {\n" +
            "      \"user\": {\"type\": \"text\"},\n" +
            "      \"postDate\": {\"type\": \"date\"},\n" +
            "      \"message\": {\"type\": \"text\"}\n" +
            "    }\n" +
            "  }\n" +
            "}";
    request.source(customMapping, XContentType.JSON);
    
    // 执行创建请求,必须传入RequestOptions(用DEFAULT即可,也可以自定义配置)
    CreateIndexResponse response = client.indices().create(request, RequestOptions.DEFAULT);
    
    // 返回索引是否创建成功
    return response.isAcknowledged();
}

场景2:写入文档时自动创建索引

如果你只是想写入文档,同时让ES自动创建索引(适合测试场景),只需要修正弃用的index方法调用,加上RequestOptions.DEFAULT参数即可:

@GetMapping("/createIndex")
public boolean createIndex() throws IOException {
    IndexRequest request = new IndexRequest("muviuser", "user", "1");
    String jsonString = "{" +
            "\"user\":\"Bran\"," +
            "\"postDate\":\"2018-01-30\"," +
            "\"message\":\"trying out Elasticsearch\"" +
            "}";
    request.source(jsonString, XContentType.JSON);
    
    // 替换弃用的index方法,传入RequestOptions参数
    IndexResponse response = client.index(request, RequestOptions.DEFAULT);
    
    // 判断文档是否成功写入(索引不存在时会自动创建)
    return RestStatus.CREATED.equals(response.status());
}

关于方法弃用的原因

ES High Level Client从7.x版本开始,统一要求所有请求都传入RequestOptions,用来配置请求的超时时间、自定义HTTP头、认证信息等,所以原来不带这个参数的index方法就被标记为弃用了,只要加上RequestOptions.DEFAULT就能正常使用啦。

内容的提问来源于stack exchange,提问作者Xwin

火山引擎 最新活动