Elasticsearch——Java API 操作

        Elasticsearch 软件是由Java语言开发的,所以也可以通过JavaAPI的方式对 Elasticsearch服务进行访问。

创建 Maven 项目

        我们在 IDEA 开发工具中创建 Maven 项目(模块也可)ES。并修改pom文件,增加Maven依赖关系。

#直接复制在pom文件的<dependencies></dependencies>中
<dependency><groupId>org.elasticsearch</groupId><artifactId>elasticsearch</artifactId><version>7.8.0</version></dependency><!-- elasticsearch 的客户端 --><dependency><groupId>org.elasticsearch.client</groupId><artifactId>elasticsearch-rest-high-level-client</artifactId><version>7.8.0</version></dependency><!-- elasticsearch 依赖 2.x 的 log4j --><dependency><groupId>org.apache.logging.log4j</groupId><artifactId>log4j-api</artifactId><version>2.8.2</version></dependency><dependency><groupId>org.apache.logging.log4j</groupId><artifactId>log4j-core</artifactId><version>2.8.2</version></dependency><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>2.9.9</version></dependency><!-- junit 单元测试 --><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version></dependency>

        测试连接客户端,若控制台正常关闭无报错正常连接。

public class ESTest_Client {public static void main(String[] args) throws Exception{//创建ES客户端RestHighLevelClient esClient = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost",9200,"http")));//关闭ES客户端esClient.close();}
}

索引操作

        创建索引

public class ESTest_Index_Create {public static void main(String[] args) throws Exception{//创建ES客户端RestHighLevelClient esClient = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost",9200,"http")));//创建索引CreateIndexRequest request = new CreateIndexRequest("user");CreateIndexResponse createIndexResponse = esClient.indices().create(request, RequestOptions.DEFAULT);//响应状态boolean acknowledged = createIndexResponse.isAcknowledged();//索引操作System.out.println("索引操作"+acknowledged);//关闭ES客户端esClient.close();}
}

        查询索引 

public class ESTest_Index_Search {public static void main(String[] args) throws Exception{//创建ES客户端RestHighLevelClient esClient = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost",9200,"http")));//查询索引GetIndexRequest request = new GetIndexRequest("user");GetIndexResponse getIndexResponse = esClient.indices().get(request, RequestOptions.DEFAULT);//响应状态System.out.println(getIndexResponse.getAliases());System.out.println(getIndexResponse.getMappings());System.out.println(getIndexResponse.getSettings());//关闭ES客户端esClient.close();}
}

        删除索引 

public class ESTest_Index_DELETE {public static void main(String[] args) throws Exception{//创建ES客户端RestHighLevelClient esClient = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost",9200,"http")));//删除索引DeleteIndexRequest request = new DeleteIndexRequest("user");AcknowledgedResponse delete = esClient.indices().delete(request, RequestOptions.DEFAULT);//响应状态System.out.println("响应结果"+delete.isAcknowledged());//关闭ES客户端esClient.close();}
}

文档操作

        创建User类

public class User {private String name;private int age;private String sex;public User(String name, int age, String sex) {this.name = name;this.age = age;this.sex = sex;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public String getSex() {return sex;}public void setSex(String sex) {this.sex = sex;}
}

        新增数据

public class ESTest_Doc_Instert {public static void main(String[] args) throws Exception{//创建ES客户端RestHighLevelClient esClient = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost",9200,"http")));//插入数据IndexRequest request = new IndexRequest();request.index("user").id("1001");User user = new User("zhangsan",30,"nan");//ES插入数据为JSON要将user转成JSONObjectMapper objectMapper = new ObjectMapper();String s = objectMapper.writeValueAsString(user);request.source(s, XContentType.JSON);IndexResponse index = esClient.index(request, RequestOptions.DEFAULT);System.out.println(index.getResult());//关闭ES客户端esClient.close();}
}

        修改文档

public class ESTest_Doc_Update {public static void main(String[] args) throws Exception{//创建ES客户端RestHighLevelClient esClient = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost",9200,"http")));//修改数据UpdateRequest request = new UpdateRequest();request.index("user").id("1001");request.doc(XContentType.JSON,"sex","女");UpdateResponse index = esClient.update(request, RequestOptions.DEFAULT);System.out.println(index.getResult());//关闭ES客户端esClient.close();}
}

        查询数据

public class ESTest_Doc_Search {public static void main(String[] args) throws Exception{//创建ES客户端RestHighLevelClient esClient = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost",9200,"http")));//查询数据GetRequest getRequest = new GetRequest();getRequest.index("user").id("1001");GetResponse index = esClient.get(getRequest, RequestOptions.DEFAULT);String sourceAsString = index.getSourceAsString();System.out.println(sourceAsString);//关闭ES客户端esClient.close();}
}

