Es中数据的插入操作

package com.atguigu.es.test;

import com.atguigu.po.User;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpHost;
import org.elasticsearch.action.DocWriteResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;

import java.io.IOException;
public class ESTest_Doc_Insert {
    public static void main(String[] args) throws IOException {
        //创建ES客户端
        HttpHost httpHost = new HttpHost("localhost", 9200, "http");
        RestHighLevelClient esClient = new RestHighLevelClient(RestClient.builder(httpHost));
        //插入数据
        IndexRequest request  = new IndexRequest();
        request.index("user").id();
        User user =new User();
        user.setName("zhangsan");
        user.setAge(30);
        user.setSex("男");
        //向ES中插入数据,必须将数据转换为JSON格式
        ObjectMapper mapper = new ObjectMapper();
        String userJson = mapper.writeValueAsString(user);
        request.source(userJson, XContentType.JSON);
        IndexResponse response = esClient.index(request, RequestOptions.DEFAULT);
        DocWriteResponse.Result result = response.getResult();
        String responseId = response.getId();
        System.out.println("result:"+result);
        System.out.println("responseId"+responseId);
        
        //关闭ES客户端
        esClient.close();

    }




}

你可能感兴趣的:(es,elasticsearch,搜索引擎,java)