天天看點

[ElasticSearch]Java API 之 索引文檔 (Index API)

版權聲明:本文為部落客原創文章,未經部落客允許不得轉載。 https://blog.csdn.net/SunnyYoona/article/details/52806082

Index API 允許我們存儲一個JSON格式的文檔,使資料可以被搜尋。文檔通過index、type、id唯一确定。我們可以自己提供一個id,或者也使用Index API 為我們自動生成一個。

這裡有幾種不同的方式來産生JSON格式的文檔(document):

(1)手動方式,使用原生的byte[]或者String

(2)使用Map方式,會自動轉換成與之等價的JSON

(3)使用第三方庫來序列化beans,如Jackson

(4)使用内置的幫助類 XContentFactory.jsonBuilder()

1. 手動方式
  1.    /**

  2.     *  手動方式 産生JSON 索引文檔

  3.     * @param client

  4.     * @param index

  5.     * @param type

  6.     * @param id

  7.     * @param json

  8.     */

  9.    public static boolean indexDocByJSON(Client client, String index, String type, String id, String json) {

  10.        // Index

  11.        IndexRequestBuilder indexRequestBuilder = client.prepareIndex();

  12.        indexRequestBuilder.setIndex(index);

  13.        indexRequestBuilder.setType(type);

  14.        indexRequestBuilder.setId(id);

  15.        indexRequestBuilder.setSource(json);

  16.        indexRequestBuilder.setTTL(8000);

  17.        // 執行

  18.        IndexResponse indexResponse = indexRequestBuilder.get();

  19.        return indexResponse.isCreated();

  20.    }

測試,下面代碼存儲梅西資訊到索引為football-index,類型為football-type,id為1的文檔中:

  1.    @Test

  2.    public void indexDocByJSON() throws Exception {

  3.        String index = "football-index";

  4.        String type = "football-type";

  5.        String id = "1";

  6.        String json = "{" +

  7.                "\"club\":\"巴薩羅那\"," +

  8.                "\"country\":\"阿根廷\"," +

  9.                "\"name\":\"梅西\"" +

  10.                "}";

  11.        boolean result = IndexDocAPI.indexDocByJSON(client, index, type , id,  json);

  12.        logger.info("--------- indexDocByJSON {}", result);

  13.    }

2. Map方式
  1.    /**

  2.     *  使用Map 産生JSON 索引文檔

  3.     * @param client

  4.     * @param index

  5.     * @param type

  6.     * @param id

  7.     */

  8.    public static boolean indexDocByMap(Client client, String index, String type, String id, Map<String, Object> map) {

  9.        // Index

  10.        IndexRequestBuilder indexRequestBuilder = client.prepareIndex();

  11.        indexRequestBuilder.setIndex(index);

  12.        indexRequestBuilder.setType(type);

  13.        indexRequestBuilder.setId(id);

  14.        indexRequestBuilder.setSource(map);

  15.        indexRequestBuilder.setTTL(8000);

  16.        // 執行

  17.        IndexResponse indexResponse = indexRequestBuilder.get();

  18.        return indexResponse.isCreated();

  19.    }

測試,下面代碼存儲穆勒資訊到索引為football-index,類型為football-type,id為2的文檔中:

  1.    @Test

  2.    public void indexDocByMap() throws Exception {

  3.        String index = "football-index";

  4.        String type = "football-type";

  5.        String id = "2";

  6.        Map<String, Object> map = Maps.newHashMap();

  7.        map.put("name", "穆勒");

  8.        map.put("club", "拜仁慕尼黑俱樂部");

  9.        map.put("country", "德國");

  10.        boolean result = IndexDocAPI.indexDocByMap(client, index, type , id,  map);

  11.        logger.info("--------- indexDocByMap {}", result);

  12.    }

