Java High Level REST Client

1 连接es

package high.level.rest;

import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;

/**
 *
 * @Description: 获取Java High Level REST Client客户端
 * @author xdq
 * @date 2019年9月4日
 *
 */
public class InitDemo {

    public static RestHighLevelClient getClient() {

        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost", 9200, "http")));

        return client;
    }
}

2 新建

2.1 index

public boolean createIndex(){
        try (RestHighLevelClient client = InitDemo.getClient()){
            // creating index with name twitter
            CreateIndexRequest request = new CreateIndexRequest("twitter");
            // setting for shards and replication
            request.settings(Settings.builder()
                    // shards:分片,replicas:副本
                    .put("index.number_of_shards", 3)
                    .put("index.number_of_replicas", 2));
            // mapping:
            Map properties = new HashMap();
            properties.put("name", new HashMap(){
                {
                    put("type", "text");
                }
            });
            properties.put("address", new HashMap(){
                {
                    put("type", "text");
                }
            });

            Map jsonMap = new HashMap();
            Map mapping = new HashMap();
            // properties:type:type-name, e.g:type:text
            mapping.put("properties", properties);
            // type-name: info
            jsonMap.put("info", mapping);
            request.mapping("info", jsonMap);

            CreateIndexResponse createIndexResponse = client.indices()
                    .create(request);
            boolean acknowledged = createIndexResponse.isAcknowledged();
            return acknowledged;

        }catch(IOException e){
            e.printStackTrace();
            return false;
        }

    }

2.2 data

public String insertData(){
        try(RestHighLevelClient client = InitDemo.getClient()){
//            IndexRequest request = new IndexRequest("twitter", "info", "1");
            Map<String, Object> jsonMap = new HashMap<>();
            String insertStatus="test";
            jsonMap.put("name", "小三三");
            jsonMap.put("address", "沈阳");
            IndexRequest request = new IndexRequest("twitter", "info", "3")
                                                .source(jsonMap);

            IndexResponse indexResponse = client.index(request);

            String index = indexResponse.getIndex();
            String type = indexResponse.getType();
            String id = indexResponse.getId();
            long version = indexResponse.getVersion();
            if (indexResponse.getResult() == DocWriteResponse.Result.CREATED){
                insertStatus = "created data";
            } else if (indexResponse.getResult() == DocWriteResponse.Result.UPDATED){
                insertStatus = "updated data";
            }
            return insertStatus;
        }catch (IOException e){
            return "insert error";
        }
    }

3 删除

3.1 index

public boolean delIndex(){
        try(RestHighLevelClient client = InitDemo.getClient()){
            DeleteIndexRequest request = new DeleteIndexRequest("twitter");
            DeleteIndexResponse deleteIndexResponse = client.indices().delete(request);
            boolean acknowledged = deleteIndexResponse.isAcknowledged();
            return acknowledged;
        }catch (IOException e){
            return false;
        }

    }

3.2 data

4 修改

public String updateData(){
        try(RestHighLevelClient client = InitDemo.getClient()){
            Map<String, Object> jsonMap = new HashMap<>();
            jsonMap.put("name", "小黑嘿嘿");
            jsonMap.put("address", "沈阳");
            UpdateRequest request = new UpdateRequest("twitter", "info", "2")
                                        .doc(jsonMap);
            UpdateResponse updateResponse = client.update(request);
            String index = updateResponse.getIndex();
            String type = updateResponse.getType();
            String id = updateResponse.getId();
            long version = updateResponse.getVersion();
            String updateStatus="test";
            if (updateResponse.getResult() == DocWriteResponse.Result.CREATED){
                updateStatus = "created data";

            }else if (updateResponse.getResult() == DocWriteResponse.Result.UPDATED){
                updateStatus = "update data";

            }else if (updateResponse.getResult() == DocWriteResponse.Result.DELETED){
                updateStatus = "delete data";

            }else if (updateResponse.getResult() == DocWriteResponse.Result.NOOP){
                updateStatus = "no operation";
            }

            return updateStatus;

        }catch (IOException e){
            return "update error";
        }
    }

5 查询

5.1 查询全部

