美文网首页
ES新增文档的四种方式

ES新增文档的四种方式

作者: 不怕天黑_0819 | 来源:发表于2022-03-29 11:40 被阅读0次

    本文集主要是总结自己在项目中使用ES 的经验教训,包括各种实战和调优。

       /** 
         * 通过prepareIndex增加文档,参数为json字符串 
         */  
        @Test  
        public void testIndexJson()  
        {  
            String source = "{\"name\":\"will\",\"age\":18}";  
            IndexResponse indexResponse = transportClient  
                    .prepareIndex(index, type, "3").setSource(source).get();  
            System.out.println(indexResponse.getVersion());  
        }  
          
        /** 
         * 通过prepareIndex增加文档,参数为Map<String,Object> 
         */  
        @Test  
        public void testIndexMap()  
        {  
            Map<String, Object> source = new HashMap<String, Object>(2);  
            source.put("name", "Alice");  
            source.put("age", 16);  
            IndexResponse indexResponse = transportClient  
                    .prepareIndex(index, type, "4").setSource(source).get();  
            System.out.println(indexResponse.getVersion());  
        }  
          
        /** 
         * 通过prepareIndex增加文档,参数为javaBean 
         *  
         * @throws ElasticsearchException 
         * @throws JsonProcessingException 
         */  
        @Test  
        public void testIndexBean() throws ElasticsearchException, JsonProcessingException  
        {  
            Student stu = new Student();  
            stu.setName("Fresh");  
            stu.setAge(22);  
              
            ObjectMapper mapper = new ObjectMapper();  
            IndexResponse indexResponse = transportClient  
                    .prepareIndex(index, type, "5").setSource(mapper.writeValueAsString(stu)).get();  
            System.out.println(indexResponse.getVersion());  
        }  
          
        /** 
         * 通过prepareIndex增加文档,参数为XContentBuilder 
         *  
         * @throws IOException 
         * @throws InterruptedException 
         * @throws ExecutionException 
         */  
        @Test  
        public void testIndexXContentBuilder() throws IOException, InterruptedException, ExecutionException  
        {  
            XContentBuilder builder = XContentFactory.jsonBuilder()  
                    .startObject()  
                    .field("name", "Avivi")  
                    .field("age", 30)  
                    .endObject();  
            IndexResponse indexResponse = transportClient  
                    .prepareIndex(index, type, "6")  
                    .setSource(builder)  
                    .execute().get();  
            //.execute().get();和get()效果一样  
            System.out.println(indexResponse.getVersion());  
        }  
    
    

    相关文章

      网友评论

          本文标题:ES新增文档的四种方式

          本文链接:https://www.haomeiwen.com/subject/znxorktx.html