Elasticsearch简单使用系列--使用Java API进行CRUD操作

1.简单介绍Elasticsearch和RDBMS对应的关系,便于记忆理解

Elasticsearch RDBMS
index database
type/mapping table
document/object row/record
field column

2.封装一个获取client的工具类


/**
 * @author lcj
 * @version 1.0
 * @description 获取client
 * @Create 2017-06-19
 */
public  class TransportClientUtil {

    public static TransportClient getTransportClient(){
        Settings settings = Settings.builder()
                .put("cluster.name","es-cluster") //设置集群的名字,默认是elasticsearch
                .put("client.transport.sniff",true) //启用监听器,每5秒刷新一次nodes
                .build();
        TransportClient client = null;
        try {
            client = new PreBuiltTransportClient(settings)
            //设置node
            //.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(System.getenv("COMPUTERNAME")),9300));
            .addTransportAddress(new InetSocketTransportAddress(InetAddress.getLocalHost(),9300));
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        return client;
    }
}

3.使用java api进行CRUD


/**
 * @author lcj
 * @version 1.0
 * @description 使用java api操作es node,进行简单的crud
 * @Create 2017-06-22
 */
public class EsJavaApi {

    private static final Logger LOGGER = LoggerFactory.getLogger(EsJavaApi.class);

    private static TransportClient client = TransportClientUtil.getTransportClient();

    public static void main(String[] args) {
        //创建索引文档
        //save();

        //搜索文档
        //get();

        //更新文档
        //update();

        //删除文档
        delete();

        //关闭链接
        client.close();

    }

    /**
     * pojo bean ,创建index 文档
     */
    private static void save(){
        Book book = new Book();
        book.setName("jvm 虚拟机5");
        book.setAuthor("lcj4");
        book.setPublishTime(new Date().toString());
        book.setPrice(512.10);
        book.setId("17");

        ObjectMapper mapper = new ObjectMapper();
        try {
            byte[] bytes = mapper.writeValueAsBytes(book);
            IndexResponse response = client.prepareIndex("book","book",book.getId())
                    .setSource(bytes)
                    .get();

            System.out.println(response.getResult()); //CREATED
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据id,搜索文档
     */
    private static void get(){
        GetResponse response = client.prepareGet("book","book","17")
                .setOperationThreaded(false) //默认为true,在不同的线程执行
                .get();

        //{"id":"17","name":"jvm 虚拟机5","author":"lcj4","price":512.1,"publishTime":"Thu Jun 22 13:36:49 CST 2017"}
        System.out.println(response.getSourceAsString());

    }


    /**
     * 更新文档
     */
    private static void update(){
        UpdateRequest updateRequest = new UpdateRequest();
        //指定索引
        updateRequest.index("book");
        //指定类型
        updateRequest.type("book");
        //指定id
        updateRequest.id("17");

        Book book = new Book();
        book.setName("jvm 虚拟机55");
        book.setAuthor("lcj4");
        book.setPublishTime(DateFormatUtils.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
        book.setPrice(512.18);
        book.setId("17");

        ObjectMapper mapper = new ObjectMapper();

        //有很多重载方法
        //{"_index":"book","_type":"book","_id":"17","_version":2,"found":true,"_source":{"id":"17","name":"jvm 虚拟机55","author":"lcj4","price":512.18,"publishTime":"2017-06-22 13:45:22"}}
        try {
            updateRequest.doc(mapper.writeValueAsBytes(book));
            client.update(updateRequest).get();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /*根据id删除文档*/
    private static void delete(){
        DeleteResponse response = client.prepareDelete("book","book","17")
                .get();
        //DeleteResponse[index=book,type=book,id=17,version=3,result=deleted,shards=ShardInfo{total=2, successful=1, failures=[]}]
        System.out.println(response);
    }
}

你可能感兴趣的:(Elasticsearch简单使用系列--使用Java API进行CRUD操作)