1. 程式人生 > >第3講:3.1 ElasticSearch建立索引,增刪改查文件

第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建立索引,增刪改查文件