ES代码操作索引库
-
创建索引库
@Test
public void createIndex() throws IOException {//使用client获取操作索引的对象 IndicesClient indicesClient = restHighLevelClient.indices(); //操作索引对象执行操作,获取返回值 CreateIndexRequest createRequest = new CreateIndexRequest("myfirst"); CreateIndexResponse response = indicesClient.create(createRequest, RequestOptions.DEFAULT); //返回结果判断 System.out.println(response.isAcknowledged());
}`
-
带mapping创建索引`
@Test
public void createIndexAndMapping() throws IOException {//使用高级客户端获取操作Index对象 IndicesClient indicesClient = restHighLevelClient.indices(); //创建索引(带索引的Index) CreateIndexRequest createIndexRequest = new CreateIndexRequest("mytwo"); String mapping = "{\n" + " \"properties\":{\n" + " \"id\":{\n" + " \"type\":\"long\",\n" + " \"store\":true,\n" + " \"index\":true\n" + " },\n" + " \"name\":{\n" + " \"type\":\"keyword\"\n" + " },\n" + " \"email\":{\n" + " \"type\":\"text\",\n" + " \"analyzer\":\"standard\"\n" + " }\n" + " }\n" + "}"; createIndexRequest.mapping(mapping, XContentType.JSON); CreateIndexResponse createIndexResponse = indicesClient.create(createIndexRequest, RequestOptions.DEFAULT); //打印结果 System.out.println(createIndexResponse.isAcknowledged());
}`
-
查询索引库`
@Test
public void queryIndex() throws IOException {//索引客户端创建 IndicesClient indicesClient = restHighLevelClient.indices(); //查询 GetIndexRequest getIndexRequest = new GetIndexRequest("mytwo"); GetIndexResponse getIndexResponse = indicesClient.get(getIndexRequest, RequestOptions.DEFAULT); //解析响应 Map<String, MappingMetaData> mappings = getIndexResponse.getMappings(); for (String key : mappings.keySet()) { System.out.println("key: " + key + ", value:" + mappings.get(key).getSourceAsMap()); }
}
` -
删除索引库`
@Test
public void deleteIndex() throws IOException {//高级客户端获取索引客户端 IndicesClient indicesClient = restHighLevelClient.indices(); //删除操作 DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest("mytwo"); AcknowledgedResponse deleteResponse = indicesClient.delete(deleteIndexRequest, RequestOptions.DEFAULT); System.out.println(deleteResponse.isAcknowledged());
}`
-
判断索引是否存在
@Test public void existIndex() throws IOException { IndicesClient indicesClient = restHighLevelClient.indices(); GetIndexRequest getIndexRequest = new GetIndexRequest("mytwo"); boolean exists = indicesClient.exists(getIndexRequest, RequestOptions.DEFAULT); System.out.println(exists); }