public String searchData(){
        try(RestHighLevelClient client = InitDemo.getClient()){
            // index and type
            SearchRequest searchRequest = new SearchRequest("twitter");
            searchRequest.types("info");

            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
            // query all
            searchSourceBuilder.query(QueryBuilders.matchAllQuery());
            searchRequest.source(searchSourceBuilder);

            SearchResponse searchResponse = client.search(searchRequest);
            RestStatus status = searchResponse.status();

            SearchHits hits = searchResponse.getHits();
            long totalHits = hits.getTotalHits();
            float maxScore = hits.getMaxScore();

            SearchHit[] searchHits = hits.getHits();
            for(SearchHit hit :searchHits){
                System.out.println("hit: "+hit);
                String index = hit.getIndex();
                String type = hit.getType();
                String id = hit.getId();
                float score = hit.getScore();
                String source = hit.getSourceAsString();
                System.out.println("index:"+index+","+"source:"+source);
            }

            return "search result";
        }catch (IOException e){
            return "search error";
        }
    }

5.2 匹配查询

  • match
public String searchData(){
        try(RestHighLevelClient client = InitDemo.getClient()){
            // index and type
            SearchRequest searchRequest = new SearchRequest("twitter");
            searchRequest.types("info");

            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
            // query in certain words
            searchSourceBuilder.query(QueryBuilders.matchQuery("name", "小三三"));
            searchRequest.source(searchSourceBuilder);
            SearchResponse searchResponse = client.search(searchRequest);
            RestStatus status = searchResponse.status();

            SearchHits hits = searchResponse.getHits();
            long totalHits = hits.getTotalHits();
            float maxScore = hits.getMaxScore();

            SearchHit[] searchHits = hits.getHits();
            for(SearchHit hit :searchHits){
                System.out.println("hit: "+hit);
                String index = hit.getIndex();
                String type = hit.getType();
                String id = hit.getId();
                float score = hit.getScore();
                String source = hit.getSourceAsString();
                System.out.println("index:"+index+","+"source:"+source);
            }

            return "search result";
        }catch (IOException e){
            return "search error";
        }
    }
  • term
public String searchData(){
        try(RestHighLevelClient client = InitDemo.getClient()){
            // index and type
            SearchRequest searchRequest = new SearchRequest("twitter");
            searchRequest.types("info");

            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
            // query in certain term
            searchSourceBuilder.query(QueryBuilders.termQuery("name", "小黄"));
            searchRequest.source(searchSourceBuilder);
            SearchResponse searchResponse = client.search(searchRequest);
            RestStatus status = searchResponse.status();

            SearchHits hits = searchResponse.getHits();
            long totalHits = hits.getTotalHits();
            float maxScore = hits.getMaxScore();

            SearchHit[] searchHits = hits.getHits();
            for(SearchHit hit :searchHits){
                System.out.println("hit: "+hit);
                String index = hit.getIndex();
                String type = hit.getType();
                String id = hit.getId();
                float score = hit.getScore();
                String source = hit.getSourceAsString();
                System.out.println("index:"+index+","+"source:"+source);
            }

            return "search result";
        }catch (IOException e){
            return "search error";
        }
    }

5.3 指定数量查询

public String searchData(){
        try(RestHighLevelClient client = InitDemo.getClient()){
            // index and type
            SearchRequest searchRequest = new SearchRequest("twitter");
            searchRequest.types("info");

            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
            // query all
            searchSourceBuilder.query(QueryBuilders.matchAllQuery());
            // show query number
            searchSourceBuilder.from(0);
            searchSourceBuilder.size(2);
            searchRequest.source(searchSourceBuilder);
            SearchResponse searchResponse = client.search(searchRequest);
            RestStatus status = searchResponse.status();

            SearchHits hits = searchResponse.getHits();
            long totalHits = hits.getTotalHits();
            float maxScore = hits.getMaxScore();

            SearchHit[] searchHits = hits.getHits();
            for(SearchHit hit :searchHits){
                System.out.println("hit: "+hit);
                String index = hit.getIndex();
                String type = hit.getType();
                String id = hit.getId();
                float score = hit.getScore();
                String source = hit.getSourceAsString();
                System.out.println("index:"+index+","+"source:"+source);
            }

            return "search result";
        }catch (IOException e){
            return "search error";
        }
    }

