ElasticSearch 基礎一

ElasticSearch(名稱太長,後面簡稱ES)做爲一個搜索引擎,目前可謂是如日中天,幾乎和solr齊駕並驅。關於他能作什麼,跟雲計算有什麼關系,在此再也不描述。可是ES的官方文檔,特別是關於java的客戶端文檔,真是少的可憐,甚至連個完整的增刪改的示例都沒有。在此,我就獻醜了。
在開始講解以前,還是先作個鋪墊,爲了能夠有一個能夠索引的模型,我們自定義了一個模型,暫時起個名稱叫LogModel吧,這個模型有各種數據類型,int,long,String,list,但千萬不要認爲這是跟記錄日誌有關的一個模型。做爲索引的一個最簡單模型。代碼以下:
Java代碼  收藏代碼
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的工具類,也很簡單,代碼:
Java代碼  收藏代碼
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的代碼以下:
Java代碼  收藏代碼
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));  
 Client對象,能夠理解爲數據庫的Connection對象。好了,準備工做完成,下面就開始增刪改查。
 Index(增長)
ES裏面的增長對象不叫什麼add,save等,叫index。但無論叫什麼名稱,反正就是向ES服務器裏面加數據。上面說過一個對象轉json的工具類,其實ES的API中,是自帶構建json的工具類的。
Java代碼  收藏代碼
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.
好了,在次,使用如下命令,應該能夠查詢到一條記錄了。
Java代碼  收藏代碼
curl -XGET 'http://localhost:9200/twitter/tweet/1'  
 
 delete(刪除)
有了增長的例子,刪除的例子也就好寫了。增長是prepareIndex,刪除是prepareDelete,查詢就是PrepareGet。
代碼以下:
Java代碼  收藏代碼
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(查詢)
Java代碼  收藏代碼
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());  
    }  
}  
 好了,增刪改查的代碼寫完。至於搜索,那是一個比較深刻的話題,我也在慢慢探索。我時間我會繼續寫下去。java

相關文章
相關標籤/搜索