博主
258
258
258
258
专辑

第七节 ElasticSearch的文档编程

亮子 2021-06-17 01:59:16 7491 0 0 0

1、添加文档

    @Test
    public void addDocumentOne() throws IOException {
        Map<String, Object> jsonMap = new HashMap<>();
        jsonMap.put("name", "吕布");
        jsonMap.put("age", 23);
        jsonMap.put("gender", "男");
        jsonMap.put("work", "码农");
        IndexRequest indexRequest = new IndexRequest("tb_hero")
                .id("1").source(jsonMap);

        IndexResponse indexResponse = client.index(indexRequest, RequestOptions.DEFAULT);
    }

2、修改文档

    @Test
    public void updateDocumentOne() throws IOException {

        Map<String, Object> jsonMap = new HashMap<>();
        jsonMap.put("name", "赵云");
        jsonMap.put("work", "项目经理");
        UpdateRequest request = new UpdateRequest("tb_hero", "1")
                .doc(jsonMap);

        UpdateResponse updateResponse = client.update(
                request, RequestOptions.DEFAULT);
    }

3、判断文档是否存在

    @Test
    public void existDocument() throws IOException {
        GetRequest getRequest = new GetRequest("tb_hero","1");
        // Disable fetching _source.
        getRequest.fetchSourceContext(new FetchSourceContext(false));
        // Disable fetching stored fields.
        getRequest.storedFields("_none_");

        boolean exists = client.exists(getRequest, RequestOptions.DEFAULT);
        System.out.println(exists);
    }

4、删除文档

    @Test
    public void deleteDocument() throws IOException {
        // 删除文档
        DeleteRequest request = new DeleteRequest("tb_hero","1");
        DeleteResponse deleteResponse = client.delete(
                request, RequestOptions.DEFAULT);

        // 检查删除结果
        GetRequest getRequest = new GetRequest("tb_hero","1");
        // Disable fetching _source.
        getRequest.fetchSourceContext(new FetchSourceContext(false));
        // Disable fetching stored fields.
        getRequest.storedFields("_none_");

        boolean exists = client.exists(getRequest, RequestOptions.DEFAULT);
        System.out.println(exists);
    }