ElasticSearch学习随笔之java api 操作

ElasticSearch

1、ElasticSearch学习随笔之基础介绍
2、ElasticSearch学习随笔之简单操作
3、ElasticSearch学习随笔之java api 操作
4、ElasticSearch学习随笔之SpringBoot Starter 操作
5、ElasticSearch学习随笔之嵌套操作
6、ElasticSearch学习随笔之分词算法
7、ElasticSearch学习随笔之高级检索
8、ELK技术栈介绍
9、Logstash部署与使用
10、ElasticSearch 7.x 版本使用 BulkProcessor 实现批量添加数据
11、ElasticSearch 8.x 弃用了 High Level REST Client,移除了 Java Transport Client,推荐使用 Elasticsearch Java API
12、ElasticSearch 8.x 使用 snapshot(快照)进行数据迁移
13、ElasticSearch 8.x 版本如何使用 SearchRequestBuilder 检索
14、ElasticSearch 8.x 使用 High Level Client 以 HTTPS 方式链接,SSL 证书、主机名验证器 各是什么,如何忽略
15、ElasticSearch 8.x 创建父子文档,用Join类型字段以及用has_child、has_parent 检索

ElasticSearch,创始人 Shay Banon(谢巴农)
本文主讲 ElasticSearch Java api 调用操作。



前言

本文主要对ElasticSearch 通过java api 操作基础案例。
示例代码已经提交到码云


一、引入ES Client jar包

<dependency>
 	<groupId>org.elasticsearch.client</groupId>
    <artifactId>elasticsearch-rest-high-level-client</artifactId>
    <version>6.7.2</version>
</dependency>

二、操作案例

2.0 实例化 ES Client 客户端

private static final String HOSTNAME = "192.168.*.*";
   private static final int PORT = 9200;
   private static final RestHighLevelClient client = getClient();
   public static RestHighLevelClient getClient(){
       RestClientBuilder builder = RestClient.builder(
               new HttpHost(HOSTNAME, PORT, "http")
       );
       RestHighLevelClient client = new RestHighLevelClient(builder);
       return client;
   }

2.1 增

public static void addIndex(RestHighLevelClient client) throws IOException {
        /*初始化 查询请求操作,指定操作 index 名称*/
        IndexRequest indexRequest = new IndexRequest(INDEX_NAME);
        /*实例化数据*/
        Tender tender = new Tender("鉴定药敏分析仪"
                ,"四川国际招标有限责任公司"
                ,"招标结果"
                ,"5");
        String json = JSONObject.toJSONString(tender);
        /*设置 类型,7.x 不用设置,默认是 _doc*/
        indexRequest.type("data");
        /*数据转换成  json 添加进去*/
        indexRequest.source(json, XContentType.JSON);
        /*添加索引 */
        client.index(indexRequest, RequestOptions.DEFAULT);
        client.close();
    }

2.2 删

public static void deleteById(String id) throws IOException {
        /*初始化 get 请求*/
        GetRequest request = new GetRequest(INDEX_NAME, TYPE, id);
        /*判断是否存在数据,用 id 查询*/
        boolean exists = client.exists(request, RequestOptions.DEFAULT);
        if(exists){
            /*初始化 Delete 请求*/
            DeleteRequest deleteRequest = new DeleteRequest(INDEX_NAME, TYPE, id);
            /*执行 delete 操作*/
            client.delete(deleteRequest, RequestOptions.DEFAULT);
        }
        client.close();
    }

2.3 改

2.3.1 Update by ID

按照 ID 进行简单的操作,此更新操作是更新整个文档。

public static void updateById(String id) throws IOException {
        /*初始化 get 请求*/
        GetRequest request = new GetRequest(INDEX_NAME, TYPE, id);
        /*判断是否存在*/
        boolean exists = client.exists(request, RequestOptions.DEFAULT);
        if(exists){
            /*初始化 Update 请求,按照 id更新*/
            UpdateRequest updateRequest = new UpdateRequest(INDEX_NAME, TYPE, id);
            /*组装 数据*/
            Tender tender = new Tender("鉴定药敏分析仪"
                    ,"四川国际招标有限责任公司"
                    ,"招标结果"
                    ,"100");
            updateRequest.doc(JSONObject.toJSONString(tender), XContentType.JSON);
            /*执行更新操作*/
            client.update(updateRequest, RequestOptions.DEFAULT);
        }
        client.close();
    }

2.3.2 Update by query(补)

Update by query操作和 kibana 中的 _update_by_query 操作一样,所以需要设施 script 参数,ES 不像关系型数据库表,可以更新单个字段,ES是以文档的方式存储的,所以如果要更新其中的一个字段,则需要用 script 脚本。

	public static void updateByQuery(String typeId) throws IOException {
        /*构建根据查询条件更新内容操作*/
        UpdateByQueryRequest updateByQuery = new UpdateByQueryRequest();
        /*设置更新条件*/
        updateByQuery.setQuery(QueryBuilders.matchQuery("notice_type_id", typeId));
        /*设置更新 INDEX*/
        updateByQuery.indices(INDEX);
        /*文档类型,ES8 默认为 doc,不用设置*/
        updateByQuery.setDocTypes("data");
        /*设置更新脚本,下面表示更新文档中的 product_agency,和 product_name 字段,如果是多个字段,也可以更新多个字段*/
        updateByQuery.setScript(new Script("ctx._source['product_agency']='一二三集团';ctx._source['product_name']='抗敏药物'"));
        long updated = client.updateByQuery(updateByQuery, RequestOptions.DEFAULT).getUpdated();
        /*更新条数*/
        System.out.println("修改成功:" + updated);
        client.close();
    }

