本次使用 elasticsearch 版本为7.17.0,建议使用 7.X 版本,8.1.2版本会遇到一些 Springboot(本人使用版本2.6.6) 版本不兼容的问题。此文章会列举一个例子。
导包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
创建客户端
我们在测试类中先创建一个客户端,用来向 ES 发送请求
//创建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();
控制台输出信息如下:
此处会遇到坑:
运行之后报错信息如下:
Exception in thread "main" ElasticsearchStatusException[Elasticsearch exception [type=illegal_argument_exception, reason=request [/book] contains unrecognized parameter: [include_type_name]]]
原因是:CreateIndexRequest 对象有两个,导报如果是下面这个包就会报错,因为已经不推荐使用此对象去创建索引,可以看到 create() 方法也有不推荐的横线
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
应该导包如下:
import org.elasticsearch.client.indices.CreateIndexRequest;
查看索引
测试代码如下:
//查询索引
GetIndexRequest getIndexRequest = new GetIndexRequest("user");
GetIndexResponse getIndexResponse = esClient.indices().get(getIndexRequest, RequestOptions.DEFAULT);
//相应状态
System.out.println(getIndexResponse.getSettings());
//关闭ES客户端
esClient.close();
控制台输出信息如下:
{user={"index.creation_date":"1650436113234","index.number_of_replicas":"1","index.number_of_shards":"1","index.provided_name":"user","index.routing.allocation.include._tier_preference":"data_content","index.uuid":"XhZ5LlZxSJaVG3Zmjs4YJQ","index.version.created":"8010299"}}
删除索引
测试代码如下:
//删除索引
DeleteIndexRequest user = new DeleteIndexRequest("user");
AcknowledgedResponse delete = esClient.indices().delete(user, RequestOptions.DEFAULT);
//相应状态
System.out.println("delete:" + delete.isAcknowledged());
//关闭ES客户端
esClient.close();
控制台输出信息如下:
文档操作
新增文档
测试代码如下:
//创建请求对象(指明索引和ID)
IndexRequest request = new IndexRequest();
request.index("user").id("1001");
User user = new User();
user.setName("wangda");
user.setAge(30);
user.setSex("男");
ObjectMapper mapper = new ObjectMapper();
String userJson = mapper.writeValueAsString(user);
request.source(userJson, XContentType.JSON);
IndexResponse response = esClient.index(request, RequestOptions.DEFAULT);
System.out.println(response.getResult());
//关闭ES客户端
esClient.close();
此时遇到 ES8.1.2 版本与 Springboot 不兼容的问题:
报错信息如下:
ElasticsearchException[java.util.concurrent.ExecutionException: java.net.ConnectException: Timeout connecting to [/10.253.117.204:9200]
但是通过 ApiPost 查看数据已插入
经测试,ES 7.17.0 版本正常!
批量新增文档
测试代码如下:
//创建批量新增请求对象
BulkRequest request = new BulkRequest();
request.add(new IndexRequest().index("user").id("1002").source(XContentType.JSON, "name", "猪八戒", "age", 20, "sex", "男"));
request.add(new IndexRequest().index("user").id("1003").source(XContentType.JSON, "name", "沙悟净", "age", 18, "sex", "男"));
request.add(new IndexRequest().index("user").id("1004").source(XContentType.JSON, "name", "白龙马", "age", 16, "sex", "女"));
//客户端发送请求
BulkResponse response = esClient.bulk(request, RequestOptions.DEFAULT);
//打印结果信息
System.out.println("took:" + response.getTook());
System.out.println("items:" + response.getItems());
//关闭ES客户端
esClient.close();
控制台输出信息如下:
根据ID查询文档
测试代码如下:
GetRequest request = new GetRequest();
request.index("user").id("1001");
GetResponse response = esClient.get(request, RequestOptions.DEFAULT);
System.out.println(response.getSourceAsString());
//关闭ES客户端
esClient.close();
控制台输出结果如下:
查询所有文档
测试代码如下:
//创建搜索请求对象
SearchRequest request = new SearchRequest();
request.indices("user");
//构建查询的请求体
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
//查询所有数据
sourceBuilder.query(QueryBuilders.matchAllQuery());
request.source(sourceBuilder);
SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
//查询匹配
SearchHits hits = response.getHits();
for (SearchHit hit : hits) {
System.out.println(hit.getSourceAsString());
}
//关闭ES客户端
esClient.close();
控制台响应结果如下:
根据ID删除文档
测试代码如下:
//创建删除请求对象
DeleteRequest request = new DeleteRequest();
request.index("user").id("1001");
DeleteResponse delete = esClient.delete(request, RequestOptions.DEFAULT);
System.out.println(delete.getResult());
//关闭ES客户端
esClient.close();
控制台响应结果如下:
批量删除文档
测试代码如下:
//创建批量删除请求对象
BulkRequest request = new BulkRequest();
request.add(new DeleteRequest().index("user").id("1002"));
request.add(new DeleteRequest().index("user").id("1003"));
request.add(new DeleteRequest().index("user").id("1004"));
//客户端发送请求
BulkResponse response = esClient.bulk(request, RequestOptions.DEFAULT);
//打印结果信息
System.out.println("took:" + response.getTook());
System.out.println("items:" + response.getItems());
//关闭ES客户端
esClient.close();
控制台响应结果如下:
修改文档
测试代码如下:
//创建修改请求对象
UpdateRequest request = new UpdateRequest();
request.index("user").id("101");
request.doc(XContentType.JSON, "name", "孙悟空");
UpdateResponse update = esClient.update(request, RequestOptions.DEFAULT);
System.out.println(update.getResult());
//关闭ES客户端
esClient.close();
控制台响应结果如下:
高级查询
条件查询
测试代码如下:
//创建搜索请求对象
SearchRequest request = new SearchRequest();
request.indices("user");
//构建查询请求体
request.source(new SearchSourceBuilder().query(QueryBuilders.matchQuery("age", 30)));
SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
//查询匹配
SearchHits hits = response.getHits();
for (SearchHit hit : hits) {
System.out.println(hit);
}
控制台输出结果如下:
分页查询
测试代码如下:
//创建搜索请求对象
SearchRequest request = new SearchRequest();
request.indices("user");
//构建查询的请求体
request.source(new SearchSourceBuilder().query(QueryBuilders.matchAllQuery()).from(0).size(2));
SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
for (SearchHit hit : hits) {
System.out.println(hit);
}
控制台输出信息如下:
排序
测试代码如下:
//创建搜索请求对象
SearchRequest request = new SearchRequest();
request.indices("user");
//构建查询请求体
request.source(new SearchSourceBuilder().query(QueryBuilders.matchAllQuery()).sort("age", SortOrder.DESC));
SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
for (SearchHit hit : hits) {
System.out.println(hit);
}
控制台输出信息如下:
{
"_index" : "user",
"_type" : "_doc",
"_id" : "1001",
"_score" : null,
"_source" : {
"name" : "孙悟空",
"age" : 30,
"sex" : "男"
},
"sort" : [
30
]
}
{
"_index" : "user",
"_type" : "_doc",
"_id" : "1002",
"_score" : null,
"_source" : {
"name" : "猪八戒",
"age" : 20,
"sex" : "男"
},
"sort" : [
20
]
}
{
"_index" : "user",
"_type" : "_doc",
"_id" : "1003",
"_score" : null,
"_source" : {
"name" : "沙悟净",
"age" : 18,
"sex" : "男"
},
"sort" : [
18
]
}
{
"_index" : "user",
"_type" : "_doc",
"_id" : "1004",
"_score" : null,
"_source" : {
"name" : "白龙马",
"age" : 16,
"sex" : "女"
},
"sort" : [
16
]
}
过滤字段(返回指定字段)
测试代码如下:
//创建搜索请求对象
SearchRequest request = new SearchRequest();
request.indices("user");
//构建查询请求体
//过滤字段
String[] excludes = {"age"};//排除字段
String[] includes = {};//包含字段
request.source(new SearchSourceBuilder().query(QueryBuilders.matchAllQuery()).fetchSource(includes, excludes));
SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
for (SearchHit hit : hits) {
System.out.println(hit);
}
控制台输出信息如下:
范围查询
测试代码如下:
//创建请求对象
SearchRequest request = new SearchRequest();
request.indices("user");
//构建查询请求体
//大于等于
//小于等于
request.source(new SearchSourceBuilder().query(new RangeQueryBuilder("age").gte("20").lte("30")));
SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
for (SearchHit hit : hits) {
System.out.println(hit);
}
控制台输出信息如下:
模糊查询(相似的意思)
测试代码如下:
//创建请求对象
SearchRequest request = new SearchRequest();
request.indices("user");
//构建请求体(这里的name故意写错一个字母wangdb,真实数据是wangda)
request.source(new SearchSourceBuilder().query(QueryBuilders.fuzzyQuery("name", "wangdb").fuzziness(Fuzziness.ONE)));
SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
for (SearchHit hit : hits) {
System.out.println(hit);
}
}
控制台输出信息如下:
模糊查询(类似于MySQl的like)
测试代码如下:
//创建请求对象
SearchRequest request = new SearchRequest();
request.indices("user");
//构建请求体(*类似于MySQL中的%,是通配符,表示零个或多个字符,?表示一个字符)
request.source(new SearchSourceBuilder().query(QueryBuilders.wildcardQuery("name", "*悟*")));
SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
for (SearchHit hit : hits) {
System.out.println(hit);
}
控制台输出信息如下:
高亮查询
测试代码如下:
//创建请求对象
SearchRequest request = new SearchRequest().indices("user");
//构建请求体
//创建查询请求体构建器
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
//构建查询方式:高亮查询
MatchPhraseQueryBuilder matchPhraseQueryBuilder = QueryBuilders.matchPhraseQuery("name", "孙悟空");
//构建高亮字段
HighlightBuilder highlightBuilder = new HighlightBuilder();
highlightBuilder.preTags("<font color='red'>");//设置标签前缀
highlightBuilder.postTags("</font>");//设置标签后缀
highlightBuilder.field("name");//设置高亮字段
//设置高亮构建对象
sourceBuilder.highlighter(highlightBuilder);
//设置查询方式
sourceBuilder.query(matchPhraseQueryBuilder);
//设置请求体
request.source(sourceBuilder);
SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
for (SearchHit hit : hits) {
System.out.println(hit);
}
控制台输出信息如下:
bool查询
测试代码如下:
//创建搜索请求对象
SearchRequest request = new SearchRequest();
request.indices("user");
//构建查询请求体
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
//必须包含(30岁的男性)
boolQueryBuilder.must(QueryBuilders.matchQuery("age", 30));
boolQueryBuilder.must(QueryBuilders.matchQuery("sex", "男"));
//必须不
// boolQueryBuilder.mustNot(QueryBuilders.matchQuery("name","孙"));
//可能包含
// boolQueryBuilder.should(QueryBuilders.matchQuery("name","白"));
sourceBuilder.query(boolQueryBuilder);
request.source(sourceBuilder);
SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
for (SearchHit hit : hits) {
System.out.println(hit);
}
控制台输出信息如下:
文章来源:https://www.toymoban.com/news/detail-408129.html
bool查询可以组合各种复杂的条件查询,比如类似于MySQL中的:where 条件1 and (条件2 or 条件3)文章来源地址https://www.toymoban.com/news/detail-408129.html
到了这里,关于java Api操作Elasticsearch的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!