【Elasticsearch】Java Client入門

序言

Elasticsearch(名稱太長,後面簡稱ES)作爲一個搜索引擎,目前可謂是如日中天,幾乎和solr齊駕並驅。關於他能做什麼,跟雲計算有什麼關係,在此不再描述。但是ES的官方文檔,特別是關於java的客戶端文檔,真是少的可憐,甚至連個完整的增刪改的示例都沒有。在此,我就獻醜了。
在開始講解之前,還是先做個鋪墊,爲了能夠有一個可以索引的模型,我們自定義了一個模型,暫時起個名稱叫LogModel吧,這個模型有各種數據類型,int,long,String,list,但千萬不要認爲這是跟記錄日誌有關的一個模型。作爲索引的一個最簡單模型。代碼如下:

import java.util.ArrayList;  
import java.util.List;  
import java.util.Random;  
import java.util.UUID;  
/** 
 * 瞎編的一個模型,跟日誌基本沒有關係 
 * @author donlian 
 */  
public class LogModel {  
    //主ID  
    private long id;  
    //次ID  
    private int subId;  
    /** 
     * 系統名稱 
     */  
    private String systemName;  
    private String host;  

    //日誌描述  
    private String desc;  
    private List<Integer> catIds;  
    public LogModel(){  
        Random random = new Random();  
        this.id = Math.abs(random.nextLong());  
        int subId = Math.abs(random.nextInt());  
        this.subId = subId;  
        List<Integer> list = new ArrayList<Integer>(5);  
        for(int i=0;i<5;i++){  
            list.add(Math.abs(random.nextInt()));  
        }  
        this.catIds = list;  
        this.systemName = subId%1 == 0?"oa":"cms";  
        this.host = subId%1 == 0?"10.0.0.1":"10.2.0.1";  
        this.desc = "中文" + UUID.randomUUID().toString();  
    }  
    public LogModel(long id,int subId,String sysName,String host,String desc,List<Integer> catIds){  
        this.id = id;  
        this.subId = subId;  
        this.systemName = sysName;  
        this.host = host;  
        this.desc = desc;  
        this.catIds = catIds;  
    }  
...//省去get,set方法  
} 

同時,因爲ES在索引的時候,一般都用json格式,因此,使用jackson定義了一個將對象轉化成json的工具類,也很簡單,代碼:

public class ESUtils {  
    private static ObjectMapper objectMapper = new ObjectMapper();  
    public static String toJson(Object o){  
        try {  
            return objectMapper.writeValueAsString(o);  
        } catch (JsonProcessingException e) {  
            e.printStackTrace();  
        }  
        return "";  
    }  
}

在開始進行操作ES服務器之前,我們必須得獲得ES的API,簡單介紹一下ES操作服務器的兩種方式,一種是使用Node方式,即本機也啓動一個ES,然後跟服務器的ES進行通信,這個node甚至還能存儲(奇怪,一般需要這樣的方式嗎?),另一種,就是下面我介紹的這一種,通過一個對象使用http協議跟服務器進行交互。
獲得一個ES客戶端API的代碼如下:

Settings settings = ImmutableSettings.settingsBuilder()  
                //指定集羣名稱  
                .put("cluster.name", "elasticsearch")  
                //探測集羣中機器狀態  
                .put("client.transport.sniff", true).build();  
        /* 
         * 創建客戶端,所有的操作都由客戶端開始,這個就好像是JDBC的Connection對象 
         * 用完記得要關閉 
         * 注意client裏面包含了連接池,對於client而言用完之後需要關閉,但是針對連接而言不需要關閉
         */  
        Client client = new TransportClient(settings)  
        .addTransportAddress(new InetSocketTransportAddress("192.168.1.106", 9300));  

Client對象,可以理解爲數據庫的Connection對象。好了,準備工作完成,下面就開始增刪改查。
Client更類似與連接池

Index(增加)

ES裏面的增加對象不叫什麼add,save等,叫index。但無論叫什麼名稱,反正就是向ES服務器裏面加數據。上面說過一個對象轉json的工具類,其實ES的API中,是自帶構建json的工具類的。

import org.elasticsearch.action.index.IndexResponse;  
import org.elasticsearch.client.Client;  
import org.elasticsearch.client.transport.TransportClient;  
import org.elasticsearch.common.settings.ImmutableSettings;  
import org.elasticsearch.common.settings.Settings;  
import org.elasticsearch.common.transport.InetSocketTransportAddress;  

import com.donlianli.es.ESUtils;  
import com.donlianli.es.model.LogModel;  
/** 
 * 向ES添加索引對象 
 * @author donlian 
 */  
