Elasticsearch 文档API(7.3.0版本)

1. 创建文档

  A. 插件请求创建: POST  /索引名/_doc PUT  /索引名/_doc/自定义ID,注意索引不存在时会自动创建,_doc是路径部分固定值,详细介绍请前往官网地址:https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-index_.html

  B.  Java代码创建: IndexRequest请求,详细介绍请前往官网地址:https://www.elastic.co/guide/en/elasticsearch/client/java-rest/current/java-rest-high-document-index.html

package com.ruhuanxingyun.doc;

import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.http.HttpHost;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.rest.RestStatus;

import java.io.IOException;
import java.util.Date;

/**
 * @description: 创建文档
 * @author: rup
 * @date: Create in 2019/8/29 20:16
 * @company: ruhuanxingyun
 */
public class createDoc {

    public static void main(String[] args) {
        IndexRequest request = new IndexRequest("nginx_20190832");
        // 文档ID不设置会自动创建
        //request.id("ESgd4GwBL_dFtmUfcPwC");

        RestHighLevelClient client = null;
        try {
            XContentBuilder xContentBuilder = XContentFactory.jsonBuilder();
            xContentBuilder.startObject()
                                .timeField("@timestamp", DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"))
                                .field("mac", "00-11-22-33-44-55")
                                .field("sn", "1234567890")
                                .field("productType", "SUV3")
                                .field("status", 200)
                                .timeField("updateTime", DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"))
                            .endObject();
            request.source(xContentBuilder);
            // 设置操作类型type就必须设置id,否则报错org.elasticsearch.action.ActionRequestValidationException: Validation Failed: 1: an id must be provided if version type or value are set;
            //request.opType(DocWriteRequest.OpType.CREATE);

            client = new RestHighLevelClient(
                    RestClient.builder(new HttpHost("localhost", 9200, "http")));
            IndexResponse response = client.index(request, RequestOptions.DEFAULT);
            if (response.status() == RestStatus.CREATED) {
                System.out.println(String.format("创建文档ID为%s成功!", request.id()));
            } else {
                System.out.println(String.format("创建文档ID为%s失败!", request.id()));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                // 关闭资源
                if (client != null) {
                    client.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

 2. 获取文档

  A. 插件请求获取: GET  /索引名/_doc/文档ID,详细介绍请前往官网地址:https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-get.html

  B. Java代码获取: GetRequest请求,详细介绍请前往官网地址:https://www.elastic.co/guide/en/elasticsearch/client/java-rest/current/java-rest-high-document-get.html

 

package com.ruhuanxingyun.doc;

import org.apache.http.HttpHost;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;

import java.io.IOException;
import java.util.Map;

/**
 * @description: 获取文档
 * @author: rup
 * @date: Create in 2019/8/30 17:37
 * @company: ruhuanxingyun
 */
public class getDoc {

    public static void main(String[] args) {
        GetRequest request = new GetRequest("nginx_20190832", "ESgd4GwBL_dFtmUfcPwA");

        RestHighLevelClient client = null;
        try {
            client = new RestHighLevelClient(
                    RestClient.builder(new HttpHost("localhost", 9200, "http")));
            GetResponse response = client.get(request, RequestOptions.DEFAULT);
            if (response.isExists()) {
                Map<String, Object> map = response.getSource();
                map.forEach((key, value) -> {
                    System.out.println(String.format("字段名为%s,字段值为%s", key, value));
                });
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // 关闭资源
                if (client != null) {
                    client.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

 

3. 更新文档

  A. 插件请求更新: PUT /索引名/_doc/文档id    POST  /索引名/_update/文档id,详细介绍可前往官网地址:https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-update.html

 

  B. Java代码更新:UpdateRequest请求,详细介绍可前往官网地址:https://www.elastic.co/guide/en/elasticsearch/client/java-rest/current/java-rest-high-document-update.html

package com.ruhuanxingyun.doc;

import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.http.HttpHost;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.rest.RestStatus;

import java.io.IOException;
import java.util.Date;

/**
 * @description: 更新索引文档
 * @author: rup
 * @date: Create in 2019/8/30 12:50
 * @company: ruhuanxingyun
 */
public class updateDoc {

    public static void main(String[] args) {
        UpdateRequest request = new UpdateRequest("nginx_20190832", "ESgd4GwBL_dFtmUfcPwA");

        RestHighLevelClient client = null;
        try {
            XContentBuilder xContentBuilder = XContentFactory.jsonBuilder();
            xContentBuilder.startObject()
                    .timeField("@timestamp", DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"))
                    .field("mac", "00-11-22-33-44-77")
                    .field("sn", "1234567890123")
                    .timeField("updateTime", DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"))
                    .endObject();
            request.doc(xContentBuilder);
            client = new RestHighLevelClient(
                    RestClient.builder(new HttpHost("localhost", 9200, "http")));

            UpdateResponse response = client.update(request, RequestOptions.DEFAULT);
            if (response.status() == RestStatus.OK) {
                System.out.println(String.format("更新索引名为%s的文档id为%s成功!", response.getIndex(), response.getId()));
            } else {
                System.out.println(String.format("更新索引名为%s的文档id为%s失败!", response.getIndex(), response.getId()));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // 关闭资源
                if (client != null) {
                    client.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}

4. 删除文档

  A. 插件请求删除: DELETE /索引名/_doc/文档id,详细介绍可前往官网地址:https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-delete.html

  B. Java代码删除:DeleteRequest请求,详细介绍可前往官网地址:https://www.elastic.co/guide/en/elasticsearch/client/java-rest/current/java-rest-high-document-delete.html

package com.ruhuanxingyun.indexDoc;

import org.apache.http.HttpHost;
import org.elasticsearch.action.DocWriteResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;

import java.io.IOException;

/**
 * @description: 删除索引文档
 * @author: rup
 * @date: Create in 2019/8/30 12:36
 * @company: ruhuanxingyun
 */
public class NginxIndexDelete {

    public static void main(String[] args) {
        DeleteRequest request = new DeleteRequest("nginx_20190832", "Eyiy4GwBL_dFtmUfW_yE");

        RestHighLevelClient client = null;
        try {
            client = new RestHighLevelClient(
                    RestClient.builder(new HttpHost("localhost", 9200, "http")));
            DeleteResponse response = client.delete(request, RequestOptions.DEFAULT);
            if (response.getResult() == DocWriteResponse.Result.DELETED) {
                System.out.println(String.format("删除索引名为%s的文档id为%s成功!", response.getIndex(), response.getId()));
            } else {
                System.out.println(String.format("删除索引名为%s的文档id为%s失败!", response.getIndex(), response.getId()));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // 关闭资源
                if (client != null) {
                    client.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

  

转载于:https://www.cnblogs.com/ruhuanxingyun/p/11434385.html

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值