1、创建新建索引请求对象
CreateIndexRequest request=new CreateIndexRequest(name);
2、通过CreateIndexRequest对象设置分片、副本和映射
request.settings(Settings.builder().put("index.number_of_shards", 3).put("index.number_of_replicas", 1));
request.mapping(mappings,XContentType.JSON);
这里的mappings可以之String,比如:
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);
也可以是XContentBuilder对象:
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);
3、通过RestHighLevelClient执行请求
首先,创建RestHighLevelClient对象:
RestHighLevelClient client = new RestHighLevelClient( RestClient.builder(new HttpHost("localhost",9200,"http")));
执行新建索引请求:
CreateIndexResponse createIndexResponse = client.indices().create(request, RequestOptions.DEFAULT);
通过创建索引响应来试试是否创建成功:
boolean acknowledged = createIndexResponse.isAcknowledged(); boolean shardsAcknowledged = createIndexResponse.isShardsAcknowledged();
如果这两个布尔值为true,创建成功。下面附上完整代码:
public class CreateIndex { private String name; private int shards; private int replicas; private String mappings; public CreateIndex(String name,int shards,int replicas,String mappings) { this.name=name; this.shards=shards; this.replicas=replicas; this.mappings=mappings; } public void createIndex() { CreateIndexRequest request=new CreateIndexRequest(name); request.settings(Settings.builder().put("index.number_of_shards", shards).put("index.number_of_replicas", replicas)); request.mapping(mappings,XContentType.JSON); RestHighLevelClient client = new RestHighLevelClient( RestClient.builder(new HttpHost("localhost",9200,"http"))); CreateIndexResponse createIndexResponse; try { createIndexResponse = client.indices().create(request, RequestOptions.DEFAULT); boolean acknowledged = createIndexResponse.isAcknowledged(); boolean shardsAcknowledged = createIndexResponse.isShardsAcknowledged(); if(acknowledged && shardsAcknowledged) { System.out.println("索引创建成功!"); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void main(String args[]) throws IOException { String mappings="{\r\n" + " \"properties\":{\r\n" + " \"title\":{\r\n" + " \"type\":\"text\",\r\n" + " \"analyzer\":\"ik_smart\"\r\n" + " },\r\n" + " \"content\":{\r\n" + " \"type\":\"text\",\r\n" + " \"analyzer\":\"ik_smart\"\r\n" + " },\r\n" + " \"date\":{\r\n" + " \"type\":\"text\"\r\n" + " }\r\n" + " }\r\n" + "}"; CreateIndex request=new CreateIndex("blog",3,1,mappings); request.createIndex(); } }