1. 程式人生 > >java操作ElasticSearch(es)進行增刪查改操作

java操作ElasticSearch(es)進行增刪查改操作

 

 

有時間是要了解一下ES這個東西的~

-------------------------------------------------------------------------------------------------

  ElasticSearch(名稱太長,後面簡稱ES)作為一個搜尋引擎,目前可謂是如日中天,幾乎和solr齊駕並驅。關於他能做什麼,跟雲端計算有什麼關係,在此不再描述。但是ES的官方文件,特別是關於java的客戶端文件,真是少的可憐,甚至連個完整的增刪改的示例都沒有。在此,我就獻醜了。

在開始講解之前,還是先做個鋪墊,為了能夠有一個可以索引的模型,我們自定義了一個模型,暫時起個名稱叫LogModel吧,這個模型有各種資料型別,int,long,String,list,但千萬不要認為這是跟記錄日誌有關的一個模型。作為索引的一個最簡單模型。程式碼如下:

Java程式碼   收藏程式碼
  1. import java.util.ArrayList;  
  2. import java.util.List;  
  3. import java.util.Random;  
  4. import java.util.UUID;  
  5. /** 
  6.  * 瞎編的一個模型,跟日誌基本沒有關係 
  7.  * @author donlian 
  8.  */  
  9. public class LogModel {  
  10.     //主ID  
  11.     private long id;  
  12.     //次ID  
  13.     private int subId;  
  14.     /** 
  15.      * 系統名稱 
  16.      */  
  17.     private String systemName;  
  18.     private String host;  
  19.       
  20.     //日誌描述  
  21.     private String desc;  
  22.     private List<Integer> catIds;  
  23.     public LogModel(){  
  24.         Random random = new Random();  
  25.         this.id = Math.abs(random.nextLong());  
  26.         int subId = Math.abs(random.nextInt());  
  27.         this.subId = subId;  
  28.         List<Integer> list = new ArrayList<Integer>(5);  
  29.         for(int i=0;i<5;i++){  
  30.             list.add(Math.abs(random.nextInt()));  
  31.         }  
  32.         this.catIds = list;  
  33.         this.systemName = subId%1 == 0?"oa":"cms";  
  34.         this.host = subId%1 == 0?"10.0.0.1":"10.2.0.1";  
  35.         this.desc = "中文" + UUID.randomUUID().toString();  
  36.     }  
  37.     public LogModel(long id,int subId,String sysName,String host,String desc,List<Integer> catIds){  
  38.         this.id = id;  
  39.         this.subId = subId;  
  40.         this.systemName = sysName;  
  41.         this.host = host;  
  42.         this.desc = desc;  
  43.         this.catIds = catIds;  
  44.     }  
  45. ...//省去get,set方法  
  46. }  

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

Java程式碼   收藏程式碼
  1. public class ESUtils {  
  2.     private static ObjectMapper objectMapper = new ObjectMapper();  
  3.     public static String toJson(Object o){  
  4.         try {  
  5.             return objectMapper.writeValueAsString(o);  
  6.         } catch (JsonProcessingException e) {  
  7.             e.printStackTrace();  
  8.         }  
  9.         return "";  
  10.     }  
  11. }  

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

獲得一個ES客戶端API的程式碼如下:

Java程式碼   收藏程式碼
  1. Settings settings = ImmutableSettings.settingsBuilder()  
  2.                 //指定叢集名稱  
  3.                 .put("cluster.name", "elasticsearch")  
  4.                 //探測叢集中機器狀態  
  5.                 .put("client.transport.sniff", true).build();  
  6.         /* 
  7.          * 建立客戶端,所有的操作都由客戶端開始,這個就好像是JDBC的Connection物件 
  8.          * 用完記得要關閉 
  9.          */  
  10.         Client client = new TransportClient(settings)  
  11.         .addTransportAddress(new InetSocketTransportAddress("192.168.1.106", 9300));  

 Client物件,可以理解為資料庫的Connection物件。好了,準備工作完成,下面就開始增刪改查。

 Index(增加)

ES裡面的增加物件不叫什麼add,save等,叫index。但無論叫什麼名稱,反正就是向ES伺服器裡面加資料。上面說過一個物件轉json的工具類,其實ES的API中,是自帶構建json的工具類的。