第二种写法(ES 7 之前版本):

注意:下面的这种写法是用 TransportClient 来操作的,如果ES是 7 之前的版本则可以用这个客户端操作,7 版本之后 TransportClient 弃用了,所以如果 ES 是 7.x 以后的版本,则用 RestHighLevelClient 客户端。

    public static void updateByQueryAction(String typeId){
        /*利用 UpdateByQueryAction 来构建一个 UpdateByQueryRequestBuilder*/
        UpdateByQueryRequestBuilder builder = UpdateByQueryAction.INSTANCE.newRequestBuilder(transportClient);
        /*设置更新脚本*/
        Script script = new Script("ctx._source['product_agency']='三一集团';ctx._source['product_name']='抗老药物'");
        BulkByScrollResponse response = builder.source(INDEX)
                .script(script)
                .filter(QueryBuilders.matchQuery("notice_type_id", typeId))
                .abortOnVersionConflict(false).get();
        long updated = response.getUpdated();
        /*更新条数*/
        System.out.println("修改成功:" + updated);
        transportClient.close();
    }

TransportClient 客户端实例化如下(拷贝即可用),需要引入依赖:

    <dependency>
        <groupId>org.elasticsearch.client</groupId>
        <artifactId>transport</artifactId>
        <version>6.7.2</version>
    </dependency>
	public static TransportClient getTransportClient(){
        try{
            TransportClient client = new PreBuiltTransportClient(Settings.EMPTY)
                    .addTransportAddress(new TransportAddress(InetAddress.getByName(HOSTNAME),9300));
            return client;
        }catch (UnknownHostException e){
            e.printStackTrace();
        }
        return null;
    }

2.4 查

2.4.1 按照 ID 获取

public static Tender searchById(String id) throws IOException {
        /*初始化 get  请求*/
        GetRequest request = new GetRequest(INDEX_NAME, TYPE, id);
        /*按照 ID 获取数据*/
        GetResponse response = client.get(request, RequestOptions.DEFAULT);
        Tender tender = JSONObject.parseObject(response.getSourceAsString(), Tender.class);
        client.close();
        return tender;
    }

2.4.2 多字段查询

public static List<Tender>  searchList(String keyword) throws IOException {
        /*初始化查询请求*/
        SearchRequest searchRequest = new SearchRequest(INDEX_NAME);
        /*初始化 构建 查询 builder*/
        SearchSourceBuilder builder = new SearchSourceBuilder();
        /*初始化 多字段 查询 builder*/
        MultiMatchQueryBuilder multiMatchQueryBuilder = QueryBuilders.multiMatchQuery(keyword, "product_agency");
        /*设置 查询 多字段查询*/
        builder.query(multiMatchQueryBuilder);
        /*把 构建好的 查询 封装到 查询请求中*/
        searchRequest.source(builder);
        /*执行查询*/
        SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
        SearchHit[] hits = response.getHits().getHits();
        List<Tender> collect = Arrays.stream(hits).map(hit -> JSONObject.parseObject(hit.getSourceAsString(), Tender.class)).collect(Collectors.toList());
        client.close();
        return collect;
    }

2.4.3 分页查询

public static List<Tender> searchListByPages(String keyword, int pageNo, int pageSize) throws IOException {
        /*构建查询请求*/
        SearchRequest searchRequest = new SearchRequest(INDEX_NAME);
        /*构建查询条件 builder*/
        SearchSourceBuilder builder = new SearchSourceBuilder();
        /*构建 多字段 查询*/
        builder.query(QueryBuilders.multiMatchQuery(keyword, "product_name","product_agency"));
        /*设置分页 每页大小*/
        builder.size(pageSize);
        /*设置 分页 page no*/
        builder.from(pageNo > 1 ?(pageNo - 1) * pageSize : 0);
        /*把组装好的 查询builder 设置到 查询请求中*/
        searchRequest.source(builder);
        /*执行查询*/
        SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
        SearchHit[] hits = response.getHits().getHits();
        List<Tender> collect = Arrays.stream(hits).map(hit -> JSONObject.parseObject(hit.getSourceAsString(), Tender.class)).collect(Collectors.toList());
        System.out.println(response.getHits().getTotalHits());
        client.close();
        return collect;
    }

2.4.4 按照游标(scroll)查询

