You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用OpenSearch Java Client创建带映射的索引?

使用OpenSearch Java Client设置索引映射

你可以通过mappings()方法为创建的索引配置映射,核心是用TypeMapping.Builder构建字段映射规则,再传入CreateIndexRequest.Builder的mappings()方法中。

以下是完整的代码示例:

import org.opensearch.client.opensearch.indices.CreateIndexRequest;
import org.opensearch.client.opensearch.indices.CreateIndexResponse;
import org.opensearch.client.opensearch._types.mapping.TypeMapping;
import org.opensearch.client.opensearch._types.mapping.TextProperty;
import org.opensearch.client.opensearch._types.mapping.LongProperty;
import org.opensearch.client.transport.rest_client.RestClientTransport;
import org.opensearch.client.json.jackson.JacksonJsonpMapper;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;

public class OpenSearchIndexDemo {
    public static void main(String[] args) throws Exception {
        String host = "localhost";
        int port = 9200;
        String scheme = "http";
        String index = "demo_index";

        RestClient restClient = RestClient
                .builder(new HttpHost(host, port, scheme))
                .build();
        RestClientTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
        OpenSearchClient client = new OpenSearchClient(transport);

        // 构建字段映射规则
        TypeMapping indexMappings = new TypeMapping.Builder()
                // 文本类型字段
                .properties("article_title", new TextProperty.Builder().build())
                .properties("article_content", new TextProperty.Builder().build())
                // 长整型字段
                .properties("publish_timestamp", new LongProperty.Builder().build())
                .build();

        CreateIndexRequest createIndexRequest = new CreateIndexRequest.Builder()
                .index(index)
                .mappings(indexMappings) // 绑定映射到索引请求
                .build();

        CreateIndexResponse response = client.indices().create(createIndexRequest);
        System.out.println("索引创建状态: " + response.acknowledged());
    }
}

核心细节说明

  • 不同字段类型对应不同的Property实现类:文本字段用TextProperty、数值字段用LongProperty/DoubleProperty、布尔字段用BooleanProperty等,按需选择即可。
  • 若需配置复杂映射(如分词器、字段权重、是否索引等),可在对应Property的Builder中添加配置,示例如下:
// 为标题字段指定分词器和搜索分词器
.properties("article_title", new TextProperty.Builder()
        .analyzer("ik_max_word")
        .searchAnalyzer("ik_smart")
        .build())

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 04:55:28