天天看点

[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