编程语言
首页 > 编程语言> > ElasticSearch Java API之crud

ElasticSearch Java API之crud

作者:互联网

Java连接es客户端方式

  1. low level rest client:低级别的rest客户端,通过http与集群交互,用户需要自己编组请求json串、解析响应的json串。
  2. high level rest client:高级别客户端,基于低级别的客户端,增加了编组请求json串、解析响应的json串等API。

部分API

示例

  1. client连接获取工具
  1. 对索引、文档的crud方法

     public class Test {
    
         private RestHighLevelClient client=ESClientConnectionUtil.getESClientConnection();
     
         /**
          * @Author haien
          * @Description 创建index
          * @Date 2019/7/18
          * @Param []
          * @return void
          **/
         public boolean createIndex() throws IOException {
             //索引名称
             CreateIndexRequest request=new CreateIndexRequest("books")
                     //设置分片、副本和刷新间隔
                     .settings(Settings.builder()
                             .put("index.number_of_shards",3)
                             .put("index.number_of_replicas",2)
                             .put("refresh_interval","10s")
                             //默认分词器
                             //.put("analysis.analyzer.default.tokenizer","ik_smart")
                     );
     
             //创建fullText属性
             Map<String,Object> fullText=new HashMap<>();
             fullText.put("type","text");
             fullText.put("analyzer","ik_max_word");
             fullText.put("search_analyzer","ik_smart");
             fullText.put("term_vector","with_positions_offsets");
     
             //创建fondCode属性
             Map<String,Object> fondCode=new HashMap<>();
             fondCode.put("type","keyword");
     
             Map<String,Object> properties=new HashMap<>();
             properties.put("fullText",fullText);
             properties.put("fondCode",fondCode);
     
             Map<String,Object> mapping=new HashMap<>();
             mapping.put("properties",properties);
     
             request.mapping(mapping);
     
             /*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);*/
     
     /*
     
             request.mapping(
                     "{\n" +
                             "  \"properties\": {\n" +
                             "    \"message\": {\n" +
                             "      \"type\": \"text\"\n" +
                             "    }\n" +
                             "  }\n" +
                             "}",
                     XContentType.JSON);
     */
     
             CreateIndexResponse response=
                     client.indices().create(request,RequestOptions.DEFAULT);
     
             boolean acknowledged=response.isAcknowledged();
             return acknowledged;
         }
     
         /**
          * @Author haien
          * @Description 删除索引
          * @Date 2019/7/21
          * @Param [indexName]
          * @return boolean
          **/
         public boolean deleteIndex(String indexName) throws IOException {
             //判断索引是否存在
             if(!existIndex(indexName))
                 return false;
     
             DeleteIndexRequest request=new DeleteIndexRequest(indexName);
             AcknowledgedResponse response=
                     client.indices().delete(request, RequestOptions.DEFAULT);
             //如果事先不判存,不存在时应该是返回false
             return response.isAcknowledged();
         }
     
         /**
          * @Author haien
          * @Description 判断索引是否存在
          * @Date 2019/7/21
          * @Param [indexName]
          * @return boolean
          **/
         public boolean existIndex(String indexName) throws IOException {
             Assert.notNull(indexName,"索引名称不能为空");
             GetIndexRequest request=new GetIndexRequest(indexName);
             return client.indices().exists(request, RequestOptions.DEFAULT);
         }
     
         /**
          * @Author haien
          * @Description 新增文档
          * @Date 2019/7/21
          * @Param []
          * @return void
          **/
         public boolean addDocument(String indexName,String id,Map<String,Object> docMap)
                 throws IOException {
             /*
             * 四种文档设置格式:json字符串、Map或XContentBuilder对象
             * */
             /*
             IndexRequest request=new IndexRequest("posts");
             request.id("1");
             String jsonString="{" +
                     "\"user\":\"kimchy\"," +
                     "\"postDate\":\"2013-01-30\"," +
                     "\"message\":\"trying out Elasticsearch\"" +
                     "}";
             //把字符串转为json,返回的还是IndexRequest
             request.source(jsonString,XContentType.JSON);
     */
             /*或者*/
             /*
             IndexRequest request=new IndexRequest("posts").id("1")
                     //自动转为json
                     .source("user","kimchy",
                         "postDate",new Date(),
                         "message","trying out Elasticsearch");*/
     
             /*或者*/
             /*
             Map<String,Object> jsonMap=new HashMap<>();
             jsonMap.put("user","kimchy");
             jsonMap.put("postDate",new Date());
             jsonMap.put("message","trying out Elasticsearch");
             //map会自动被转为json
             IndexRequest request=new IndexRequest("posts").id("1").source(jsonMap);
     */
             /*或者*/
             //用来生成json的工具
             /*
             XContentBuilder builder=XContentFactory.jsonBuilder();
             builder.startObject();
             {
                 builder.field("user","kimchy");
                 builder.field("postDate",new Date());
                 builder.field("message","trying out Elasticsearch");
             }
             builder.endObject();
             IndexRequest request=new IndexRequest("posts").id("1").source(builder);*/
     
             boolean opFlag=Boolean.TRUE;
             try {
                 Assert.notNull(indexName, "索引名称不能为空");
                 Assert.notNull(id, "索引文档id不能为空");
                 Assert.notNull(docMap, "索引文档docMap不能为空");
     
                 //未指定type,默认为_doc
                 IndexRequest request = new IndexRequest(indexName).id(id).source(docMap);
                 request.opType(DocWriteRequest.OpType.CREATE);
     
                 client.index(request, RequestOptions.DEFAULT);
             } catch (Exception e){
                 logger.error("添加索引文档失败异常,索引名称【{}】,索引文档【{}】",
                         indexName,id,e);
                 opFlag=Boolean.FALSE;
             }
             return opFlag;
     
         }
     
         /**
          * @Author haien
          * @Description 查询文档
          * @Date 2019/7/21
          * @Param [indexName, type, id]
          * @return java.util.Map<java.lang.String,java.lang.Object>
          **/
         public Map<String,Object> getDocument(String indexName,String id){
             if(!existDocument(indexName,id)){
                 logger.error("索引或id不存在,索引名称【{}】,索引文档【{}】",
                         indexName,id);
                 return null;
             }
     
             Map<String,Object> docMap=null;
             try {
                 Assert.notNull(indexName,"索引名称不能为空");
                 Assert.notNull(id,"索引文档id不能为空");
     
                 GetRequest request = new GetRequest(indexName,id);
                 GetResponse response=client.get(request,RequestOptions.DEFAULT);
                 docMap=response.getSourceAsMap();
             } catch (Exception e){
                 logger.error("根据id获取索引文档异常,索引名称【{}】,索引文档【{}】",
                         indexName,id,e);
             }
     
             return docMap;
         }
     
         /**
          * @Author haien
          * @Description 判断文档是否存在
          * @Date 2019/7/21
          * @Param [indexName, id]
          * @return boolean
          **/
         public boolean existDocument(String indexName,String id){
             boolean opFlag=Boolean.TRUE;
     
             try {
                 Assert.notNull(indexName,"索引名称不能为空");
                 Assert.notNull(id,"索引文档id不能为空");
     
                 GetRequest request=new GetRequest(indexName,id);
                 request.fetchSourceContext(new FetchSourceContext(false));
                 request.storedFields("_none_");
                 opFlag=client.exists(request,RequestOptions.DEFAULT);
             } catch (IOException e) {
                 logger.error("根据id判断索引文档是否存在异常,
                     索引名称【{}】,索引文档id【{}】," +
                         indexName,id,e);
             }
     
             return opFlag;
         }
     
         /**
          * @Author haien
          * @Description 删除文档
          * @Date 2019/7/21
          * @Param [indexName, type, id]
          * @return boolean
          **/
         public boolean deleteDocument(String indexName,String id){
             boolean opFlag=Boolean.TRUE;
             try{
                 Assert.notNull(indexName,"索引名称不能为空");
                 Assert.notNull(id,"索引文档id不能为空");
     
                 GetRequest request=new GetRequest(indexName,id);
                 request.fetchSourceContext(new FetchSourceContext(false));
                 request.storedFields("_none_");
                 opFlag=client.exists(request,RequestOptions.DEFAULT);
                 if(opFlag){
                     DeleteRequest request1=new DeleteRequest(indexName,id);
                     client.delete(request1,RequestOptions.DEFAULT);
                 }
             } catch (IOException e) {
                 logger.error("根据id判断索引文档是否存在异常,索引名称【{}】,索引文档id【{}】",
                         indexName,id);
             }
     
             return opFlag;
         }
     
         /**
          * @Author haien
          * @Description 更新文档
          * @Date 2019/7/21
          * @Param [indexName, type, id, docMap]
          * @return boolean
          **/
         public boolean updateDocument(String indexName,String id,
                 Map<String,Object> docMap){
             boolean opFlag=Boolean.TRUE;
     
             try {
                 Assert.notNull(indexName,"索引名称不能为空");
                 Assert.notNull(id,"文档id不能为空");
                 Assert.notNull(docMap,"索引文档docMap不能为空");
     
                 UpdateRequest request=new UpdateRequest(indexName,id).doc(docMap);
                 client.update(request,RequestOptions.DEFAULT);
             } catch (IOException e) {
                 logger.error("修改文档异常,索引名称【{}】,文档id【{}】",indexName,id,e);
             }
     
             return opFlag;
         }
     
         /**
          * @Author haien
          * @Description 批量添加文档
          * @Date 2019/7/21
          * @Param [indexName, docMaps]
          * @return boolean
          **/
         public boolean bulkAddDocument(String indexName, List<Map<String,Object>> docMaps){
             boolean opFlag=Boolean.TRUE;
     
             try {
                 Assert.notNull(indexName,"索引名称不能为空");
                 Assert.notNull(docMaps,"索引文档docMaps不能为空");
     
                 BulkRequest request=new BulkRequest();
                 for (int i=0;i<docMaps.size();i++){
                     Map<String,Object> docMap=docMaps.get(i);
                     request.add(new IndexRequest(indexName).id(docMap.get("id")+"")
                             .source(docMap).opType(DocWriteRequest.OpType.CREATE));
                 }
                 client.bulk(request,RequestOptions.DEFAULT);
             } catch (IOException e) {
                 logger.error("批量添加文档异常,索引名称【{}】",indexName,e);
             }
             
             //处理响应
             if(responses!=null){
                 for(BulkItemResponse bulkItemResponse:responses){
                     DocWriteResponse itemResponse=bulkItemResponse.getResponse();
                     //操作类型为新增文档
                     if(bulkItemResponse.getOpType()==DocWriteRequest.OpType.INDEX
                         ||bulkItemResponse.getOpType()==DocWriteRequest.OpType.CREATE){
                         IndexResponse indexResponse=(IndexResponse)itemResponse;
                         //新增文档成功的处理
                         
                     }else if(bulkItemResponse.getOpType() == 
                             DocWriteRequest.OpType.UPDATE) {
                         DeleteResponse deleteResponse=(DeleteResponse)itemResponse;
                         //删除文档成功的处理
                     }
                 }
             }
     
             return opFlag;
         }
     
         /**
          * @Author haien
          * @Description 批量修改文档
          * @Date 2019/7/21
          * @Param [indexName, docMaps]
          * @return boolean
          **/
         public boolean bulkUpdateDocument(String indexName,
                 List<Map<String,Object>> docMaps){
                 
             boolean opFlag=Boolean.TRUE;
     
             try {
                 Assert.notNull(indexName,"索引名称不能为空");
                 Assert.notNull(docMaps,"索引文档docMaps不能为空");
     
                 BulkRequest request=new BulkRequest();
                 for (int i=0;i<docMaps.size();i++){
                     Map<String,Object> docMap=docMaps.get(i);
                     request.add(
                             new UpdateRequest(indexName,docMap.get("id")+"").doc(docMap));
                 }
                 client.bulk(request,RequestOptions.DEFAULT);
             } catch (IOException e) {
                 logger.error("批量修改文档异常,索引名称【{}】",indexName,e);
             }
     
             return opFlag;
         }
     
         /**
          * @Author haien
          * @Description 批量删除文档
          * @Date 2019/7/25
          * @Param [indexName, docMaps]
          * @return boolean
          **/
         public boolean bulkdeleteDocument(String indexName,
                 List<Map<String,Object>> docMaps){
                 
             boolean opFlag=Boolean.TRUE;
     
             try {
                 Assert.notNull(indexName,"索引名称不能为空");
                 Assert.notNull(docMaps,"索引文档docMaps不能为空");
     
                 BulkRequest request=new BulkRequest();
                 for (int i=0;i<docMaps.size();i++){
                     Map<String,Object> docMap=docMaps.get(i);
                     request.add(new DeleteRequest(indexName,docMap.get("id")+""));
                 }
                 client.bulk(request,RequestOptions.DEFAULT);
             } catch (IOException e) {
                 logger.error("批量删除文档异常,索引名称【{}】",indexName,e);
             }
     
             return opFlag;
         }
     }
    

标签:indexName,request,crud,client,return,API,new,Java,id
来源: https://blog.csdn.net/jiachunchun/article/details/115397687