3.  序列化方式
  1.    /**

  2.     * 利用Json序列化 産生JSON 索引文檔

  3.     *

  4.     * @param client

  5.     * @param index

  6.     * @param type

  7.     * @param id

  8.     */

  9.    public static boolean indexDocByBean(Client client, String index, String type, String id, Object bean) {

  10.        // Bean轉換為位元組

  11.        ObjectMapper mapper = new ObjectMapper();

  12.        byte[] json;

  13.        try {

  14.            json = mapper.writeValueAsBytes(bean);

  15.        } catch (JsonProcessingException e) {

  16.            logger.error("---------- json 轉換失敗 Bean:{}", bean.toString());

  17.            return false;

  18.        }

  19.        // Index

  20.        IndexRequestBuilder indexRequestBuilder = client.prepareIndex();

  21.        indexRequestBuilder.setIndex(index);

  22.        indexRequestBuilder.setType(type);

  23.        indexRequestBuilder.setId(id);

  24.        indexRequestBuilder.setSource(json);

  25.        indexRequestBuilder.setTTL(8000);

  26.        // 執行

  27.        IndexResponse response = indexRequestBuilder.get();

  28.        return response.isCreated();

  29.    }

測試,下面代碼存儲卡卡資訊到索引為football-index,類型為football-type,id為3的文檔中:

  1. @Test

  2. public void indexDocByBean() throws Exception {

  3. String index = "football-index";

  4. String type = "football-type";

  5. String id = "3";

  6. FootballPlayer footballPlayer = new FootballPlayer();

  7. footballPlayer.setName("卡卡");

  8. footballPlayer.setClub("奧蘭多城俱樂部");

  9. footballPlayer.setCountry("巴西");

  10. boolean result = IndexDocAPI.indexDocByBean(client, index, type , id, footballPlayer);

  11. logger.info("--------- indexDocByBean {}", result);

  12. }

4.  XContentBuilder幫助類方式

ElasticSearch提供了一個内置的幫助類XContentBuilder來産生JSON文檔

  1.    /**

  2.     * 使用幫助類XContentBuilder 産生JSON 索引文檔

  3.     * @param client

  4.     * @param index

  5.     * @param type

  6.     * @param id

  7.     * @param xContentBuilder

  8.     * @return

  9.     */

  10.    public static boolean indexDocByXContentBuilder(Client client, String index, String type, String id, XContentBuilder xContentBuilder) {

  11.        // Index

  12.        IndexRequestBuilder indexRequestBuilder = client.prepareIndex();

  13.        indexRequestBuilder.setIndex(index);

  14.        indexRequestBuilder.setType(type);

  15.        indexRequestBuilder.setId(id);

  16.        indexRequestBuilder.setSource(xContentBuilder);

  17.        indexRequestBuilder.setTTL(8000);

  18.        // 執行

  19.        IndexResponse response = indexRequestBuilder.get();

  20.        return response.isCreated();

  21.    }

測試,下面代碼存儲托雷斯資訊到索引為football-index,類型為football-type,id為4的文檔中:

  1.    @Test

  2.    public void indexDocByXContentBuilder() throws Exception {

  3.        String index = "football-index";

  4.        String type = "football-type";

  5.        String id = "4";

  6.        XContentBuilder xContentBuilder;

  7.        try {

  8.            xContentBuilder = XContentFactory.jsonBuilder();

  9.            xContentBuilder

  10.                    .startObject()

  11.                        .field("name", "托雷斯")

  12.                        .field("club", "馬德裡競技俱樂部")

  13.                        .field("country", "西班牙")

  14.                    .endObject();

  15.        } catch (IOException e) {

  16.            logger.error("----------indexDocByXContentBuilder create xContentBuilder failed", e);

  17.            return;

  18.        }

  19.        boolean result = IndexDocAPI.indexDocByXContentBuilder(client, index, type, id, xContentBuilder);

  20.        logger.info("--------- indexDocByXContentBuilder result {}", result);

  21.    }

備注:

你還可以通過startArray(string)和endArray()方法添加數組。.field()方法可以接受多種對象類型。你可以給它傳遞數字、日期、甚至其他XContentBuilder對象。

參考:

https://www.elastic.co/guide/en/elasticsearch/client/java-api/current/java-docs-index.html#java-docs-index-generate