1. 程式人生 > >ES 2.4 java API document APIs

ES 2.4 java API document APIs

暫時記錄的只是我看的比較懂得

TransportClient  客戶端的建立

Settings settings = Settings.settingsBuilder()
        .put("cluster.name", "myClusterName").build();
TransportClient client = TransportClient.builder().settings(settings).build();
//Add transport addresses and do something with the client...

sniff 一般也是開啟的,迴圈查詢port陣列上的節點
Settings settings = Settings.settingsBuilder()
        .put("client.transport.sniff", true).build();
TransportClient client = TransportClient.builder().settings(settings).build();

index API index接收的資料形式是json,而轉換成json最基本的資料是byte[],所以只要把string、map等等資料型別轉換成byte[],就有辦法轉換成json形式。
String json = "{" +
        "\"user\":\"kimchy\"," +
        "\"postDate\":\"2013-01-30\"," +
        "\"message\":\"trying out Elasticsearch\"" +
    "}";

IndexResponse response = client.prepareIndex("twitter", "tweet")
        .setSource(json)
        .get();

也可以利用json builder建立json字串
import static org.elasticsearch.common.xcontent.XContentFactory.*;

XContentBuilder builder = jsonBuilder()
    .startObject()
        .field("user", "kimchy")
        .field("postDate", new Date())
        .field("message", "trying out Elasticsearch")
    .endObject()
get API  setOperationThreaded是否應用於同步 查到的結果也是json形式

GetResponse response = client.prepareGet("twitter", "tweet", "1")
        .setOperationThreaded(false)
        .get();
delete API
DeleteResponse response = client.prepareDelete("twitter", "tweet", "1")
        .setOperationThreaded(false)
        .get();
bulk API 批量操作 builder.add.get
import static org.elasticsearch.common.xcontent.XContentFactory.*;

BulkRequestBuilder bulkRequest = client.prepareBulk();

// either use client#prepare, or use Requests# to directly build index/delete requests
bulkRequest.add(client.prepareIndex("twitter", "tweet", "1")
        .setSource(jsonBuilder()
                    .startObject()
                        .field("user", "kimchy")
                        .field("postDate", new Date())
                        .field("message", "trying out Elasticsearch")
                    .endObject()
                  )
        );

bulkRequest.add(client.prepareIndex("twitter", "tweet", "2")
        .setSource(jsonBuilder()
                    .startObject()
                        .field("user", "kimchy")
                        .field("postDate", new Date())
                        .field("message", "another post")
                    .endObject()
                  )
        );

BulkResponse bulkResponse = bulkRequest.get();
if (bulkResponse.hasFailures()) {
    // process failures by iterating through each bulk response item
}