public static List<Tender> searchListByScrollPages(String keyword, String scrollId, int pageSize) throws IOException {
        SearchResponse response = null;
        if(Objects.nonNull(scrollId)){
            /*如果游标 id 不为空的话,直接按照 游标 获取数据*/
            SearchScrollRequest searchScrollRequest = new SearchScrollRequest(scrollId);
            /*设置游标id, 有效时间 5 分钟*/
            searchScrollRequest.scroll(TimeValue.timeValueMinutes(5));
            response = client.scroll(searchScrollRequest, RequestOptions.DEFAULT);
        }else{
            SearchRequest searchRequest = new SearchRequest(INDEX_NAME);
            SearchSourceBuilder builder = new SearchSourceBuilder();
            builder.query(QueryBuilders.multiMatchQuery(keyword, "product_name","product_agency"));
            builder.size(pageSize);
            searchRequest.source(builder);
            searchRequest.scroll(TimeValue.timeValueMinutes(5));
            response = client.search(searchRequest, RequestOptions.DEFAULT);
        }
        SearchHit[] hits = response.getHits().getHits();
        System.out.println(response.getHits().getTotalHits());
        System.out.println(response.getScrollId());
        List<Tender> collect = Arrays.stream(hits).map(hit -> JSONObject.parseObject(hit.getSourceAsString(), Tender.class)).collect(Collectors.toList());
        client.close();
        return collect;
    }

2.4.5 分页、游标、高亮查询

public static List<Tender> searchListByScrollPageWithHighLight(String keyword, String scrollId, int pageSize) throws IOException {
        SearchResponse response = null;
        if(Objects.nonNull(scrollId)){
            SearchScrollRequest searchScrollRequest = new SearchScrollRequest(scrollId);
            searchScrollRequest.scroll(TimeValue.timeValueMinutes(5));
            response = client.scroll(searchScrollRequest, RequestOptions.DEFAULT);
        }else{
            SearchRequest searchRequest = new SearchRequest(INDEX_NAME);
            SearchSourceBuilder builder = new SearchSourceBuilder();
            builder.query(QueryBuilders.multiMatchQuery(keyword, "product_name","product_agency"));
            //设置高亮查询 初始化 高亮 builder
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            /*设置高亮的 字段*/
            highlightBuilder.field("product_name");
            /*设置高亮标签字段*/
            highlightBuilder.preTags("<font color='red'>");
            highlightBuilder.postTags("</font>");
            /*把高亮builder 设置到 查询 builder 里面*/
            builder.highlighter(highlightBuilder);
            builder.size(pageSize);
            searchRequest.source(builder);
            searchRequest.scroll(TimeValue.timeValueMinutes(5));
            response = client.search(searchRequest, RequestOptions.DEFAULT);
        }
        SearchHit[] hits = response.getHits().getHits();
        System.out.println(response.getHits().getTotalHits());
        System.out.println(response.getScrollId());
        List<Tender> collect = Arrays.stream(hits).map(hit -> JSONObject.parseObject(hit.getSourceAsString(), Tender.class)).collect(Collectors.toList());
        for (SearchHit hit : hits) {
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            HighlightField productName = highlightFields.get("product_name");
            if(Objects.nonNull(productName)){
                System.out.println(productName);
            }
        }
        client.close();
        return collect;
    }

总结

以上是 java api 对 ES 的增删改查的简单案例,方便公司里面临时有需要对ES操作大量数据是,可以直接copy 执行。
不过 ES 随着版本的升级,客户端也随着升级,操作ES的 API 也会发生变化,不过 Spring 当然会对 ES 客户端进行整合,项目中可方便使用,请看
SpringBoot整合ES篇

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java API可以用于操作Elasticsearch(ES)搜索引擎,以下是使用Java API进行ES操作的基本步骤: 1. 导入依赖 在项目中添加Elasticsearch Java API的依赖,例如: ```xml <dependency> <groupId>org.elasticsearch.client</groupId> <artifactId>elasticsearch-rest-high-level-client</artifactId> <version>7.14.1</version> </dependency> ``` 2. 创建连接 使用Java API连接ES集群,例如: ```java RestHighLevelClient client = new RestHighLevelClient( RestClient.builder(new HttpHost("localhost", 9200, "http"))); ``` 3. 创建索引 使用Java API创建索引,例如: ```java CreateIndexRequest request = new CreateIndexRequest("my_index"); client.indices().create(request, RequestOptions.DEFAULT); ``` 4. 添加文档 使用Java API向索引添加文档,例如: ```java IndexRequest request = new IndexRequest("my_index"); request.id("1"); String jsonString = "{" + "\"name\":\"John\"," + "\"age\":30," + "\"city\":\"New York\"" + "}"; request.source(jsonString, XContentType.JSON); client.index(request, RequestOptions.DEFAULT); ``` 5. 搜索文档 使用Java API搜索文档,例如: ```java SearchRequest request = new SearchRequest("my_index"); SearchSourceBuilder builder = new SearchSourceBuilder(); builder.query(QueryBuilders.matchQuery("name", "John")); request.source(builder); SearchResponse response = client.search(request, RequestOptions.DEFAULT); ``` 6. 关闭连接 使用完Java API后,需要关闭连接,例如: ```java client.close(); ``` 以上就是使用Java API操作ES的基本步骤。具体的操作方式和方法需要根据具体的需求来进行选择。同时,需要注意ES版本和Java API版本的兼容性。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值