6 完整代码

6.1 项目结构

在这里插入图片描述

图 项目结构

6.2 maven

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.java.es</groupId>
    <artifactId>java.es</artifactId>
    <version>1.0-SNAPSHOT</version>
    <dependencies>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.10.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>2.10.0</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.8.0-beta2</version>
        </dependency>
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>transport</artifactId>
            <version>6.4.2</version>
        </dependency>
        <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>6.3.0</version>
        </dependency>
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-high-level-client</artifactId>
            <version>6.3.0</version>
        </dependency>
    </dependencies>
</project>

6.3 源码

6.3.1 InitDemo.java

连接ES.

package high.level.rest;

import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;

/**
 *
 * @Description: 获取Java High Level REST Client客户端
 * @author xdq
 * @date 2019年9月4日
 *
 */
public class InitDemo {

    public static RestHighLevelClient getClient() {

        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost", 9200, "http")));

        return client;
    }
}

6.3.2 HighAPITestV1.java

package high.level.rest;

import com.sun.org.apache.xml.internal.security.Init;
import org.apache.http.HttpHost;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.action.DocWriteRequest;
import org.elasticsearch.action.DocWriteResponse;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexResponse;
import org.elasticsearch.action.admin.indices.get.GetIndexRequest;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.support.replication.ReplicationResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentType;


import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;

import java.io.IOException;
import java.util.*;

public class HighAPITestV1 {
    public boolean existsIndex(){
        try(RestHighLevelClient client = InitDemo.getClient()){
            GetIndexRequest request = new GetIndexRequest();
            request.indices("twitter");
            boolean exists = client.indices().exists(request);
            return exists;
        }catch (IOException e){
            return false;
        }
    }

    public boolean createIndex(){
        try (RestHighLevelClient client = InitDemo.getClient()){
            // creating index with name twitter
            CreateIndexRequest request = new CreateIndexRequest("twitter");
            // setting for shards and replication
            request.settings(Settings.builder()
                    // shards:分片,replicas:副本
                    .put("index.number_of_shards", 3)
                    .put("index.number_of_replicas", 2));
            // mapping:
            Map properties = new HashMap();
            properties.put("name", new HashMap(){
                {
                    put("type", "text");
                }
            });
            properties.put("address", new HashMap(){
                {
                    put("type", "text");
                }
            });

            Map jsonMap = new HashMap();
            Map mapping = new HashMap();
            // properties:type:type-name, e.g:type:text
            mapping.put("properties", properties);
            // type-name: info
            jsonMap.put("info", mapping);
            request.mapping("info", jsonMap);

            CreateIndexResponse createIndexResponse = client.indices()
                    .create(request);
            boolean acknowledged = createIndexResponse.isAcknowledged();
            return acknowledged;

        }catch(IOException e){
            e.printStackTrace();
            return false;
        }

    }

    public String insertData(){
        try(RestHighLevelClient client = InitDemo.getClient()){
            Map<String, Object> jsonMap = new HashMap<>();
            String insertStatus="test";
            jsonMap.put("name", "小三三");
            jsonMap.put("address", "沈阳");
            IndexRequest request = new IndexRequest("twitter", "info", "1")
                                                .source(jsonMap);

            IndexResponse indexResponse = client.index(request);

            String index = indexResponse.getIndex();
            String type = indexResponse.getType();
            String id = indexResponse.getId();
            long version = indexResponse.getVersion();
            if (indexResponse.getResult() == DocWriteResponse.Result.CREATED){
                insertStatus = "created data";
            } else if (indexResponse.getResult() == DocWriteResponse.Result.UPDATED){
                insertStatus = "updated data";
            }
            return insertStatus;
        }catch (IOException e){
            return "insert error";
        }
    }

    public boolean delIndex(){
        try(RestHighLevelClient client = InitDemo.getClient()){
            DeleteIndexRequest request = new DeleteIndexRequest("twitter");
            DeleteIndexResponse deleteIndexResponse = client.indices().delete(request);
            boolean acknowledged = deleteIndexResponse.isAcknowledged();
            return acknowledged;
        }catch (IOException e){
            return false;
        }

    }

