【ElasticSearch】索引(添加)

翠微 / 2023-06-17 / 原文

【ElasticSearch】索引(添加)

REST API,settings 中的 index 可以不要

PUT /myindex
{
  "settings": {
    "index": {
      "number_of_shards": 3,
      "number_of_replicas": 3
    }
  },
  "mappings": {
    "properties": {
      "name": {
        "type": "keyword"
      },
      "age": {
        "type": "integer"
      },
      "title": {
        "type": "text",
        "fields": {
          "raw": {
            "type": "keyword"
          }
        }
      }
    }
  },
  "aliases": {
    "myindex_alias": {}
  }
}

Java REST Client

CreateIndexRequest request = new CreateIndexRequest("myindex");
// 设置
Settings.Builder settings = Settings.builder()
    .put("index.number_of_shards", 3)
    .put("index.number_of_replicas", 3);
request.settings(elasticsearchIndexRequest.getSettings());
// 别名
request.alias(new Alias("myindex_alias"));
// 映射
Map<String, Object> name = new HashMap<>();
name.put("type", "keyword");
Map<String, Object> age = new HashMap<>();
age.put("type", "integer");
Map<String, Object> raw = new HashMap<>();
raw.put("type", "keyword");
Map<String, Object> fields = new HashMap<>();
fields.put("raw", raw);
Map<String, Object> title = new HashMap<>();
title.put("type", "text");
title.put("fields", "fields");
Map<String, Object> properties = new HashMap<>();
properties.put("name", name);
properties.put("age", age);
properties.put("title", title);
Map<String, Object> mapping = new HashMap<>();
mapping.put("properties", properties);
request.mapping(mapping);
// 超时时间
request.setTimeout(TimeValue.timeValueMinutes(2));
request.setMasterTimeout(TimeValue.timeValueMinutes(1));
// 请求
CreateIndexResponse createIndexResponse = restHighLevelClient.indices().create(request, RequestOptions.DEFAULT);
if (createIndexResponse.isShardsAcknowledged()) {
    return true;
} else {
    return false;
}