ElasticSearch High Level REST API【1】文档基本操作

获取ES客户端

ES的提供了四种Java客户端,分别为节点客户端(node client)、传输客户端(Transport Client)、低级REST客户端、高级REST客户端。

节点客户端作为集群节点的一部分,在集群节点较多的情况下会影响集群的反应速度。

传输客户端客户端虽然实现了和集群的解耦,相对节点更“轻”,但是会在ES7.0或8.0之后被移除,被“高级Rest客户端”所取代。

在此截取了ES官方文档对此的说明。因此学习“高级RestAPI”的使用还是很有必要的。

如下为ES 客户端的创建:

@Configuration
public class ElasticClient {
    private String host = "10.1.59.101";
    private int port = 9200;

    /**
     * 获取Rest高级客户端
     * @return
     */
    @Bean
    public RestHighLevelClient getRestHighLevelClient(){
        RestClientBuilder builder = RestClient.builder(new HttpHost(host, port));
        return new RestHighLevelClient(builder);
    }

    /**
     * 获取Rest低级客户端
     * @return
     */
    @Bean
    public RestClient getRestClient(){
        RestClient build = RestClient.builder(new HttpHost(host)).build();
        return build;
    }

下面介绍下ES在Java中基本的文档增删改查操作

索引操作

索引即我们的新增操作,ES提供了三种形式的索引,分别为通过Json字符串、Map集合、XContentBuilder实现索引操作

示例如下:

public void save(User user) {
        RestHighLevelClient client = elasticClient.getRestHighLevelClient();
        //Json字符串作为数据源
        IndexRequest indexRequest1 = new IndexRequest(
                "02",
                "book",
                "3");
        String jsonString = "{" +
                "\"name\":\"生命的诞生\"," +
                "\"type\":\"科学\"," +
                "\"price\":\"170\"" +
                "}";

        indexRequest1.source(jsonString, XContentType.JSON);
        //Map集合作为数据源
        Map jsonMap = new HashMap<>();
        jsonMap.put("user", "userByMap");
        jsonMap.put("postDate", new Date());
        jsonMap.put("message", "messageByMap");
        IndexRequest indexRequest2 = new IndexRequest("posts", "doc", "34")
                .source(jsonMap);
        //XContentBuilder作为数据源
        XContentBuilder builder = null;
        try {
            builder = XContentFactory.jsonBuilder();
            builder.startObject();
            builder.field("user", "userXXX");
            builder.timeField("postDate", new Date());
            builder.field("message", "messageXXX");
            builder.endObject();
        } catch (IOException e) {
            e.printStackTrace();
        }
        IndexRequest indexRequest3 = new IndexRequest("posts", "doc", "1")
                .source(builder);
        try {
            IndexResponse indexResponse1 = client.index(indexRequest1, RequestOptions.DEFAULT);
            client.index(indexRequest2, RequestOptions.DEFAULT);
            client.index(indexRequest3, RequestOptions.DEFAULT);
            client.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

查询

根据索引、类型、ID 查询文档,示例如下

public void get(){
        RestHighLevelClient client = elasticClient.getRestHighLevelClient();
        GetRequest getRequest = new GetRequest(
                "posts",
                "doc",
                "1");
        try {
            GetResponse getResponse = client.get(getRequest, RequestOptions.DEFAULT);
            client.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

删除

public void delete(){
        RestHighLevelClient client = elasticClient.getRestHighLevelClient();
        DeleteRequest deleteRequest = new DeleteRequest("02", "book", "2");
        deleteRequest.timeout(TimeValue.timeValueMinutes(10));
        deleteRequest.setRefreshPolicy(WriteRequest.RefreshPolicy.WAIT_UNTIL);
        try {
            client.delete(deleteRequest, RequestOptions.DEFAULT);
            client.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

更新

public void update(User user){
        RestHighLevelClient client = elasticClient.getRestHighLevelClient();
        UpdateRequest updateRequest = new UpdateRequest("posts", "doc", "35");
        Map map = new HashMap<>();
        map.put("message", "message_update");
        map.put("user", "user_update");
        updateRequest.doc(user.toJsonString(), XContentType.JSON);
        try {
            client.update(updateRequest, RequestOptions.DEFAULT);
            client.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

查询文档是否存在

public void exists() {
        RestHighLevelClient client = elasticClient.getRestHighLevelClient();
        GetRequest getRequest = new GetRequest("posts","doc","33");
        GetResponse getResponse = null;
        try {
            getRequest.fetchSourceContext(new FetchSourceContext(false));//禁用获取 _source字段
            getRequest.storedFields("_none_");//禁用获取存储字段。
            boolean exists = client.exists(getRequest, RequestOptions.DEFAULT);
            client.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

 

Bulk批量操作

bulk可以批量执行多条操作语句,bulk支持批量操作不同的命令,例如批量更新和删除

public void bulk(User user){
        RestHighLevelClient client = elasticClient.getRestHighLevelClient();
        User user2 = new User();
        user2.setName("周大福");
        user2.setAge(211);
        user2.setPosition("珠宝");
        BulkRequest bulkRequest = new BulkRequest();
        IndexRequest indexRequest1 = new IndexRequest("posts", "doc", "41").source(user.toJsonString(), XContentType.JSON);
        IndexRequest indexRequest2 = new IndexRequest("posts", "doc", "42").source(user2.toJsonString(), XContentType.JSON);
        DeleteRequest deleteRequest = new DeleteRequest("01", "law", "3");
        bulkRequest.add(indexRequest1);
        bulkRequest.add(indexRequest2);
        bulkRequest.add(deleteRequest);
        try {
            client.bulk(bulkRequest, RequestOptions.DEFAULT);
            client.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

 

posted @ 2019-01-20 22:14  有追求的程序员  阅读(3749)  评论(0编辑  收藏  举报