java操作ElasticSearch(es)進行增刪查改操作
有時間是要了解一下ES這個東西的~
-------------------------------------------------------------------------------------------------
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的工具類,也很簡單,程式碼:
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());
- }
- }
好了,增刪改查的程式碼寫完。至於搜尋,那是一個比較深入的話題,我也在慢慢探索。我時間我會繼續寫下去。