[Java]本地Java High-Level单应用调用ES-7.8.1简单方法

目录

查看ES官网:

下载访问ES

编写Java访问:

参考的文章:


查看ES官网:

目前官网是这个:Elastic Stack and Product Documentation | Elastic

如果要其他版本,往下找找,然后注意是不是ES,然后可以点击这里:

[Java]本地Java High-Level单应用调用ES-7.8.1简单方法_第1张图片

然后这个地方有关于watch的java-api,里面有一个警告

[Java]本地Java High-Level单应用调用ES-7.8.1简单方法_第2张图片

同时要注意ES版本,如果是ES8开始就将High-Level移除了,所以要es的Java依赖和ES版本尽量一致,如果对应不上版本号程序可能会出现各种问题。

[Java]本地Java High-Level单应用调用ES-7.8.1简单方法_第3张图片

 如果要官网的Java-api:high-leveld调用案例,需要到这个网址:Java REST Client [7.8] | Elastic


下载访问ES:

下载ES,配好Java环境,然后进去elasticsearch-7.8.1\bin目录,点击elasticsearch.bat,就立即启动es了,可以访问http://localhost:9200查看(注意启动端口和其他配置)

[Java]本地Java High-Level单应用调用ES-7.8.1简单方法_第4张图片

ES还可能修改下 conf/elasticsearch.yml,改下ssl,指定下端口,集群名称启动,不然java访问可能会要登录 ssl 等等的处理:

cluster.name: my-application
network.host: 127.0.0.1
http.port: 9200
discovery.seed_hosts: ["127.0.0.1", "[::1]"]
xpack.security.http.ssl.enabled: false
xpack.security.transport.ssl.enabled: false
xpack.security.enabled: false

编写Java访问:

为了直接能使用,就建立一个maven项目,然后把 ESUtilsTest 和 maven 依赖放进去即可

maven依赖:

如果要 log4j2 等等的,另外引入,然后 es 就会打印,现在因为测试需要,暂时不用大量日志影响测试的输出结果。

        
            com.alibaba
            fastjson
            1.2.66
        

        
        
            org.elasticsearch
            elasticsearch
            7.8.1
        
        
            org.elasticsearch.client
            elasticsearch-rest-high-level-client
            7.8.1
        

ESUtilsTest:

package com.example.estestproject;

