其实Rest High Level Client的使用逻辑一共就分散步:
- 拼json
- 创建request
- client执行request
创建client:
RestHighLevelClient restHighLevelClient = new RestHighLevelClient(RestClient.builder(new HttpHost("127.0.0.1",9200,"http"))); 创建索引:
@Test public void createIndex() throws IOException { //1.拼json //settings Settings.Builder settings = Settings.builder() .put("number_of_shards", 3) .put("number_of_replicas", 1); //mappings XContentBuilder mappings = JsonXContent.contentBuilder(). startObject(). startObject("properties"). startObject("name"). field("type", "text"). endObject(). startObject("age"). field("type", "integer"). endObject(). endObject(). endObject(); //2.创建request CreateIndexRequest createIndexRequest = new CreateIndexRequest("person").settings(settings).mapping(mappings); //3.client执行request restHighLevelClient.indices().create(createIndexRequest, RequestOptions.DEFAULT); } 创建文档:
@Test public void createDoc() throws IOException { Person person=new Person("1","zou",20); JSONObject json = JSONObject.from(person); System.out.println(json); IndexRequest request=new IndexRequest("person",null,person.getId().toString()); request.source(json, XContentType.JSON); IndexResponse response = restHighLevelClient.index(request, RequestOptions.DEFAULT); System.out.println(response); } 响应结果: