Elasticsearch 文档Doucment API(7.5.0)

1. 创建文档

  A. 插件:官网Index API

     POST  /索引名/_doc PUT  /索引名/_doc/自定义ID,注意索引不存在时会自动创建,_doc是路径部分固定值;

  B. 代码:官网Index API

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: ruphie
 * @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 API

    GET  /索引名/_doc/文档ID

  B. Java: 官网Get API

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. 插件:官网Upate API

    PUT /索引名/_doc/文档id    POST  /<index>/_update/<_id>

  B. 更新文档一部分字段  

POST /<index>/_update/<_id>
{
   "doc": {
        "user": {
             "ip": "127.0.0.1"
        }
    } 
}

  C. Java:官网Update API

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 API

    DELETE /索引名/_doc/文档id

  B. Java:官网Delete API

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

  

 

5. 批量新增/修改/删除文档

   A. shell脚本导入:curl -s -u elastic:123456 -XPOST "http://localhost:9200/ip/_bulk" -H 'Content-Type: application/json' --data-binary '@./rhxy.txt'

      注意:书写文件时必须@开头

   B. 插件:官网Bulk API

   C. 代码:官网Bulk API

 

posted @ 2019-08-30 12:35  如幻行云  阅读(5869)  评论(0编辑  收藏  举报