ElasticSearch6.X版本Java Api中文詳解(二)之Index Api解析

Inde API允許將類型化JSON文檔索引到特定索引中,並使其可搜索。

生成JSON文檔有幾種不同的方法:

1.手動(也就是自己使用)使用本機字節[]或作爲字符串。

2.使用將自動轉換爲其JSON等效的映射。

3.使用第三方庫序列化您的bean,如Jackson。

4.使用內置的助手XContentFactory.jsonBuilder()

在內部,每個類型轉換爲byte[](因此一個字符串被轉換爲一個字節[])。因此,如果對象已經在這個表單中,那麼就使用它。jsonBuilder是高度優化的JSON生成器,它直接構造一個字節[]。

這裏沒有什麼真正困難的,但是注意您必須按照日期格式編碼日期。

String json = "{" +
        "\"user\":\"kimchy\"," +
        "\"postDate\":\"2013-01-30\"," +
        "\"message\":\"trying out Elasticsearch\"" +
    "}";

使用Map

Map是一個鍵:值對集合。它表示一個JSON結構:

Map<String, Object> json = new HashMap<String, Object>();
json.put("user","kimchy");
json.put("postDate",new Date());
json.put("message","trying out Elasticsearch");

序列化你beans

您可以使用Jackson將您的beans序列化爲JSON。請將Jackson Databind添加到您的項目中。然後,您可以使用ObjectMapper來序列化您的bean.

import com.fasterxml.jackson.databind.*;

// instance a json mapper
ObjectMapper mapper = new ObjectMapper(); // create once, reuse

// generate json
byte[] json = mapper.writeValueAsBytes(yourbeaninstance);

使用Elasticsearch helpers

Elasticsearch提供了內置的幫助來生成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()

注意,您還可以使用startArray(String)和endArray()方法添加數組。順便說一下,字段方法接受許多對象類型。您可以直接通過數字、日期甚至其他XContentBuilder對象。

如果需要查看生成的JSON內容,可以使用string()方法。

String json = builder.string();
下面的示例將一個JSON文檔索引爲一個名爲twitter的索引,其類型爲tweet, id爲1:
import static org.elasticsearch.common.xcontent.XContentFactory.*;

IndexResponse response = client.prepareIndex("twitter", "tweet", "1")
        .setSource(jsonBuilder()
                    .startObject()
                        .field("user", "kimchy")
                        .field("postDate", new Date())
                        .field("message", "trying out Elasticsearch")
                    .endObject()
                  )
        .get();

請注意,您還可以將文檔作爲JSON字符串進行索引,而不必給出ID:

String json = "{" +
        "\"user\":\"kimchy\"," +
        "\"postDate\":\"2013-01-30\"," +
        "\"message\":\"trying out Elasticsearch\"" +
    "}";

IndexResponse response = client.prepareIndex("twitter", "tweet")
        .setSource(json, XContentType.JSON)
        .get();
IndexResponse對象會給你一個報告:
// Index name
String _index = response.getIndex();
// Type name
String _type = response.getType();
// Document ID (generated or not)
String _id = response.getId();
// Version (if it's the first time you index this document, you will get: 1)
long _version = response.getVersion();
// status has stored current instance statement.
RestStatus status = response.status();

僅供參考。

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