1. 程式人生 > >ElasticSearch6.X版本Java Api中文詳解(二)之Index Api解析

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();

僅供參考。