    public String updateData(){
        try(RestHighLevelClient client = InitDemo.getClient()){
            Map<String, Object> jsonMap = new HashMap<>();
            jsonMap.put("name", "小黑嘿嘿");
            jsonMap.put("address", "沈阳");
            UpdateRequest request = new UpdateRequest("twitter", "info", "1")
                                        .doc(jsonMap);
            UpdateResponse updateResponse = client.update(request);
            String index = updateResponse.getIndex();
            String type = updateResponse.getType();
            String id = updateResponse.getId();
            long version = updateResponse.getVersion();
            String updateStatus="test";
            if (updateResponse.getResult() == DocWriteResponse.Result.CREATED){
                updateStatus = "created data";

            }else if (updateResponse.getResult() == DocWriteResponse.Result.UPDATED){
                updateStatus = "update data";

            }else if (updateResponse.getResult() == DocWriteResponse.Result.DELETED){
                updateStatus = "delete data";

            }else if (updateResponse.getResult() == DocWriteResponse.Result.NOOP){
                updateStatus = "no operation";
            }

            return updateStatus;

        }catch (IOException e){
            return "update error";
        }
    }

    public String searchData(){
        try(RestHighLevelClient client = InitDemo.getClient()){
            // index and type
            SearchRequest searchRequest = new SearchRequest("twitter");
            searchRequest.types("info");

            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
            searchSourceBuilder.query(QueryBuilders.matchQuery("name", "小三三"));
            // query all
//            searchSourceBuilder.query(QueryBuilders.matchAllQuery());
            // show query number
//            searchSourceBuilder.from(0);
            searchSourceBuilder.size(1);
            searchRequest.source(searchSourceBuilder);


            SearchResponse searchResponse = client.search(searchRequest);
            RestStatus status = searchResponse.status();

            SearchHits hits = searchResponse.getHits();
            long totalHits = hits.getTotalHits();
            float maxScore = hits.getMaxScore();

            SearchHit[] searchHits = hits.getHits();
            for(SearchHit hit :searchHits){
                System.out.println("hit: "+hit);
                String index = hit.getIndex();
                String type = hit.getType();
                String id = hit.getId();
                float score = hit.getScore();
                String source = hit.getSourceAsString();
                System.out.println("index:"+index+","+"source:"+source);
            }

            return "search result";
        }catch (IOException e){
            return "search error";
        }
    }

    public static void main(String[] args) {
        System.out.println("Starting create index...");
        // initialize object
        HighAPITestV1 indexOperations = new HighAPITestV1();
        // index exists or not
        boolean existsIndex;
        existsIndex = indexOperations.existsIndex();
        if(existsIndex){
            System.out.println("Index already exists, please change index name and try again!");
        }else{
            // create index
            boolean createIndexStatus;
            createIndexStatus = indexOperations.createIndex();
            System.out.println("Create index status: "+createIndexStatus);
        }

        // delete index
//        boolean delIndexStatus;
//        delIndexStatus = indexOperations.delIndex();
//        System.out.println("Del index status: "+ delIndexStatus);
//        // insert data
//        String insertStatus;
//        insertStatus = indexOperations.insertData();
//        System.out.println("Insert data status: "+insertStatus);

//        // update data
//        String updateStatus;
//        updateStatus = indexOperations.updateData();
//        System.out.println("Update data status: "+updateStatus);
        // search data
        String searchStatus;
        searchStatus = indexOperations.searchData();
        System.out.println("Search data status: "+ searchStatus);

    }
}

7 小结

官方文档和博客交替看,有助理解及使用.


【参考文献】
[1]https://www.cnblogs.com/ginb/p/8716485.html
[2]https://www.cnblogs.com/zhaixingzhu/p/10565593.html
[3]https://www.cnblogs.com/leeSmall/p/9218779.html
[4]https://www.elastic.co/guide/en/elasticsearch/client/java-rest/current/java-rest-high.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

天然玩家

坚持才能做到极致

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值