ElasticSearch Java API 操作

news/2024/11/27 23:57:03/

1.idea创建Maven项目

2.添加依赖

修改 pom.xml 文件

<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>

3.客户端对象

创建 ES_test 类:

public class ES_test {public static void main(String[] args) throws IOException {// 创建客户端对象RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));// 关闭客户端连接client.close();}
}

 localhost为 es服务器主机名(windows下部署,所以用localhost就可以)

 9200端口为es 通信端口

执行代码:

4.ES api 操作

4.1 索引操作

4.1.1创建索引

    /*** 创建索引* @param client  客户端对象* @param indexName  索引名称* @throws IOException*/public static void CreateIndex(RestHighLevelClient client,String indexName) throws IOException {// 创建索引 - 请求对象CreateIndexRequest request = new CreateIndexRequest(indexName);// 发送请求,获取响应CreateIndexResponse response = client.indices().create(request,RequestOptions.DEFAULT);boolean acknowledged = response.isAcknowledged();// 响应状态System.out.println("操作状态 = " + acknowledged);}

4.1.2 查看索引

    /**** @param client 客户端对象* @param indexName 索引名称* @throws IOException*/public static void GetIndex(RestHighLevelClient client,String indexName) throws IOException {// 查询索引 - 请求对象GetIndexRequest request = new GetIndexRequest(indexName);// 发送请求,获取响应GetIndexResponse response = client.indices().get(request,RequestOptions.DEFAULT);System.out.println("aliases:"+response.getAliases());System.out.println("mappings:"+response.getMappings());System.out.println("settings:"+response.getSettings());}

4.1.3 删除索引

    /**** @param client 客户端对象* @param indexName 索引名称* @throws IOException*/public static void DeleteIndex(RestHighLevelClient client,String indexName) throws IOException {// 删除索引 - 请求对象DeleteIndexRequest request = new DeleteIndexRequest(indexName);// 发送请求,获取响应AcknowledgedResponse response = client.indices().delete(request,RequestOptions.DEFAULT);// 操作结果System.out.println("操作结果 : " + response.isAcknowledged());}

4.2 文档操作

创建User 类

/*** @author MR.Liu* @version 1.0* @data 2023-07-19 15:28*/
public class User {private String name;private Integer age;private String sex;public String getName() {return name;}public void setName(String name) {this.name = name;}public Integer getAge() {return age;}public void setAge(Integer age) {this.age = age;}public String getSex() {return sex;}public void setSex(String sex) {this.sex = sex;}public User(String name, Integer age, String sex) {this.name = name;this.age = age;this.sex = sex;}public User() {}
}

4.2.1 新增文档

    public static void InsertDoc(RestHighLevelClient client,String indexName,User user,String id) throws IOException {// 新增文档 - 请求对象IndexRequest request = new IndexRequest();// 设置索引及唯一性标识request.index(indexName).id(id);ObjectMapper objectMapper = new ObjectMapper();String productJson = objectMapper.writeValueAsString(user);// 添加文档数据,数据格式为 JSON 格式request.source(productJson, XContentType.JSON);// 客户端发送请求,获取响应对象IndexResponse response = client.index(request, RequestOptions.DEFAULT);3.打印结果信息System.out.println("_index:" + response.getIndex());System.out.println("_id:" + response.getId());System.out.println("_result:" + response.getResult());}

4.2.2 修改文档

    public static  void UpdateDoc(RestHighLevelClient client,String indexName,String id,String field,Object value) throws IOException {// 修改文档 - 请求对象UpdateRequest request = new UpdateRequest();// 配置修改参数request.index(indexName).id(id);// 设置请求体,对数据进行修改request.doc(XContentType.JSON, field, value);// 客户端发送请求,获取响应对象UpdateResponse response = client.update(request, RequestOptions.DEFAULT);System.out.println("_index:" + response.getIndex());System.out.println("_id:" + response.getId());System.out.println("_result:" + response.getResult());}

4.2.3 删除文档

    public static void DeleteDoc(RestHighLevelClient client,String indexName,String id) throws IOException {//创建请求对象DeleteRequest request = new DeleteRequest().index(indexName).id(id);//客户端发送请求,获取响应对象DeleteResponse response = client.delete(request, RequestOptions.DEFAULT);//打印信息System.out.println(response.toString());}

4.2.4 批量新增文档

public static void ListInsertDoc(RestHighLevelClient client,String indexName) throws IOException {//创建批量新增请求对象BulkRequest request = new BulkRequest();request.add(new IndexRequest().index(indexName).id("10001").source(XContentType.JSON, "name","zhangsan"));request.add(new IndexRequest().index(indexName).id("10002").source(XContentType.JSON, "name","lisi"));request.add(new IndexRequest().index(indexName).id("10003").source(XContentType.JSON, "name","wangwu"));//客户端发送请求,获取响应对象BulkResponse responses = client.bulk(request, RequestOptions.DEFAULT);//打印结果信息System.out.println("took:" + responses.getTook());System.out.println("items:" + responses.getItems());}

4.2.5 批量删除文档

public static void ListDeleteDoc(RestHighLevelClient client,String indexName,String ... id) throws IOException {//创建批量删除请求对象BulkRequest request = new BulkRequest();for (int i=0;i<id.length;i++){System.out.println(id[i]);request.add(new DeleteRequest().index(indexName).id(id[i]));}//客户端发送请求,获取响应对象BulkResponse responses = client.bulk(request, RequestOptions.DEFAULT);//打印结果信息System.out.println("took:" + responses.getTook());System.out.println("items:" + responses.getItems());}

4.3 高级查询

4.3.1 请求体查询

4.3.1.1 查询索引中所有文档

    public static void SelectIndexAllDoc(RestHighLevelClient client,String indexName) throws IOException {// 创建搜索请求对象SearchRequest request = new SearchRequest();request.indices(indexName);// 构建查询的请求体SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();// 查询所有数据sourceBuilder.query(QueryBuilders.matchAllQuery());request.source(sourceBuilder);SearchResponse response = client.search(request, RequestOptions.DEFAULT);// 查询匹配SearchHits hits = response.getHits();System.out.println("took:" + response.getTook());System.out.println("timeout:" + response.isTimedOut());System.out.println("total:" + hits.getTotalHits());System.out.println("MaxScore:" + hits.getMaxScore());System.out.println("hits========>>");for (SearchHit hit : hits) {//输出每条查询的结果信息System.out.println(hit.getSourceAsString());}System.out.println("<<========");}

4.3.1.2 term查询关键字

    public static void TramSelectByKeyWords(RestHighLevelClient client,String indexName) throws IOException {// 创建搜索请求对象SearchRequest request = new SearchRequest();request.indices("student");// 构建查询的请求体SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();sourceBuilder.query(QueryBuilders.termQuery("age", "30"));request.source(sourceBuilder);SearchResponse response = client.search(request, RequestOptions.DEFAULT);// 查询匹配SearchHits hits = response.getHits();System.out.println("took:" + response.getTook());System.out.println("timeout:" + response.isTimedOut());System.out.println("total:" + hits.getTotalHits());System.out.println("MaxScore:" + hits.getMaxScore());System.out.println("hits========>>");for (SearchHit hit : hits) {//输出每条查询的结果信息System.out.println(hit.getSourceAsString());}System.out.println("<<========");}

4.3.1.3分页查询

 public static void Paging(RestHighLevelClient client,String indexName) throws IOException {// 创建搜索请求对象SearchRequest request = new SearchRequest();request.indices("student");// 构建查询的请求体SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();sourceBuilder.query(QueryBuilders.matchAllQuery());// 分页查询// 当前页其实索引(第一条数据的顺序号),fromsourceBuilder.from(0);// 每页显示多少条 sizesourceBuilder.size(2);request.source(sourceBuilder);SearchResponse response = client.search(request, RequestOptions.DEFAULT);// 查询匹配SearchHits hits = response.getHits();System.out.println("took:" + response.getTook());System.out.println("timeout:" + response.isTimedOut());System.out.println("total:" + hits.getTotalHits());System.out.println("MaxScore:" + hits.getMaxScore());System.out.println("hits========>>");for (SearchHit hit : hits) {//输出每条查询的结果信息System.out.println(hit.getSourceAsString());}System.out.println("<<========");}

4.3.1.4排序查询

public static void SortOrderAll(RestHighLevelClient client,String indexName) throws IOException {// 创建搜索请求对象SearchRequest request = new SearchRequest();request.indices("student");// 构建查询的请求体SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();sourceBuilder.query(QueryBuilders.matchAllQuery());// 排序sourceBuilder.sort("age", SortOrder.ASC);request.source(sourceBuilder);SearchResponse response = client.search(request, RequestOptions.DEFAULT);// 查询匹配SearchHits hits = response.getHits();System.out.println("took:" + response.getTook());System.out.println("timeout:" + response.isTimedOut());System.out.println("total:" + hits.getTotalHits());System.out.println("MaxScore:" + hits.getMaxScore());System.out.println("hits========>>");for (SearchHit hit : hits) {//输出每条查询的结果信息System.out.println(hit.getSourceAsString());}System.out.println("<<========");}

4.3.1.5 过滤字段

public static void FilterByColumn(RestHighLevelClient client,String indexName) throws IOException {// 创建搜索请求对象SearchRequest request = new SearchRequest();request.indices("student");// 构建查询的请求体SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();sourceBuilder.query(QueryBuilders.matchAllQuery());//查询字段过滤String[] excludes = {};String[] includes = {"name", "age"};sourceBuilder.fetchSource(includes, excludes);request.source(sourceBuilder);SearchResponse response = client.search(request, RequestOptions.DEFAULT);// 查询匹配SearchHits hits = response.getHits();System.out.println("took:" + response.getTook());System.out.println("timeout:" + response.isTimedOut());System.out.println("total:" + hits.getTotalHits());System.out.println("MaxScore:" + hits.getMaxScore());System.out.println("hits========>>");for (SearchHit hit : hits) {//输出每条查询的结果信息System.out.println(hit.getSourceAsString());}System.out.println("<<========");}

4.3.1.6 Bool查询

public static void boolSelect(RestHighLevelClient client,String indexName) throws IOException {// 创建搜索请求对象SearchRequest request = new SearchRequest();request.indices("student");// 构建查询的请求体SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();// 必须包含boolQueryBuilder.must(QueryBuilders.matchQuery("age", "30"));// 一定不含boolQueryBuilder.mustNot(QueryBuilders.matchQuery("name", "zhangsan"));// 可能包含boolQueryBuilder.should(QueryBuilders.matchQuery("sex", "男"));sourceBuilder.query(boolQueryBuilder);request.source(sourceBuilder);SearchResponse response = client.search(request, RequestOptions.DEFAULT);// 查询匹配SearchHits hits = response.getHits();System.out.println("took:" + response.getTook());System.out.println("timeout:" + response.isTimedOut());System.out.println("total:" + hits.getTotalHits());System.out.println("MaxScore:" + hits.getMaxScore());System.out.println("hits========>>");for (SearchHit hit : hits) {//输出每条查询的结果信息System.out.println(hit.getSourceAsString());}System.out.println("<<========");}

4.3.1.7 范围查询

public static void RangeSelect(RestHighLevelClient client,String indexName) throws IOException {// 创建搜索请求对象SearchRequest request = new SearchRequest();request.indices("student");// 构建查询的请求体SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("age");// 大于等于rangeQuery.gte("30");// 小于等于rangeQuery.lte("40");sourceBuilder.query(rangeQuery);request.source(sourceBuilder);SearchResponse response = client.search(request, RequestOptions.DEFAULT);// 查询匹配SearchHits hits = response.getHits();System.out.println("took:" + response.getTook());System.out.println("timeout:" + response.isTimedOut());System.out.println("total:" + hits.getTotalHits());System.out.println("MaxScore:" + hits.getMaxScore());System.out.println("hits========>>");for (SearchHit hit : hits) {//输出每条查询的结果信息System.out.println(hit.getSourceAsString());}System.out.println("<<========");}

4.3.1.8 模糊查询

public static void VagueSelect(RestHighLevelClient client,String indexName) throws IOException {// 创建搜索请求对象SearchRequest request = new SearchRequest();request.indices("student");// 构建查询的请求体SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();sourceBuilder.query(QueryBuilders.fuzzyQuery("name","zhangsan").fuzziness(Fuzziness.ONE));request.source(sourceBuilder);SearchResponse response = client.search(request, RequestOptions.DEFAULT);// 查询匹配SearchHits hits = response.getHits();System.out.println("took:" + response.getTook());System.out.println("timeout:" + response.isTimedOut());System.out.println("total:" + hits.getTotalHits());System.out.println("MaxScore:" + hits.getMaxScore());System.out.println("hits========>>");for (SearchHit hit : hits) {//输出每条查询的结果信息System.out.println(hit.getSourceAsString());}System.out.println("<<========");}

4.3.2 高亮查询

public static void HighlightSelect(RestHighLevelClient client,String indexName) throws IOException {// 高亮查询SearchRequest request = new SearchRequest().indices("student");//2.创建查询请求体构建器SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();//构建查询方式:高亮查询TermsQueryBuilder termsQueryBuilder = QueryBuilders.termsQuery("name","zhangsan");//设置查询方式sourceBuilder.query(termsQueryBuilder);//构建高亮字段HighlightBuilder highlightBuilder = new HighlightBuilder();highlightBuilder.preTags("<font color='red'>");//设置标签前缀highlightBuilder.postTags("</font>");//设置标签后缀highlightBuilder.field("name");//设置高亮字段//设置高亮构建对象sourceBuilder.highlighter(highlightBuilder);//设置请求体request.source(sourceBuilder);//3.客户端发送请求,获取响应对象SearchResponse response = client.search(request, RequestOptions.DEFAULT);//4.打印响应结果SearchHits hits = response.getHits();System.out.println("took::"+response.getTook());System.out.println("time_out::"+response.isTimedOut());System.out.println("total::"+hits.getTotalHits());System.out.println("max_score::"+hits.getMaxScore());System.out.println("hits::::>>");for (SearchHit hit : hits) {String sourceAsString = hit.getSourceAsString();System.out.println(sourceAsString);//打印高亮结果Map<String, HighlightField> highlightFields = hit.getHighlightFields();System.out.println(highlightFields);}System.out.println("<<::::");}

4.3.3 聚合函数

4.3.3.1 最大值查询

public static void MaxSelect(RestHighLevelClient client,String indexName) throws IOException {// 高亮查询SearchRequest request = new SearchRequest().indices("student");SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();sourceBuilder.aggregation(AggregationBuilders.max("maxAge").field("age"));//设置请求体request.source(sourceBuilder);//3.客户端发送请求,获取响应对象SearchResponse response = client.search(request, RequestOptions.DEFAULT);//4.打印响应结果SearchHits hits = response.getHits();System.out.println(response);}

4.3.3.2 分组查询

public static void GroupSelect(RestHighLevelClient client,String indexName) throws IOException {// 高亮查询SearchRequest request = new SearchRequest().indices("student");SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();sourceBuilder.aggregation(AggregationBuilders.terms("age_groupby").field("age"));//设置请求体request.source(sourceBuilder);//3.客户端发送请求,获取响应对象SearchResponse response = client.search(request, RequestOptions.DEFAULT);//4.打印响应结果SearchHits hits = response.getHits();System.out.println(response);}


http://www.ppmy.cn/news/978086.html

相关文章

网络安全.域名备案和ICP备案

首先我们来了解一下域名备案和ICP备案分别代表什么意义。 域名备案一般需要1至3个工作日的时间进行审核&#xff0c;而ICP备案的审核时间较长&#xff0c;需要在5至20个工作日的时间内完成。域名备案方面主要考虑域名的合法性和域名归属人信息的真实性&#xff0c;而ICP备案方…

C++ STL sort函数的底层实现

C STL sort函数的底层实现 sort函数的底层用到的是内省式排序以及插入排序&#xff0c;内省排序首先从快速排序开始&#xff0c;当递归深度超过一定深度&#xff08;深度为排序元素数量的对数值&#xff09;后转为堆排序。 先来回顾一下以上提到的3中排序方法&#xff1a; 快…

kafka权限控制功能

参考链接&#xff1a; https://www.clougence.com/cc-doc/dataMigrationAndSync/database/privs_for_kafka Kafka需要的权限 | CloudCanal of ClouGence Kafka Topic 权限控制可以通过使用 Apache Kafka 的内置安全特性来实现。这主要涉及到两个方面&#xff1a;认证&#…

Linux6.14 Docker Compose容器编排

文章目录 计算机系统5G云计算第四章 LINUX Docker Compose容器编排一、Compose概述1.Docker Compose 的概述2.Docker Compose 三大的概念 二、部署过程1.Docker Compose 环境安装2.YAML 文件格式及编写注意事项3.Docker Compose配置常用字段4.Docker Compose 常用命令5.Docker …

C语言学习笔记 第一个C语言项目-07

目录 1.新建一个文件夹 2.新建一个文件&#xff0c;后缀以.cpp结尾 3.编写代码 4.编译与执行代码 代码解析 总结 1.新建一个文件夹 2.新建一个文件&#xff0c;后缀以.cpp结尾 如下图所示&#xff0c;选择相应的文件夹&#xff0c;然后点击新建文件按钮&#xff0c;新建的文…

何优化 PHP 数据库查询性能?

当你想要优化 PHP 数据库查询性能时&#xff0c;以下是一些可以从新手角度出发的有趣且实用的技巧&#xff1a; 学会写 SQL 查询语句 SQL 查询语句是数据库操作的核心&#xff0c;学会写高效的 SQL 查询语句是优化数据库查询性能的关键。不要发送过多的数据到服务器&#xff0…

集成学习Boosting - AdaBoost

目录 1. Boosting方法的基本思想 1.1 Bagging VS Boosting 1.2 Boosting算法的基本元素与基本流程 1.3 sklearn中的Boosting算法 2. AdaBoost 3 AdaBoost的基本参数与损失函数 3.1 参数 base_estimator&#xff0c;属性base_estimator_与estimators_ 3.1. 参数 learnin…

微信小程序 内容评论-回复评论-回复回复的实现(纯前端)

wxml <!-- 评论-回复-回复评论显示区域 --> <view class"container"><!-- 总共评论数 --> <view class"total">共{{comment_list.length comment_list2.length}}条评论</view> <!-- END --><!-- 评论框 …