一、Elasticsearch——使用Java API实现ES中的索引、映射、文档操作
1.1 简单介绍
之前是对ES中的创建/查看/删除索引、创建定义映射、创建/查看/修改/删除文档的这些操作有了一定的了解认识,但是是通过Postman + JSON串的方法来实现的
那么之后仍然是对ES中的索引、映射、文档进行操作,只是方法换成了Java API。
1.2 案例详情
首先需要创建一个maven工程,必然要添加ES相关的依赖。
同时双击ES安装目录的bin目录下的 elasticsearch.bat ,先启动ES服务端。
- pom文件
<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>
1.2.1 创建ES客户端:完成与ES服务端连接
后边都是按照这个模板代码来的
package com.szh.es;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import java.io.IOException;
/**
*
*/
public class ESTestClient {
public static void main(String[] args) throws IOException {
//创建ES客户端
RestHighLevelClient esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
//关闭ES客户端
esClient.close();
}
}
1.2.2 创建索引
//创建ES客户端
RestHighLevelClient esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
//创建索引 --- 请求对象
CreateIndexRequest request = new CreateIndexRequest("user");
//发送请求 --- 获取响应
CreateIndexResponse response = esClient.indices().create(request, RequestOptions.DEFAULT);
//响应状态
boolean acknowledged = response.isAcknowledged();
System.out.println("索引操作:" + acknowledged);
//关闭ES客户端
esClient.close();
1.2.3 查看索引
public class ESTestIndexSearch {
public static void main(String[] args) throws IOException {
//创建ES客户端
RestHighLevelClient esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
//查询索引 --- 请求对象
GetIndexRequest request = new GetIndexRequest("user");
//发送请求 --- 获取响应
GetIndexResponse response = esClient.indices().get(request, RequestOptions.DEFAULT);
//响应状态
System.out.println(response.getAliases());
System.out.println(response.getMappings());
System.out.println(response.getSettings());
//关闭ES客户端
esClient.close();
}
}
1.2.4 删除索引
public class ESTestIndexDelete {
public static void main(String[] args) throws IOException {
//创建ES客户端
RestHighLevelClient esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
//删除索引 --- 请求对象
DeleteIndexRequest request = new DeleteIndexRequest("user");
//发送请求 --- 获取响应
AcknowledgedResponse response = esClient.indices().delete(request,RequestOptions.DEFAULT);
//响应状态
System.out.println(response.isAcknowledged());
//关闭ES客户端
esClient.close();
}
}
1.2.5 创建文档
索引有了,就相当于有了数据库。接下来就需要向数据库中建表、添加数据。建表自然要有表结构(有哪些属性、这些属性分别都是什么数据类型),也就是ES中的映射,在Java代码中就可以采用实体类来实现。
public class User {
private String name;
private String sex;
private Integer age;
//getter and setter
}
public class ESTestDocInsert {
public static void main(String[] args) throws IOException {
//创建ES客户端
RestHighLevelClient esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
//创建文档 --- 请求对象
IndexRequest request = new IndexRequest();
//设置索引及索引中文档的唯一性标识id(如果不指定,则ES会默认随机生成一个id)
request.index("user").id("1001");
//创建数据对象(文档内容)
User user = new User();
user.setName("张起灵");
user.setSex("man");
user.setAge(21);
//向ES中插入数据,必须将数据格式转换为JSON
ObjectMapper objectMapper = new ObjectMapper();
String userJson = objectMapper.writeValueAsString(user);
request.source(userJson, XContentType.JSON);
//发送请求 --- 获取响应
IndexResponse response = esClient.index(request, RequestOptions.DEFAULT);
System.out.println(response.getResult());
//关闭ES客户端
esClient.close();
}
}
1.2.6 修改文档
public class ESTestDocUpdate {
public static void main(String[] args) throws IOException {
//创建ES客户端
RestHighLevelClient esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
//修改文档 --- 请求对象
UpdateRequest request = new UpdateRequest();
//配置修改参数 --- 表示要修改user索引中id为1001的文档内容
request.index("user").id("1001");
//将修改后的内容,以JSON格式写入请求体中
request.doc(XContentType.JSON,"age",18);
//发送请求 --- 获取响应
UpdateResponse response = esClient.update(request,RequestOptions.DEFAULT);
System.out.println(response.getResult());
//关闭ES客户端
esClient.close();
}
}
1.2.7 查看文档
public class ESTestDocSearch {
public static void main(String[] args) throws IOException {
//创建ES客户端
RestHighLevelClient esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
//查询文档 --- 请求对象
GetRequest request = new GetRequest();
//设置请求参数 --- 表示要查询user索引中id为1001的文档内容
request.index("user").id("1001");
//发送请求 --- 获取响应
GetResponse response = esClient.get(request,RequestOptions.DEFAULT);
System.out.println(response.getSourceAsString());
//关闭ES客户端
esClient.close();
}
}
1.2.8 删除文档
public class ESTestDocDelete {
public static void main(String[] args) throws IOException {
//创建ES客户端
RestHighLevelClient esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
//删除文档 --- 请求对象
DeleteRequest request = new DeleteRequest();
//设置请求参数 --- 表示要删除user索引中id为1001的文档
request.index("user").id("1001");
//发送请求 --- 获取响应
DeleteResponse response = esClient.delete(request,RequestOptions.DEFAULT);
System.out.println(response.getResult());
//关闭ES客户端
esClient.close();
}
}
1.2.9 批量创建文档
public class ESTestDocInsertBatch {
public static void main(String[] args) throws IOException {
//创建ES客户端
RestHighLevelClient esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
//批量新增文档 --- 请求对象
BulkRequest request = new BulkRequest();
//以JSON格式批量新增文档 --- 存入请求体中
request.add(new IndexRequest().index("user").id("1001").source(XContentType.JSON, "name", "张起灵","sex","boy","age",21));
request.add(new IndexRequest().index("user").id("1002").source(XContentType.JSON, "name", "小哥","sex","boy","age",18));
request.add(new IndexRequest().index("user").id("1003").source(XContentType.JSON, "name", "小宋","sex","boy","age",20));
//发送请求 --- 获取响应
BulkResponse response = esClient.bulk(request, RequestOptions.DEFAULT);
System.out.println(response.getTook());
//关闭ES客户端
esClient.close();
}
}
1.2.10 批量删除文档
public class ESTestDocDeleteBatch {
public static void main(String[] args) throws IOException {
//创建ES客户端
RestHighLevelClient esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
//批量删除文档 --- 请求对象
BulkRequest request = new BulkRequest();
//将要删除的文档id存入请求体中
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 response = esClient.bulk(request,RequestOptions.DEFAULT);
System.out.println(response.getTook());
System.out.println(response.getItems());
//关闭ES客户端
esClient.close();
}
}
1.2.11 全量查询
因为上面两个代码案例分别进行了批量创建、批量删除。所以这里首先执行一次批量创建的代码,确保索引中有多条数据供我们查询。
public class ESTestDocInsertBatch {
public static void main(String[] args) throws IOException {
//创建ES客户端
RestHighLevelClient esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
//批量新增文档 --- 请求对象
BulkRequest request = new BulkRequest();
//以JSON格式批量新增文档 --- 存入请求体中
request.add(new IndexRequest().index("user").id("1001").source(XContentType.JSON, "name", "张起灵","sex","boy","age",21));
request.add(new IndexRequest().index("user").id("1002").source(XContentType.JSON, "name", "小哥","sex","boy","age",18));
request.add(new IndexRequest().index("user").id("1003").source(XContentType.JSON, "name", "小宋","sex","boy","age",20));
request.add(new IndexRequest().index("user").id("1004").source(XContentType.JSON, "name", "冷少","sex","boy","age",25));
request.add(new IndexRequest().index("user").id("1005").source(XContentType.JSON, "name", "Java软件工程师","sex","girl","age",40));
//发送请求 --- 获取响应
BulkResponse response = esClient.bulk(request, RequestOptions.DEFAULT);
System.out.println(response.getTook());
//关闭ES客户端
esClient.close();
}
}
下面首先进行全量查询操作。
public class ESTestDocQuery {
public static void main(String[] args) throws IOException {
//创建ES客户端
RestHighLevelClient esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
//1.查询索引中的全部文档 --- matchAllQuery 全量查询
//创建搜索请求对象
SearchRequest request = new SearchRequest();
//设置参数 --- 表示查询哪个索引中的文档内容
request.indices("user");
//构建查询的请求体 --- 存入搜索请求对象中
request.source(new SearchSourceBuilder().query(QueryBuilders.matchAllQuery()));
//发送请求 --- 获取响应
SearchResponse response = esClient.search(request,RequestOptions.DEFAULT);
//获取查询到的结果集
SearchHits hits = response.getHits();
System.out.println(hits.getTotalHits()); //结果集的条数
System.out.println(response.getTook()); //总耗时
//遍历结果集
for (SearchHit hit : hits) {
System.out.println(hit.getSourceAsString());
}
//关闭ES客户端
esClient.close();
}
}
1.2.12 条件查询
做匹配查询,查询年龄age=21的文档内容。
public class ESTestDocQuery {
public static void main(String[] args) throws IOException {
//创建ES客户端
RestHighLevelClient esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
//2.条件查询--- termQuery age=21
//创建搜索请求对象
SearchRequest request = new SearchRequest();
//设置参数 --- 表示查询哪个索引中的文档内容
request.indices("user");
//构建查询的请求体 --- 存入搜索请求对象中
request.source(new SearchSourceBuilder().query(QueryBuilders.termQuery("age",21)));
//发送请求 --- 获取响应
SearchResponse response = esClient.search(request,RequestOptions.DEFAULT);
//获取查询到的结果集
SearchHits hits = response.getHits();
System.out.println(hits.getTotalHits()); //结果集的条数
System.out.println(response.getTook()); //总耗时
//遍历结果集
for (SearchHit hit : hits) {
System.out.println(hit.getSourceAsString());
}
//关闭ES客户端
esClient.close();
}
}
1.2.13 分页查询
做全量查询,对查询结果进行分页显示,每页2条数据,查询第1页。
查看第几页:(页码 - 1)*每页条数
public class ESTestDocQuery {
public static void main(String[] args) throws IOException {
//创建ES客户端
RestHighLevelClient esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
//3.分页查询
//创建搜索请求对象
SearchRequest request = new SearchRequest();
//设置参数 --- 表示查询哪个索引中的文档内容
request.indices("user");
//构建查询的请求体
SearchSourceBuilder builder = new SearchSourceBuilder().query(QueryBuilders.matchAllQuery());
builder.from(0);
builder.size(2);
//将构建好的查询请求体存入搜索请求对象中
request.source(builder);
//发送请求 --- 获取响应
SearchResponse response = esClient.search(request,RequestOptions.DEFAULT);
//获取查询到的结果集
SearchHits hits = response.getHits();
System.out.println(hits.getTotalHits()); //结果集的条数
System.out.println(response.getTook()); //总耗时
//遍历结果集
for (SearchHit hit : hits) {
System.out.println(hit.getSourceAsString());
}
//关闭ES客户端
esClient.close();
}
}
1.2.14 排序查询
做全量查询,对查询结果中的年龄age字段做降序排序。
public class ESTestDocQuery {
public static void main(String[] args) throws IOException {
//创建ES客户端
RestHighLevelClient esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
//4.对查询结果进行排序
//创建搜索请求对象
SearchRequest request = new SearchRequest();
//设置参数 --- 表示查询哪个索引中的文档内容
request.indices("user");
//构建查询的请求体
SearchSourceBuilder builder = new SearchSourceBuilder().query(QueryBuilders.matchAllQuery());
builder.sort("age", SortOrder.DESC);
//将构建好的查询请求体存入搜索请求对象中
request.source(builder);
//发送请求 --- 获取响应
SearchResponse response = esClient.search(request,RequestOptions.DEFAULT);
//获取查询到的结果集
SearchHits hits = response.getHits();
System.out.println(hits.getTotalHits()); //结果集的条数
System.out.println(response.getTook()); //总耗时
//遍历结果集
for (SearchHit hit : hits) {
System.out.println(hit.getSourceAsString());
}
//关闭ES客户端
esClient.close();
}
}
1.2.15 过滤字段查询
做全量查询,同时排除性别sex字段。
public class ESTestDocQuery {
public static void main(String[] args) throws IOException {
//创建ES客户端
RestHighLevelClient esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
//5.过滤字段
//创建搜索请求对象
SearchRequest request = new SearchRequest();
//设置参数 --- 表示查询哪个索引中的文档内容
request.indices("user");
//构建查询的请求体
SearchSourceBuilder builder = new SearchSourceBuilder().query(QueryBuilders.matchAllQuery());
String[] excludes = {"sex"};
String[] includes = {};
builder.fetchSource(includes,excludes);
//将构建好的查询请求体存入搜索请求对象中
request.source(builder);
//发送请求 --- 获取响应
SearchResponse response = esClient.search(request,RequestOptions.DEFAULT);
//获取查询到的结果集
SearchHits hits = response.getHits();
System.out.println(hits.getTotalHits()); //结果集的条数
System.out.println(response.getTook()); //总耗时
//遍历结果集
for (SearchHit hit : hits) {
System.out.println(hit.getSourceAsString());
}
//关闭ES客户端
esClient.close();
}
}
1.2.16 组合条件查询
查询年龄 age=18 或者 name=张起灵 的文档内容。文章来源:https://www.toymoban.com/news/detail-474575.html
public class ESTestDocQuery {
public static void main(String[] args) throws IOException {
//创建ES客户端
RestHighLevelClient esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
//6.组合查询
//创建搜索请求对象
SearchRequest request = new SearchRequest();
//设置参数 --- 表示查询哪个索引中的文档内容
request.indices("user");
//构建查询的请求体
SearchSourceBuilder builder = new SearchSourceBuilder();
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
boolQueryBuilder.should(QueryBuilders.matchQuery("age",18));
boolQueryBuilder.should(QueryBuilders.matchQuery("name","张起灵"));
builder.query(boolQueryBuilder);
//将构建好的查询请求体存入搜索请求对象中
request.source(builder);
//发送请求 --- 获取响应
SearchResponse response = esClient.search(request,RequestOptions.DEFAULT);
//获取查询到的结果集
SearchHits hits = response.getHits();
System.out.println(hits.getTotalHits()); //结果集的条数
System.out.println(response.getTook()); //总耗时
//遍历结果集
for (SearchHit hit : hits) {
System.out.println(hit.getSourceAsString());
}
//关闭ES客户端
esClient.close();
}
}
RestClient.builder(new HttpHost("localhost",9200,"http"))
二、参考链接
[01] 分布式全文搜索引擎 Elasticsearch文章来源地址https://www.toymoban.com/news/detail-474575.html
到了这里,关于552、Elasticsearch详细入门教程系列 -【分布式全文搜索引擎 Elasticsearch(三)】 2023.05.19的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!