public class IndexTest {  
    public static void main(String[] argv){  
        Settings settings = ImmutableSettings.settingsBuilder()  
                //指定集羣名稱  
                .put("cluster.name", "elasticsearch")  
                //探測集羣中機器狀態  
                .put("client.transport.sniff", true).build();  
        /* 
         * 創建客戶端,所有的操作都由客戶端開始,這個就好像是JDBC的Connection對象 
         * 用完記得要關閉 
         */  
        Client client = new TransportClient(settings)  
        .addTransportAddress(new InetSocketTransportAddress("192.168.1.106", 9300));  
        String json = ESUtils.toJson(new LogModel());  
        //在這裏創建我們要索引的對象  
        IndexResponse response = client.prepareIndex("twitter", "tweet")  
                //必須爲對象單獨指定ID  
                .setId("1")  
                .setSource(json)  
                .execute()  
                .actionGet();  
        //多次index這個版本號會變  
        System.out.println("response.version():"+response.version());  
        client.close();  
    }  
}  

運行這個代碼,就向ES插入了一條數據,你運行兩遍,還是一條。ES根據你設置的ID來設置對象,如果沒有則插入,有則更新。每更新一次,對應的version加1.
好了,在次,使用以下命令,應該能夠查詢到一條記錄了。

curl -XGET 'http://localhost:9200/twitter/tweet/1'  

delete(刪除)

有了增加的例子,刪除的例子也就好寫了。增加是prepareIndex,刪除是prepareDelete,查詢就是PrepareGet。
代碼如下:

import org.elasticsearch.action.delete.DeleteResponse;  
import org.elasticsearch.client.Client;  
import org.elasticsearch.client.transport.TransportClient;  
import org.elasticsearch.common.settings.ImmutableSettings;  
import org.elasticsearch.common.settings.Settings;  
import org.elasticsearch.common.transport.InetSocketTransportAddress;  

import com.donlianli.es.ESUtils;  

public class DeleteTest {  
    public static void main(String[] argv){  
        Settings settings = ImmutableSettings.settingsBuilder()  
                //指定集羣名稱  
                .put("cluster.name", "elasticsearch")  
                //探測集羣中機器狀態  
                .put("client.transport.sniff", true).build();  
        /* 
         * 創建客戶端,所有的操作都由客戶端開始,這個就好像是JDBC的Connection對象 
         * 用完記得要關閉 
         */  
        Client client = new TransportClient(settings)  
        .addTransportAddress(new InetSocketTransportAddress("192.168.1.106", 9300));  
        //在這裏創建我們要索引的對象  
        DeleteResponse response = client.prepareDelete("twitter", "tweet", "1")  
                .execute().actionGet();  
        System.out.println(response.getId());  
        System.out.println(ESUtils.toJson(response.getHeaders()));  
    }  
}  

GET(查詢)

import org.elasticsearch.action.get.GetResponse;  
import org.elasticsearch.client.Client;  
import org.elasticsearch.client.transport.TransportClient;  
import org.elasticsearch.common.settings.ImmutableSettings;  
import org.elasticsearch.common.settings.Settings;  
import org.elasticsearch.common.transport.InetSocketTransportAddress;  

public class GetTest {  
    public static void main(String[] argv){  
        Settings settings = ImmutableSettings.settingsBuilder()  
                //指定集羣名稱  
                .put("cluster.name", "elasticsearch")  
                //探測集羣中機器狀態  
                .put("client.transport.sniff", true).build();  
        /* 
         * 創建客戶端,所有的操作都由客戶端開始,這個就好像是JDBC的Connection對象 
         * 用完記得要關閉 
         */  
        Client client = new TransportClient(settings)  
        .addTransportAddress(new InetSocketTransportAddress("192.168.1.106", 9300));  
        //在這裏創建我們要索引的對象  
        GetResponse response = client.prepareGet("twitter", "tweet", "1")  
                .execute().actionGet();  
        System.out.println("response.getId():"+response.getId());  
        System.out.println("response.getSourceAsString():"+response.getSourceAsString());  
    }  
}  

好了,增刪改查的代碼寫完。至於搜索,那是一個比較深入的話題,我也在慢慢探索。我時間我會繼續寫下去。

對於ES的Java Client我覺得更多的是類似於JDBC連接池的概念。你不能在程序裏不停的new client,所有的連接都可以使用同一個client來操作,類似於我們在JDBC裏每一次的查詢都會使用同一個連接池。極端情況下不斷的實例化client會導致服務器達到最大連接數,從而是應用報錯。根據經驗,默認情況下client保留的連接數是15。

如有不同見解,歡迎留言討論!

原文出自http://donlianli.iteye.com/blog/1902238

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章