ElasticSearch学习(七)在java应用中实现文档的添加、删除、更新

更新文档有直接更新和Upsert方式两种更新的方式:

Upsert更新方式:如果文档存在,执行更新;如果文档不存在,执行添加。

package Test;

import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.junit.Test;
import java.net.InetAddress;
import java.net.UnknownHostException;

public class ESTest {

    //从es找那个查询数据
    @org.junit.Test
    public void test1(){

        //指定ES集群
        Settings settings = Settings.builder().put("cluster.name", "my-application").build();

        //创建访问ES服务器的客户端
        try {
            TransportClient client = new PreBuiltTransportClient(settings)
                    .addTransportAddress(new TransportAddress(InetAddress.getByName("192.168.123.101"),9300));

            //数据查询
            GetResponse response  = client.prepareGet("lib3","user","1").execute().actionGet();

            //得到查询出的数据
            System.out.println(response.getSourceAsString());

            client.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    //向ES中添加文档
    @Test
    public void test2() throws Exception {
        //指定ES集群
        Settings settings = Settings.builder().put("cluster.name", "my-application").build();
        //创建访问ES服务器的客户端
        TransportClient client = new PreBuiltTransportClient(settings)
                .addTransportAddress(new TransportAddress(InetAddress.getByName("192.168.123.101"),9300));

        //向ES中添加文档
        /**
         *
         *      "{" +
         *     "\"id\":\"1"," +
         *     "\"titie\ ":\"Java设计模式之装饰模式\","+
         *     "\"content\ ":\"在不必改变原类文件和使用集成的情况下,动态地扩展一个对象的功能。\","+
         *      "\"postdate\ ":\"2018-05-20\","+
         *      "\"url\ ":\"csdn.net/79239071\""+
         *      "}"
         *
         *
         * PUT /index1
         * {
         *   "settings": {
         *     "number_of_shards": 3,
         *     "number_of_replicas": 0
         *   },
         *   "mappings": {
         *     "blog":{
         *       "properties": {
         *         "id":{
         *           "type": "long"
         *         },
         *         "title":{
         *           "type": "text"
         *           , "analyzer": "ik_max_word"
         *         },
         *         "content":{
         *           "type": "text"
         *           , "analyzer": "ik_max_word"
         *         },
         *         "postdate":{
         *           "type": "date"
         *         },
         *         "url":{
         *           "type": "text"
         *         }
         *       }
         *     }
         *   }
         * }
         */

        XContentBuilder doc = XContentFactory.jsonBuilder()
                .startObject()
                .field("id","1")
                .field("title","Java设计模式之装饰模式")
                .field("content","在不必改变原类文件和使用集成的情况下,动态地扩展一个对象的功能。")
                .field("postdate","2018-05-20")
                .field("url","csdn.net/79239071")
                .endObject();
        //添加文档
        IndexResponse response = client.prepareIndex("index1","blog","10")
                .setSource(doc).get();

        System.out.println(response.status());

    }

    //删除文档
    @Test
    public void test3() throws UnknownHostException {
        //指定ES集群
        Settings settings = Settings.builder().put("cluster.name", "my-application").build();
        //创建访问ES服务器的客户端
        TransportClient client = new PreBuiltTransportClient(settings)
                .addTransportAddress(new TransportAddress(InetAddress.getByName("192.168.123.101"),9300));

        //删除文档
        DeleteResponse deleteResponse = client.prepareDelete("index1", "blog", "10").get();
        System.out.println(deleteResponse.status());
        client.close();
    }

    //直接更新文档
    @Test
    public void test4 () throws Exception {
        //指定ES集群
        Settings settings = Settings.builder().put("cluster.name", "my-application").build();

        //创建访问ES服务器的客户端
        TransportClient client = new PreBuiltTransportClient(settings)
                .addTransportAddress(new TransportAddress(InetAddress.getByName("192.168.123.101"),9300));

        UpdateRequest request = new UpdateRequest();

        request.index("index1")
                .type("blog")
                .id("10")
                .doc(
                        XContentFactory.jsonBuilder().startObject()
                        .field("title","单例设计模式")
                        .endObject()
                );

        UpdateResponse response = client.update(request).get();

        System.out.println(response.status());

    }

    //upsert方式更新
    //如果文档存在,执行更新
    //如果文档不存在,执行添加
    @Test
    public void test5() throws Exception {
        //指定ES集群
        Settings settings = Settings.builder().put("cluster.name", "my-application").build();

        //创建访问ES服务器的客户端
        TransportClient client = new PreBuiltTransportClient(settings)
                .addTransportAddress(new TransportAddress(InetAddress.getByName("192.168.123.101"),9300));

        //添加文档
        IndexRequest request1 = new IndexRequest("index1", "blog", "8")
                .source(
                        XContentFactory.jsonBuilder().startObject()
                                .field("id", "2")
                                .field("title", "工厂模式")
                                .field("content", "静态工厂,实例工厂")
                                .field("postdate", "2018-05-20")
                                .field("url", "csdn.net/79239072")
                                .endObject()
                );

        UpdateRequest request2 = new UpdateRequest("index1", "blog", "8")
                .doc(
                        XContentFactory.jsonBuilder().startObject()
                                .field("title", "设计模式")
                                .endObject()
                ).upsert(request1);

        UpdateResponse response = client.update(request2).get();
        System.out.println(response.status());


    }
}

猜你喜欢

转载自blog.csdn.net/qq_41851454/article/details/81387946