import com.alibaba.fastjson.JSON;
import org.apache.http.HttpHost;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
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.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class ESUtilsTest {
    public static void main(String[] args) throws Exception {
        RestHighLevelClient resHLClient = new RestHighLevelClient(
                RestClient.builder(new HttpHost[]{new HttpHost("127.0.0.1", 9200, "http")}));

        // 这里创建结果集
        String keyid = "id";
        String key01 = "obj1-key01";
        String key02 = "obj1-key02";

        List> testList = new ArrayList<>();
        Map testObject01 = new HashMap<>();
        Map testObject02 = new HashMap<>();
        Map testObject03 = new HashMap<>();
        testObject01.put(keyid, "1");
        testObject01.put(key01, "v01");
        testObject01.put(key02, "v02");
        testObject02.put(keyid, "2");
        testObject02.put(key01, "v03");
        testObject02.put(key02, "v04");
        testObject03.put(keyid, "3");
        testObject03.put(key01, "v05");
        testObject03.put(key02, "v06");

        testList.add(testObject01);
        testList.add(testObject02);
        testList.add(testObject03);

        // 操作
        String idx = "index01";
        for(Map map : testList) {
            String id = String.valueOf(map.get("id"));
            IndexResponse indexResponse = addDoc(resHLClient, map, idx, id);
            System.out.println("添加后的index:" + indexResponse.toString());
            System.out.println("添加后的index状态:" + indexResponse.status());

            boolean exists = existDoc(resHLClient, idx, id);
            System.out.println("测试文档是否存在:" + exists);

            GetResponse docResponse = getDoc(resHLClient, idx, id);
            System.out.println("获取文档后返回值:" + docResponse.getSourceAsString());

            DeleteResponse delResponse = deleteDoc(resHLClient, idx, id);
            System.out.println("删除后:" + delResponse.toString());
            System.out.println("删除操作的状态:" + delResponse.status());
        }

        // 批量插入
        List> testList2 = new ArrayList<>();
        testList2.add(testObject02);

        BulkResponse bulk = batchDoc(resHLClient, testList, testList2, idx);
        System.out.println("批量操作后响应:" + bulk.toString());
        System.out.println("批量操作后的响应状态:" + bulk.status());
        // 返回false 代表没有失败
        System.out.println("批量操作后的状态:" + bulk.hasFailures());

        // 条件搜索
        SearchResponse searchResAll = queryAll(resHLClient);
        for (SearchHit hit : searchResAll.getHits().getHits()) {
            System.out.println("全量命中:" + hit.getSourceAsString());
        }

        // 包含的字段
        String[] includes = new String[]{keyid, key01};
        // 排除的字段
        String[] excludes = new String[]{key02};

        // match匹配 字段
        MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery(key01, "v01");
        SearchResponse searchRes = query(resHLClient, idx, matchQueryBuilder, includes, excludes);

        System.out.println("条件搜索命中:" + searchRes.getHits().getHits().length);
        for (SearchHit hit : searchRes.getHits().getHits()) {
            System.out.println("命中:" + hit.getSourceAsString());
        }
        resHLClient.close();
    }

    public static IndexResponse addDoc(RestHighLevelClient restHighLevelClient, Map map, String idx, String id) throws IOException {
        // 指定索引库
        IndexRequest indexRequest = new IndexRequest(idx);
        // 设置参数 id 超时时间 和数据源
        indexRequest.id(id).timeout(TimeValue.timeValueSeconds(500)).source(JSON.toJSONString(map), XContentType.JSON);
        // 执行请求
        return restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
    }

    public static boolean existDoc(RestHighLevelClient restHighLevelClient, String idx, String id) throws IOException {
        GetRequest flower = new GetRequest(idx, id);
        return restHighLevelClient.exists(flower, RequestOptions.DEFAULT);
    }

    public static GetResponse getDoc(RestHighLevelClient restHighLevelClient, String idx, String id) throws IOException {
        GetRequest flower = new GetRequest(idx, id);
        return restHighLevelClient.get(flower, RequestOptions.DEFAULT);
    }

    public static DeleteResponse deleteDoc(RestHighLevelClient restHighLevelClient, String idx, String id) throws IOException {
        DeleteRequest deleteRequest = new DeleteRequest(idx, id);
        return restHighLevelClient.delete(deleteRequest, RequestOptions.DEFAULT);
    }

    /**
     * 测试批量 增删改查都可以 只需要更换不同的Request就可以了
     * @throws IOException
     */
    public static BulkResponse batchDoc(RestHighLevelClient restHighLevelClient,
                                List> updResults,
                                List> delResults,
                                String idx) throws IOException {

        BulkRequest batchReq = new BulkRequest();
        for (Map map : updResults) {
            batchReq.add(new IndexRequest(idx)
                            .id(String.valueOf(map.get("id")))
                            .source(JSON.toJSONString(map), XContentType.JSON));
        }

        for (Map map : delResults) {
            batchReq.add( new DeleteRequest(idx).id( String.valueOf(map.get("id")) ) );
        }

        return restHighLevelClient.bulk(batchReq, RequestOptions.DEFAULT);
    }

    public static SearchResponse queryAll(RestHighLevelClient restHighLevelClient) throws IOException {
        SearchRequest searchReq = new SearchRequest();
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(QueryBuilders.matchAllQuery());
        searchReq.source(searchSourceBuilder);
        return restHighLevelClient.search(searchReq, RequestOptions.DEFAULT);
    }

    public static SearchResponse query(RestHighLevelClient restHighLevelClient,
                                       String idx,
                                       MatchQueryBuilder matchQueryBuilder,
                                       String[] includes,
                                       String[] excludes) throws IOException {

        SearchRequest searchReq = new SearchRequest(idx);

        // 构造搜索条件
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        // 加入条件
        sourceBuilder.query(matchQueryBuilder);
        sourceBuilder.fetchSource(includes, excludes);
        // 分页
        sourceBuilder.from(0);
        sourceBuilder.size(2);

        sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));

        searchReq.source(sourceBuilder);
        return restHighLevelClient.search(searchReq, RequestOptions.DEFAULT);
    }
}

测试结果:

[Java]本地Java High-Level单应用调用ES-7.8.1简单方法_第5张图片

 删除还可能有段刷新合并1秒左右延迟,此外es也会持久化,如果之前有其他数据存入,那么可能还会查出其他的数据。


参考的文章:

Java API 代码操作ElasticSearch7.6.1(2) - 云+社区 - 腾讯云

你可能感兴趣的:(Java,Elasticsearch,java)