Java程式碼   收藏程式碼
  1. import org.elasticsearch.action.index.IndexResponse;  
  2. import org.elasticsearch.client.Client;  
  3. import org.elasticsearch.client.transport.TransportClient;  
  4. import org.elasticsearch.common.settings.ImmutableSettings;  
  5. import org.elasticsearch.common.settings.Settings;  
  6. import org.elasticsearch.common.transport.InetSocketTransportAddress;  
  7.   
  8. import com.donlianli.es.ESUtils;  
  9. import com.donlianli.es.model.LogModel;  
  10. /** 
  11.  * 向ES新增索引物件 
  12.  * @author donlian 
  13.  */  
  14. public class IndexTest {  
  15.     public static void main(String[] argv){  
  16.         Settings settings = ImmutableSettings.settingsBuilder()  
  17.                 //指定叢集名稱  
  18.                 .put("cluster.name", "elasticsearch")  
  19.                 //探測叢集中機器狀態  
  20.                 .put("client.transport.sniff", true).build();  
  21.         /* 
  22.          * 建立客戶端,所有的操作都由客戶端開始,這個就好像是JDBC的Connection物件 
  23.          * 用完記得要關閉 
  24.          */  
  25.         Client client = new TransportClient(settings)  
  26.         .addTransportAddress(new InetSocketTransportAddress("192.168.1.106", 9300));  
  27.         String json = ESUtils.toJson(new LogModel());  
  28.         //在這裡建立我們要索引的物件  
  29.         IndexResponse response = client.prepareIndex("twitter", "tweet")  
  30.                 //必須為物件單獨指定ID  
  31.                 .setId("1")  
  32.                 .setSource(json)  
  33.                 .execute()  
  34.                 .actionGet();  
  35.         //多次index這個版本號會變  
  36.         System.out.println("response.version():"+response.version());  
  37.         client.close();  
  38.     }  
  39. }  

 執行這個程式碼,就向ES插入了一條資料,你執行兩遍,還是一條。ES根據你設定的ID來設定物件,如果沒有則插入,有則更新。每更新一次,對應的version加1.

好了,在次,使用以下命令,應該能夠查詢到一條記錄了。

Java程式碼   收藏程式碼
  1. curl -XGET 'http://localhost:9200/twitter/tweet/1'  

 

 delete(刪除)

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

程式碼如下:

Java程式碼   收藏程式碼
  1. import org.elasticsearch.action.delete.DeleteResponse;  
  2. import org.elasticsearch.client.Client;  
  3. import org.elasticsearch.client.transport.TransportClient;  
  4. import org.elasticsearch.common.settings.ImmutableSettings;  
  5. import org.elasticsearch.common.settings.Settings;  
  6. import org.elasticsearch.common.transport.InetSocketTransportAddress;  
  7.   
  8. import com.donlianli.es.ESUtils;  
  9.   
  10. public class DeleteTest {  
  11.     public static void main(String[] argv){  
  12.         Settings settings = ImmutableSettings.settingsBuilder()  
  13.                 //指定叢集名稱  
  14.                 .put("cluster.name", "elasticsearch")  
  15.                 //探測叢集中機器狀態  
  16.                 .put("client.transport.sniff", true).build();  
  17.         /* 
  18.          * 建立客戶端,所有的操作都由客戶端開始,這個就好像是JDBC的Connection物件 
  19.          * 用完記得要關閉 
  20.          */  
  21.         Client client = new TransportClient(settings)  
  22.         .addTransportAddress(new InetSocketTransportAddress("192.168.1.106", 9300));  
  23.         //在這裡建立我們要索引的物件  
  24.         DeleteResponse response = client.prepareDelete("twitter", "tweet", "1")  
  25.                 .execute().actionGet();  
  26.         System.out.println(response.getId());  
  27.         System.out.println(ESUtils.toJson(response.getHeaders()));  
  28.     }  
  29. }  

 

GET(查詢)

Java程式碼   收藏程式碼
  1. import org.elasticsearch.action.get.GetResponse;  
  2. import org.elasticsearch.client.Client;  
  3. import org.elasticsearch.client.transport.TransportClient;  
  4. import org.elasticsearch.common.settings.ImmutableSettings;  
  5. import org.elasticsearch.common.settings.Settings;  
  6. import org.elasticsearch.common.transport.InetSocketTransportAddress;  
  7.   
  8. public class GetTest {  
  9.     public static void main(String[] argv){  
  10.         Settings settings = ImmutableSettings.settingsBuilder()  
  11.                 //指定叢集名稱  
  12.                 .put("cluster.name", "elasticsearch")  
  13.                 //探測叢集中機器狀態  
  14.                 .put("client.transport.sniff", true).build();  
  15.         /* 
  16.          * 建立客戶端,所有的操作都由客戶端開始,這個就好像是JDBC的Connection物件 
  17.          * 用完記得要關閉 
  18.          */  
  19.         Client client = new TransportClient(settings)  
  20.         .addTransportAddress(new InetSocketTransportAddress("192.168.1.106", 9300));  
  21.         //在這裡建立我們要索引的物件  
  22.         GetResponse response = client.prepareGet("twitter", "tweet", "1")  
  23.                 .execute().actionGet();  
  24.         System.out.println("response.getId():"+response.getId());  
  25.         System.out.println("response.getSourceAsString():"+response.getSourceAsString());  
  26.     }  
  27. }  

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