IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> Java知识库 -> ElasticSearch(三):操作之Java的API操作实例 -> 正文阅读

[Java知识库]ElasticSearch(三):操作之Java的API操作实例

目录

Java API操作

创建Maven项目

客户端对象

索引操作

创建索引

查看索引

删除索引

文档操作

新增文档

修改文档

查询文档

删除文档

批量操作

高级查询

请求体查询

高亮查询

聚合查询


Java API操作

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

创建Maven项目

我们在IDEA开发工具中创建Maven项目(模块也可)ES??????

修改pom文件,增加Maven依赖关系

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

</dependencies>

客户端对象

创建com.atguigu.es.test.Elasticsearch01_Client类,代码中创建Elasticsearch客户端对象

因为早期版本的客户端对象已经不再推荐使用,且在未来版本中会被删除,所以这里我们采用高级REST客户端对象???

// 创建客户端对象

RestHighLevelClient client = new RestHighLevelClient(

??????? RestClient.builder(new HttpHost("localhost", 9200, "http"))

)

// 关闭客户端连接

client.close();

注意:9200端口为Elasticsearch的Web通信端口localhost为启动ES服务的主机名

执行代码,查看控制台信息:???

索引操作

ES服务器正常启动后,可以通过Java API 客户端对象对ES索引进行操作

创建索引

// 创建索引 - 请求对象

CreateIndexRequest request = new CreateIndexRequest("user");

// 发送请求,获取响应

CreateIndexResponse response = client.indices().create(request, RequestOptions.DEFAULT);

boolean acknowledged = response.isAcknowledged();

// 响应状态

System.out.println("操作状态 = " + acknowledged);

操作结果:?????

查看索引

// 查询索引 - 请求对象

GetIndexRequest request = new GetIndexRequest("user");

// 发送请求,获取响应

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());

操作结果:?????

删除索引

// 删除索引 - 请求对象

DeleteIndexRequest request = new DeleteIndexRequest("user");

// 发送请求,获取响应

AcknowledgedResponse response = client.indices().delete(request, RequestOptions.DEFAULT);

// 操作结果

System.out.println("操作结果 : " + response.isAcknowledged());

操作结果:?????

文档操作

新增文档

创建数据模型

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;             

    }                               

}   

??????????????????????????

创建数据,添加到文档中

// 新增文档 - 请求对象

IndexRequest request = new IndexRequest();

// 设置索引及唯一性标识

request.index("user").id("1001");

// 创建数据对象

User user = new User();

user.setName("zhangsan");

user.setAge(30);

user.setSex("男");

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());??????????????????????????????

操作结果:?????

修改文档

// 修改文档 - 请求对象

UpdateRequest request = new UpdateRequest();

// 配置修改参数

request.index("user").id("1001");

// 设置请求体,对数据进行修改

request.doc(XContentType.JSON, "sex", "女");

// 客户端发送请求,获取响应对象

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());

执行结果:???

查询文档

//1.创建请求对象

GetRequest request = new GetRequest().index("user").id("1001");

//2.客户端发送请求,获取响应对象

GetResponse response = client.get(request, RequestOptions.DEFAULT);

3.打印结果信息

System.out.println("_index:" + response.getIndex());

System.out.println("_type:" + response.getType());

System.out.println("_id:" + response.getId());

System.out.println("source:" + response.getSourceAsString());

执行结果为:??????

删除文档

//创建请求对象

DeleteRequest request = new DeleteRequest().index("user").id("1");

//客户端发送请求,获取响应对象

DeleteResponse response = client.delete(request, RequestOptions.DEFAULT);

//打印信息

System.out.println(response.toString());

执行结果为:??????

批量操作

  • 批量新增:

//创建批量新增请求对象

BulkRequest request = new BulkRequest();

request.add(new IndexRequest().index("user").id("1001").source(XContentType.JSON, "name", "zhangsan"));

request.add(new IndexRequest().index("user").id("1002").source(XContentType.JSON, "name", "lisi"));

request.add(new IndexRequest().index("user").id("1003").source(XContentType.JSON, "name", "wangwu"));

//客户端发送请求,获取响应对象

BulkResponse responses = client.bulk(request, RequestOptions.DEFAULT);

//打印结果信息

System.out.println("took:" + responses.getTook());

System.out.println("items:" + responses.getItems());

执行结果为:

  • 批量删除:

//创建批量删除请求对象

BulkRequest request = new BulkRequest();

request.add(new DeleteRequest().index("user").id("1001"));

request.add(new DeleteRequest().index("user").id("1002"));

request.add(new DeleteRequest().index("user").id("1003"));

//客户端发送请求,获取响应对象

BulkResponse responses = client.bulk(request, RequestOptions.DEFAULT);

//打印结果信息

System.out.println("took:" + responses.getTook());

System.out.println("items:" + responses.getItems());

执行结果为:

高级查询

请求体查询

  • 查询所有索引数据

// 创建搜索请求对象

SearchRequest request = new SearchRequest();

request.indices("student");

// 构建查询的请求体

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("<<========");

  • term查询,查询条件为关键字

// 创建搜索请求对象

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("<<========");

?

  • 分页查询

// 创建搜索请求对象

SearchRequest request = new SearchRequest();

request.indices("student");

// 构建查询的请求体

SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

sourceBuilder.query(QueryBuilders.matchAllQuery());

// 分页查询

// 当前页其实索引(第一条数据的顺序号),from

sourceBuilder.from(0);

// 每页显示多少条size

sourceBuilder.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("<<========");

?

  • 数据排序

// 构建查询的请求体

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("<<========");

  • 过滤字段

// 创建搜索请求对象

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("<<========");

  • Bool查询

// 创建搜索请求对象

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("<<========");

?

  • 范围查询

// 创建搜索请求对象

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("<<========");

?

  • 模糊查询

// 创建搜索请求对象

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("<<========");

?

高亮查询

// 高亮查询

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("<<::::");

?

聚合查询

  • 最大年龄

// 高亮查询

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

?

  • 分组统计

// 高亮查询

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

  Java知识库 最新文章
计算距离春节还有多长时间
系统开发系列 之WebService(spring框架+ma
springBoot+Cache(自定义有效时间配置)
SpringBoot整合mybatis实现增删改查、分页查
spring教程
SpringBoot+Vue实现美食交流网站的设计与实
虚拟机内存结构以及虚拟机中销毁和新建对象
SpringMVC---原理
小李同学: Java如何按多个字段分组
打印票据--java
上一篇文章           查看所有文章
加:2021-07-04 19:22:40  更:2021-07-04 19:23:35 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年12日历 -2024/12/18 15:11:14-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码