        文档删除

public class ESTest_Doc_Delete {public static void main(String[] args) throws Exception{//创建ES客户端RestHighLevelClient esClient = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost",9200,"http")));//删除数据DeleteRequest request = new DeleteRequest();request.index("user").id("1001");User user = new User("zhangsan",30,"nan");DeleteResponse index = esClient.delete(request, RequestOptions.DEFAULT);System.out.println(index.getResult());//关闭ES客户端esClient.close();}
}

        批量新增

public class ESTest_Doc_Instert_Batch {public static void main(String[] args) throws Exception{//创建ES客户端RestHighLevelClient esClient = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost",9200,"http")));//批量插入数据BulkRequest bulkRequest = new BulkRequest();bulkRequest.add(new IndexRequest().index("user").id("1001").source(XContentType.JSON, "name", "zhangsan"));bulkRequest.add(new IndexRequest().index("user").id("1002").source(XContentType.JSON, "name", "lisi"));bulkRequest.add(new IndexRequest().index("user").id("1002").source(XContentType.JSON, "name", "wangwu"));BulkResponse bulk = esClient.bulk(bulkRequest, RequestOptions.DEFAULT);System.out.println(bulk.getItems());System.out.println(bulk.getItems());//关闭ES客户端esClient.close();}
}

        批量删除 

public class ESTest_Doc_Delete_Batch {public static void main(String[] args) throws Exception{//创建ES客户端RestHighLevelClient esClient = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost",9200,"http")));//批量删除数据BulkRequest bulkRequest = new BulkRequest();bulkRequest.add(new DeleteRequest().index("user").id("1001"));bulkRequest.add(new DeleteRequest().index("user").id("1002"));bulkRequest.add(new DeleteRequest().index("user").id("1002"));BulkResponse bulk = esClient.bulk(bulkRequest, RequestOptions.DEFAULT);System.out.println(bulk.getItems());System.out.println(bulk.getItems());//关闭ES客户端esClient.close();}
}

