创建SpringBoot项目,并导入依赖
二、配置 1、配置类org.springframework.boot spring-boot-starter-data-elasticsearch
非SpringBoot项目,可通过配置类的方式配置ES
@Bean public RestHighLevelClient restHighLevelClient(){ HttpHost httpHost = new HttpHost("localhost", 9200, "http"); RestClientBuilder clientBuilder = RestClient.builder(httpHost); return new RestHighLevelClient(clientBuilder); }2、配置文件
SpringBoot项目可通过配置文件配置ES
spring: elasticsearch: rest: uris: http://localhost:9200三、索引 1、创建索引
@PutMapping("createIndex") public String createIndex(@RequestParam String indexName){ // 封装请求 CreateIndexRequest indexRequest=new CreateIndexRequest(indexName); CreateIndexResponse createIndexResponse = null; try { // 发送请求 createIndexResponse = restHighLevelClient.indices().create(indexRequest, RequestOptions.DEFAULT); } catch (IOException e) { e.printStackTrace(); } if (createIndexResponse.isAcknowledged()){ return indexName+" 索引创建创建成功"; } return indexName+" 索引创建失败"; }2、删除索引
@DeleteMapping("deleteIndex") public String deleteIndex(@RequestParam String indexName){ DeleteIndexRequest indexRequest=new DeleteIndexRequest(indexName); AcknowledgedResponse acknowledgedResponse = null; try { acknowledgedResponse = restHighLevelClient.indices().delete(indexRequest, RequestOptions.DEFAULT); } catch (IOException e) { e.printStackTrace(); } if (acknowledgedResponse.isAcknowledged()){ return indexName+" 索引删除成功"; } return indexName+" 索引删除失败"; }四、文档 1、创建/修改文档
@PostMapping("createDoc/{docId}") public String createdocument(@PathVariable String docId,@RequestBody String doc){ IndexRequest indexRequest=new IndexRequest("index2"); indexRequest.id(docId); indexRequest.source(doc, XContentType.JSON); IndexResponse indexResponse = null; try { indexResponse = restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT); } catch (IOException e) { e.printStackTrace(); } RestStatus status = indexResponse.status(); if (status.getStatus() == 200){ return "文档创建成功,id为"+docId; } return docId+ "文档创建失败"; }2、删除文档
@DeleteMapping("deleteDoc/{docId}") public String deleteDoc(@PathVariable String docId){ DeleteRequest indexRequest=new DeleteRequest("index2"); indexRequest.id(docId); DeleteResponse deleteResponse=null; try { deleteResponse = restHighLevelClient.delete(indexRequest, RequestOptions.DEFAULT); } catch (IOException e) { e.printStackTrace(); } if (deleteResponse.status().getStatus() == 201) { return "文档删除成功"; } return "文档删除失败"; }五、查询文档
查询的逻辑比较复杂,如下图所示
public String searchDoc(){ List
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)