(18)ElasticSearch java项目中的增删查改基本操作

  新建索引,名称index1、类型blog、title与content用中文分词器

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"
        }
      }
    }
  }
}
View Code

  1、增加文档

    @Test
    public void testAdd() throws IOException {
        //指定集群
        Settings settings = Settings.builder().put("cluster.name","my-application").build(); 
        //创建客户端
        TransportClient client = new PreBuiltTransportClient(settings)
                                .addTransportAddress(new TransportAddress(InetAddress.getByName("192.168.43.151"),9300));
        //创建文档
        XContentBuilder doc = XContentFactory.jsonBuilder()
                              .startObject()
                              .field("id","1")
                              .field("title","java设计模式之装配模式")
                              .field("content","在不必改变原类文件和使用继承的情况下,动态的扩展一个对象的功能")
                              .field("postdate","2018-05-20")
                              .field("url","csdn.net/79239027")
                              .endObject();
        //增加文档并返回结果
        IndexResponse response = client.prepareIndex("index1","blog","10").setSource(doc).get();
        //如果执行成功输出CREATED
        System.out.println(response.status());
        client.close();                        
    }

  2、查询文档

    @Test
    public void testQuery() throws UnknownHostException {
        //指定集群
        Settings settings = Settings.builder().put("cluster.name","my-application").build(); 
        //创建客户端
        TransportClient client = new PreBuiltTransportClient(settings)
                                .addTransportAddress(new TransportAddress(InetAddress.getByName("192.168.43.151"),9300));
        //查询并返回结果,查询条件:索引是index1,类型是blog,id是10的数据
        GetResponse response = client.prepareGet("index1","blog","10").execute().actionGet();
        //如果查询到数据输出json字符串,否则输出null
        System.out.println(response.getSourceAsString());
        client.close();//关闭客户端
    }

   3、修改文档

    @Test
    public void testUpdate() throws IOException, InterruptedException, ExecutionException {
        //指定集群
        Settings settings = Settings.builder().put("cluster.name","my-application").build(); 
        //创建客户端
        TransportClient client = new PreBuiltTransportClient(settings)
                                .addTransportAddress(new TransportAddress(InetAddress.getByName("192.168.43.151"),9300));
        //创建文档
        XContentBuilder doc = XContentFactory.jsonBuilder()
                                               .startObject()
                                               .field("title","单例设计模式")
                                               .endObject();
        //更新文档请求
        UpdateRequest request = new  UpdateRequest();
        //指定更新的文档
        request.index("index1").type("blog").id("10").doc(doc);
        //执行操作并返回结果
        UpdateResponse response = client.update(request).get();
        //如果更新成功输出OK,如果找不到数据序直接报错
        System.out.println(response.status());
        client.close();
   }

  4、删除文档

    @Test
    public void testDelete() throws IOException {
        //指定集群
        Settings settings = Settings.builder().put("cluster.name","my-application").build(); 
        //创建客户端
        TransportClient client = new PreBuiltTransportClient(settings)
                                .addTransportAddress(new TransportAddress(InetAddress.getByName("192.168.43.151"),9300));
        //删除文档并返回结果
        DeleteResponse response = client.prepareDelete("index1","blog","10").get();
        //如果删除成功输出OK,不存在输出NOT_FOUND
        System.out.println(response.status());
        client.close();                    
    }

  5、如果存在则更新,不存在则新增

    @Test
    public void testUpsert() throws IOException, InterruptedException, ExecutionException {
        //指定集群
        Settings settings = Settings.builder().put("cluster.name","my-application").build(); 
        //创建客户端
        TransportClient client = new PreBuiltTransportClient(settings)
                                .addTransportAddress(new TransportAddress(InetAddress.getByName("192.168.43.151"),9300));
        //创建新增文档
        XContentBuilder doc = XContentFactory.jsonBuilder()
                             .startObject()
                             .field("id","2")
                             .field("title","工厂模式")
                             .field("content","静态工厂,实例工厂。")
                             .field("postdate","2018-05-20")
                             .field("url","csdn.net/79239027")
                             .endObject();
        //创建更新文档
        XContentBuilder doc2 = XContentFactory.jsonBuilder()
                                              .startObject()
                                              .field("title","设计模式")
                                              .endObject();
        //指定新增的位置
        IndexRequest request1 = new  IndexRequest("index1","blog","8").source(doc);
        //创建更新请求
        UpdateRequest request2 = new UpdateRequest("index1","blog","8").doc(doc2).upsert(request1);
        //执行并返回结果            
        UpdateResponse response = client.update(request2).get();
        //如果执行增加输出CREATED,如果执行更新输出OK
        System.out.println(response.status());
    }

  附:完成测试类