        高级查询&分页查询

package org.example.ES;import org.apache.http.HttpHost;
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.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.common.unit.Fuzziness;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;import javax.naming.directory.SearchResult;
import javax.swing.text.Highlighter;public class ESTest_Doc_Query {public static void main(String[] args) throws Exception{//创建ES客户端RestHighLevelClient esClient = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost",9200,"http")));//        //1.查询索引中全量数据
//        SearchRequest searchRequest = new SearchRequest();
//        searchRequest.indices("user");
//
//        searchRequest.source(new SearchSourceBuilder().query(QueryBuilders.matchAllQuery()));
//        SearchResponse response = esClient.search(searchRequest, RequestOptions.DEFAULT);
//
//        SearchHits hits = response.getHits();
//        System.out.println(hits.getTotalHits()+" "+ response.getTook());
//        for (SearchHit hit : hits){
//
//            System.out.println(hit.getSourceAsString());
//        }//        //条件查询 :termQuery
//        SearchRequest searchRequest = new SearchRequest();
//        searchRequest.indices("user");
//
//        searchRequest.source(new SearchSourceBuilder().query(QueryBuilders.termQuery("age",30)));
//        SearchResponse response = esClient.search(searchRequest, RequestOptions.DEFAULT);
//
//        SearchHits hits = response.getHits();
//        System.out.println(hits.getTotalHits()+" "+ response.getTook());
//        for (SearchHit hit : hits){
//
//            System.out.println(hit.getSourceAsString());
//        }//分页查询
//        SearchRequest searchRequest = new SearchRequest();
//        searchRequest.indices("user");
//
//        SearchSourceBuilder query = new SearchSourceBuilder().query(QueryBuilders.matchAllQuery());
//        query.from(0);
//        query.size(2);
//
//        searchRequest.source(query);
//        SearchResponse response = esClient.search(searchRequest, RequestOptions.DEFAULT);
//
//        SearchHits hits = response.getHits();
//        System.out.println(hits.getTotalHits()+" "+ response.getTook());
//        for (SearchHit hit : hits){
//
//            System.out.println(hit.getSourceAsString());
//        }//查询排序
//        SearchRequest searchRequest = new SearchRequest();
//        searchRequest.indices("user");
//
//        SearchSourceBuilder query = new SearchSourceBuilder().query(QueryBuilders.matchAllQuery());
//        query.sort("age", SortOrder.DESC);
//
//        searchRequest.source(query);
//        SearchResponse response = esClient.search(searchRequest, RequestOptions.DEFAULT);
//
//        SearchHits hits = response.getHits();
//        System.out.println(hits.getTotalHits()+" "+ response.getTook());
//        for (SearchHit hit : hits){
//
//            System.out.println(hit.getSourceAsString());
//        }//过滤字段
//        SearchRequest searchRequest = new SearchRequest();
//        searchRequest.indices("user");
//
//        SearchSourceBuilder query = new SearchSourceBuilder().query(QueryBuilders.matchAllQuery());
//
//        //排除
//        String [] excludes = {"age"};
//        //只查询name
//        String [] includes = {};
//        query.fetchSource(includes,excludes);
//
//        searchRequest.source(query);
//        SearchResponse response = esClient.search(searchRequest, RequestOptions.DEFAULT);
//
//        SearchHits hits = response.getHits();
//        System.out.println(hits.getTotalHits()+" "+ response.getTook());
//        for (SearchHit hit : hits){
//
//            System.out.println(hit.getSourceAsString());
//        }//组合查询
//        SearchRequest searchRequest = new SearchRequest();
//        searchRequest.indices("user");
//
//        SearchSourceBuilder query = new SearchSourceBuilder();
//        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
//
//        boolQueryBuilder.must(QueryBuilders.matchQuery("age",30));
//        boolQueryBuilder.must(QueryBuilders.matchQuery("sex","男"));
//
//
//
//        query.query(boolQueryBuilder);
//
//        searchRequest.source(query);
//        SearchResponse response = esClient.search(searchRequest, RequestOptions.DEFAULT);
//
//        SearchHits hits = response.getHits();
//        System.out.println(hits.getTotalHits()+" "+ response.getTook());
//        for (SearchHit hit : hits){
//
//            System.out.println(hit.getSourceAsString());
//        }//范围查询
//        SearchRequest searchRequest = new SearchRequest();
//        searchRequest.indices("user");
//
//        SearchSourceBuilder query = new SearchSourceBuilder();
//        RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("age");
//
//        rangeQuery.gte(30);
//        rangeQuery.lte(40);
//
//        query.query(rangeQuery);
//
//        searchRequest.source(query);
//        SearchResponse response = esClient.search(searchRequest, RequestOptions.DEFAULT);
//
//        SearchHits hits = response.getHits();
//        System.out.println(hits.getTotalHits()+" "+ response.getTook());
//        for (SearchHit hit : hits){
//
//            System.out.println(hit.getSourceAsString());
//        }//模糊查询
////高亮查询
//        SearchRequest searchRequest = new SearchRequest();
//        searchRequest.indices("user");
//
//        SearchSourceBuilder query = new SearchSourceBuilder();
//
//        TermsQueryBuilder termsQueryBuilder = QueryBuilders.termsQuery("name", "zhangsan");
//
//        HighlightBuilder highlightBuilder = new HighlightBuilder();
//        highlightBuilder.preTags("<font> color = 'red'");
//        highlightBuilder.postTags("</font>");
//        highlightBuilder.field("name");
//
//        query.highlighter(highlightBuilder);
//        query.query(termsQueryBuilder);
//
//        searchRequest.source(query);
//        SearchResponse response = esClient.search(searchRequest, RequestOptions.DEFAULT);
//
//        SearchHits hits = response.getHits();
//        System.out.println(hits.getTotalHits()+" "+ response.getTook());
//        for (SearchHit hit : hits){
//
//            System.out.println(hit.getSourceAsString());
//        }//聚合查询
//        SearchRequest searchRequest = new SearchRequest();
//        searchRequest.indices("user");
//
//        SearchSourceBuilder query = new SearchSourceBuilder();
//
//        AggregationBuilder aggregationBuilder =   AggregationBuilders.max("maxAge").field("age");
//
//        query.aggregation(aggregationBuilder);
//
//        query.query();
//
//        searchRequest.source(query);
//        SearchResponse response = esClient.search(searchRequest, RequestOptions.DEFAULT);
//
//        SearchHits hits = response.getHits();
//        System.out.println(hits.getTotalHits()+" "+ response.getTook());
//        for (SearchHit hit : hits){
//
//            System.out.println(hit.getSourceAsString());
//        }//分组查询SearchRequest searchRequest = new SearchRequest();searchRequest.indices("user");SearchSourceBuilder query = new SearchSourceBuilder();AggregationBuilder aggregationBuilder =   AggregationBuilders.terms("ageGrroup").field("age");query.aggregation(aggregationBuilder);query.query();searchRequest.source(query);SearchResponse response = esClient.search(searchRequest, RequestOptions.DEFAULT);SearchHits hits = response.getHits();System.out.println(hits.getTotalHits()+" "+ response.getTook());for (SearchHit hit : hits){System.out.println(hit.getSourceAsString());}//关闭ES客户端esClient.close();}
}

        全量查询

        条件查询

        分页查询

        排序查询

        只查姓名

        排除年龄

        多条件查询

        范围查询

        模糊查询

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.rhkb.cn/news/482091.html

如若内容造成侵权/违法违规/事实不符,请联系长河编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

量化的8位LLM训练和推理使用bitsandbytes在AMD GPUs上

Quantized 8-bit LLM training and inference using bitsandbytes on AMD GPUs — ROCm Blogs 在这篇博客文章中&#xff0c;我们将介绍bitsandbytes的8位表示方式。正如你将看到的&#xff0c;bitsandbytes的8位表示方式显著地减少了微调和推理大语言模型&#xff08;LLMs&…

自回归(Autoregressive)模型概述

自回归&#xff08;Autoregressive&#xff09;模型概述 自回归&#xff08;Autoregressive&#xff0c;简称AR&#xff09;模型是一类基于“历史数据”来预测未来数据的模型。其核心思想是模型的输出不仅依赖于当前输入&#xff0c;还依赖于先前的输出。自回归模型通常用于时…

Win11电脑亮度无法调节以及夜间模式点击没有用失效解决方法

一、问题 最近&#xff0c;突然感觉屏幕亮度十分刺眼&#xff0c;想调整为夜间模式&#xff0c;发现点了夜间模式根本没用&#xff0c;亮度也是变成了灰色。 明明前几天还能调节的&#xff0c;这实在是太难受了&#xff01; 二、原因 这是远程控制软件向日葵的问题 在向日葵…

Linux笔记---进程:进程终止

1. 进程终止概念与分类 进程终止是指一个正在运行的进程结束其执行的操作。以下是一些常见的导致进程终止的情况&#xff1a; 一、正常终止 完成任务当进程完成了它被设计要执行的任务后&#xff0c;就会正常终止。收到特定信号在操作系统中&#xff0c;进程可能会收到来自操作…

【工具推荐】dnsx——一个快速、多用途的 DNS 查询工具

basic/基本使用方式 echo baidu.com | dnsx -recon # 查询域名所有记录echo baidu.com | dnsx -a -resp # 查询域名的a记录echo baidu.com | dnsx -txt -resp # 查询域名的TXT记录echo ip | dnsx -ptr -resp # ip反查域名 A记录查询 TXT记录查询 ip反查域名 help/帮助信息 输…

【树莓派5】移动热点获取树莓派IP并初次登录SSH

本篇文章包含的内容 1 打开系统热点2 烧录系统设置3 配置 MobaXterm4 初次启动树莓派配置选项4.1 换源4.2 更新软件包4.3 安装vim编辑器4.4 更改CPU FAN温度转速 Windows版本&#xff1a;Windows11 24H2树莓派&#xff1a;树莓派5&#xff0c;Raspberry Pi 5SSH软件&#xff1a…

【Git系列】Git 提交历史分析:深入理解`git log`命令

&#x1f49d;&#x1f49d;&#x1f49d;欢迎来到我的博客&#xff0c;很高兴能够在这里和您见面&#xff01;希望您在这里可以感受到一份轻松愉快的氛围&#xff0c;不仅可以获得有趣的内容和知识&#xff0c;也可以畅所欲言、分享您的想法和见解。 推荐:kwan 的首页,持续学…

第144场双周赛:移除石头游戏、两个字符串得切换距离、零数组变换 Ⅲ、最多可收集的水果数目

Q1、[简单] 移除石头游戏 1、题目描述 Alice 和 Bob 在玩一个游戏&#xff0c;他们俩轮流从一堆石头中移除石头&#xff0c;Alice 先进行操作。 Alice 在第一次操作中移除 恰好 10 个石头。接下来的每次操作中&#xff0c;每位玩家移除的石头数 恰好 为另一位玩家上一次操作…

Python parsel库学习总结

parsel库是Python中用于解析HTML文件的库&#xff0c;其能通过CSS选择器、xpath、正则表达式来定位html中的元素。 通过css选择器定位元素 from parsel import Selectorhtml """ <html><head><a class"option1">这是一个伪html片…

【HarmonyOS学习日志(11)】计算机网络之概念,组成和功能

文章目录 计算机网络概念计算机网络&#xff0c;互连网与互联网的区别计算机网络互连网互联网&#xff08;因特网&#xff0c;Internet&#xff09; 计算机网络的组成和功能计算机网络的组成从组成部分看从工作方式看从逻辑功能看 计算机网络的功能数据通信资源共享分布式处理提…

Vue3 开源UI 框架推荐 (大全)

一 、前言 &#x1f4a5;这篇文章主要推荐了支持 Vue3 的开源 UI 框架&#xff0c;包括 web 端和移动端的多个框架&#xff0c;如 Element-Plus、Ant Design Vue 等 web 端框架&#xff0c;以及 Vant、NutUI 等移动端框架&#xff0c;并分别介绍了它们的特性和资源地址。&#…

视觉语言动作模型VLA的持续升级:从π0之参考基线Octo到OpenVLA、TinyVLA、DeeR-VLA、3D-VLA

第一部分 VLA模型π0之参考基线Octo 1.1 Octo的提出背景与其整体架构 1.1.1 Octo的提出背景与相关工作 许多研究使用从机器人收集的大量轨迹数据集来训练策略 从早期使用自主数据收集来扩展策略训练的工作[71,48,41,19-Robonet,27,30]到最近探索将现代基于transformer的策略…

k8s--pod创建、销毁流程

文章目录 一、pod创建流程二、pod销毁流程 一、pod创建流程 1、用户通过kubectl或其他api客户端提交pod spec给apiserver,然后会进行认证、鉴权、变更、校验等一系列过程2、apiserver将pod对象的相关信息最终存入etcd中,待写入操作执行完成,apiserver会返回确认信息给客户端3、…

相同的二叉树

给你两棵二叉树的根节点 p 和 q &#xff0c;编写一个函数来检验这两棵树是否相同。 如果两个树在结构上相同&#xff0c;并且节点具有相同的值&#xff0c;则认为它们是相同的。 示例 1&#xff1a; 输入&#xff1a;p [1,2,3], q [1,2,3] 输出&#xff1a;true示例 2&…

算法妙妙屋-------1.递归的深邃回响:全排列的奇妙组合

全排列的简要总结 全排列&#xff08;Permutation&#xff09;是数学中一个经典的问题&#xff0c;指的是从一组元素中&#xff0c;将所有元素按任意顺序排列形成的所有可能序列。 特点 输入条件&#xff1a; 给定一组互异的元素&#xff08;通常为数组或字符串&#xff09;。…

【Rust】unsafe rust入门

这篇文章简单介绍下unsafe rust的几个要点 1. 解引用裸指针 裸指针其实就是C或者说C的指针&#xff0c;与C的指针不同的是&#xff0c;Rust的裸指针还是要分为可变和不可变&#xff0c;*const T 和 *mut T&#xff1a; 基于引用创建裸指针 let mut num 5;let r1 &num …

什么是人工智能大模型?

成长路上不孤单&#x1f60a;&#x1f60a;&#x1f60a;&#x1f60a;&#x1f60a;&#x1f60a; 【14后&#x1f60a;///C爱好者&#x1f60a;///持续分享所学&#x1f60a;///如有需要欢迎收藏转发///&#x1f60a;】 今日分享关于人工智能大模型的相关内容&#xff01; …

基于深度学习和卷积神经网络的乳腺癌影像自动化诊断系统(PyQt5界面+数据集+训练代码)

乳腺癌是全球女性中最常见的恶性肿瘤之一&#xff0c;早期准确诊断对于提高生存率具有至关重要的意义。传统的乳腺癌诊断方法依赖于放射科医生的经验&#xff0c;然而&#xff0c;由于影像分析的复杂性和人类判断的局限性&#xff0c;准确率和一致性仍存在挑战。近年来&#xf…

【IMF靶场渗透】

文章目录 一、基础信息 二、信息收集 三、flag1 四、flag2 五、flag3 六、flag4 七、flag5 八、flag6 一、基础信息 Kali IP&#xff1a;192.168.20.146 靶机IP&#xff1a;192.168.20.147 二、信息收集 Nmap -sP 192.168.20.0/24 Arp-scan -l nmap -sS -sV -p- -…

MySQL 复合查询

实际开发中往往数据来自不同的表&#xff0c;所以需要多表查询。本节我们用一个简单的公司管理系统&#xff0c;有三张表EMP,DEPT,SALGRADE 来演示如何进行多表查询。表结构的代码以及插入的数据如下&#xff1a; DROP database IF EXISTS scott; CREATE database IF NOT EXIST…