第3讲:3.1 ElasticSearch创建索引,增删改查文档

1.新建一个testIndex类,设置ip和端口,写getClient(){} 方法,添加@Before注解

package com.cruise;

import java.net.InetAddress;

import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.google.gson.JsonObject;

public class TestIndex {

    private static String host="192.168.245.40";
    private static int port=9300;
    private TransportClient client =null;
    
    @SuppressWarnings({ "resource", "unchecked" })
    @Before
    public void getClient() throws Exception{
        client = new PreBuiltTransportClient(Settings.EMPTY)
      .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(host),port));
    }
}

2.添加JUnit,写close()方法,添加@After注解

    @After
    public void close(){
        if(client!=null){
            client.close();
        }
    }

3.写testIndex()方法,运行测试;去掉id,测试

    @Test
    public void testIndex() throws Exception{
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("name", "java编程思想");
        jsonObject.addProperty("publishDate", "2011-11-11");
        jsonObject.addProperty("pirce", "100");
        IndexResponse indexResponse = client.prepareIndex("book","java","1")
            .setSource(jsonObject.toString(), XContentType.JSON).get();
        System.out.println("索引名称:"+indexResponse.getIndex());
        System.out.println("类型:"+indexResponse.getType());
        System.out.println("id:"+indexResponse.getId());
        System.out.println("当前索引状态:"+indexResponse.status());
        
    }

测试:

3.1_ElasticSearch创建索引,增删改查文档

   修改(去掉id "1")

    @Test
    public void testIndex() throws Exception{
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("name", "java编程思想");
        jsonObject.addProperty("publishDate", "2011-11-11");
        jsonObject.addProperty("pirce", "100");
        IndexResponse indexResponse = client.prepareIndex("book","java")
            .setSource(jsonObject.toString(), XContentType.JSON).get();
        System.out.println("索引名称:"+indexResponse.getIndex());
        System.out.println("类型:"+indexResponse.getType());
        System.out.println("id:"+indexResponse.getId());
        System.out.println("当前索引状态:"+indexResponse.status());
        
    }

   测试:(为了后面的操作方便,测试之后改回"1")

3.1_ElasticSearch创建索引,增删改查文档

猜你喜欢

转载自blog.csdn.net/u010393325/article/details/83996325