package com.edu.elasticSearch;

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.concurrent.ExecutionException;

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;

public class ESTest {

    @Test
    public void testAdd() throws IOException {
        //指定集群
        Settings settings = Settings.builder().put("cluster.name","my-application").build(); 
        //创建客户端
        TransportClient client = new PreBuiltTransportClient(settings)
                                .addTransportAddress(new TransportAddress(InetAddress.getByName("192.168.43.151"),9300));
        //创建文档
        XContentBuilder doc = XContentFactory.jsonBuilder()
                              .startObject()
                              .field("id","1")
                              .field("title","java设计模式之装配模式")
                              .field("content","在不必改变原类文件和使用继承的情况下,动态的扩展一个对象的功能")
                              .field("postdate","2018-05-20")
                              .field("url","csdn.net/79239027")
                              .endObject();
        //增加文档并返回结果
        IndexResponse response = client.prepareIndex("index1","blog","10").setSource(doc).get();
        //如果执行成功输出CREATED
        System.out.println(response.status());
        client.close();                        
    }

    @Test
    public void testQuery() throws UnknownHostException {
        //指定集群
        Settings settings = Settings.builder().put("cluster.name","my-application").build(); 
        //创建客户端
        TransportClient client = new PreBuiltTransportClient(settings)
                                .addTransportAddress(new TransportAddress(InetAddress.getByName("192.168.43.151"),9300));
        //查询并返回结果,查询条件:索引是index1,类型是blog,id是10的数据
        GetResponse response = client.prepareGet("index1","blog","10").execute().actionGet();
        //如果查询到数据输出json字符串,否则输出null
        System.out.println(response.getSourceAsString());
        client.close();//关闭客户端
    }

    @Test
    public void testDelete() throws IOException {
        //指定集群
        Settings settings = Settings.builder().put("cluster.name","my-application").build(); 
        //创建客户端
        TransportClient client = new PreBuiltTransportClient(settings)
                                .addTransportAddress(new TransportAddress(InetAddress.getByName("192.168.43.151"),9300));
        //删除文档并返回结果
        DeleteResponse response = client.prepareDelete("index1","blog","10").get();
        //如果删除成功输出OK,不存在输出NOT_FOUND
        System.out.println(response.status());
        client.close();                    
    }

    @Test
    public void testUpdate() throws IOException, InterruptedException, ExecutionException {
        //指定集群
        Settings settings = Settings.builder().put("cluster.name","my-application").build(); 
        //创建客户端
        TransportClient client = new PreBuiltTransportClient(settings)
                                .addTransportAddress(new TransportAddress(InetAddress.getByName("192.168.43.151"),9300));
        //创建文档
        XContentBuilder doc = XContentFactory.jsonBuilder()
                                               .startObject()
                                               .field("title","单例设计模式")
                                               .endObject();
        //更新文档请求
        UpdateRequest request = new  UpdateRequest();
        //指定更新的文档
        request.index("index1").type("blog").id("10").doc(doc);
        //执行操作并返回结果
        UpdateResponse response = client.update(request).get();
        //如果更新成功输出OK,如果找不到数据序直接报错
        System.out.println(response.status());
        client.close();
   }

    @Test
    public void testUpsert() throws IOException, InterruptedException, ExecutionException {
        //指定集群
        Settings settings = Settings.builder().put("cluster.name","my-application").build(); 
        //创建客户端
        TransportClient client = new PreBuiltTransportClient(settings)
                                .addTransportAddress(new TransportAddress(InetAddress.getByName("192.168.43.151"),9300));
        //创建新增文档
        XContentBuilder doc = XContentFactory.jsonBuilder()
                             .startObject()
                             .field("id","2")
                             .field("title","工厂模式")
                             .field("content","静态工厂,实例工厂。")
                             .field("postdate","2018-05-20")
                             .field("url","csdn.net/79239027")
                             .endObject();
        //创建更新文档
        XContentBuilder doc2 = XContentFactory.jsonBuilder()
                                              .startObject()
                                              .field("title","设计模式")
                                              .endObject();
        //指定新增的位置
        IndexRequest request1 = new  IndexRequest("index1","blog","8").source(doc);
        //创建更新请求
        UpdateRequest request2 = new UpdateRequest("index1","blog","8").doc(doc2).upsert(request1);
        //执行并返回结果            
        UpdateResponse response = client.update(request2).get();
        //如果执行增加输出CREATED,如果执行更新输出OK
        System.out.println(response.status());
    }
}
View Code

  备注:网页客户端相关命令

  GET /index1/blog/10
  DELETE index1/blog/10

  GET /index1/blog/8
  DELETE index1/blog/8

     

原文地址:https://www.cnblogs.com/javasl/p/12070403.html