2.Java API操作elasticsearch
新建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>
客户端连接:
public class ESTest_Client {
public static void main(String[] args) throws IOException {
// 创建客户端对象,高级别客户端,你需要连接服务器,需要知道ip端口号,访问方式
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost", 9200, "http")));
//业务逻辑
System.out.println(client);
// 关闭客户端连接
client.close();
}
}
4.2 索引操作
4.2.1 创建索引
public static void main(String[] args) throws IOException {
// 创建客户端对象,高级别客户端,你需要连接服务器,需要知道ip端口号,访问方式
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost", 9200, "http")));
//业务逻辑
System.out.println(client);
// 创建索引,先拿到索引,然后创建,第一个参数是请求对象,后面是选项
CreateIndexRequest request = new CreateIndexRequest("user");//索引名称
// 发完请求,就会有响应
CreateIndexResponse response = client.indices().create(request, RequestOptions.DEFAULT);// 默认请求配置
// 响应的状态
boolean acknowledged = response.isAcknowledged();
//输出true
System.out.println(acknowledged);
// 关闭客户端连接
client.close();
}
查询所有索引发现索引创建成功!
4.2.2 索引查询
public class ESTest_Index_Search {
public static void main(String[] args) throws IOException {
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost", 9200, "http")));
// 查询索引
GetIndexRequest request = new GetIndexRequest("user");
GetIndexResponse response = client.indices().get(request, RequestOptions.DEFAULT);
// 别名操作
System.out.println(response.getAliases());
// 结构
System.out.println(response.getMappings());
client.close();
}
}
输出:
{user=[]}
{user=org.elasticsearch.cluster.metadata.MappingMetadata@e2704661}
4.2.3 索引删除
public class DeleteIndex {
public static void main(String[] args) throws IOException {
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost", 9200, "http")));
// 删除索引 - 请求对象
DeleteIndexRequest request = new DeleteIndexRequest("user");
// 发送请求,获取响应
AcknowledgedResponse response = client.indices().delete(request,RequestOptions.DEFAULT);
// 操作结果
System.out.println("操作结果 : " + response.isAcknowledged());
client.close();
}
}
输出true:
4.3 文档操作
4.3.1 新建实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private String name;
private String sex;
private Integer age;
}
4.3.2 插入数据
public class ESTest_Doc_Insert {
public static void main(String[] args) throws IOException {
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost", 9200, "http")));
// 插入数据,这里需要的是index
IndexRequest indexRequest = new IndexRequest();
// 索引名字,索引的id
indexRequest.index("user").id("1001");
User user = new User();
user.setName("zhangsan");
user.setAge(30);
user.setSex("男");
// 向ES插入数据,必须将数据转换为json格式
ObjectMapper mapper = new ObjectMapper();
String value = mapper.writeValueAsString(user);
// 放到请求体中
indexRequest.source(value, XContentType.JSON);
IndexResponse response = client.index(indexRequest, RequestOptions.DEFAULT);
//输出:CREATED
System.out.println(response.getResult());
client.close();
}
}
postman获取文档,发现其已经创建成功!
4.3.3 修改数据
public class ESTest_Doc_Update {
public static void main(String[] args) throws IOException {
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost", 9200, "http")));
//修改数据
UpdateRequest request=new UpdateRequest();
request.index("user").id("1001");
request.doc(XContentType.JSON,"sex","女");
UpdateResponse response = client.update(request, RequestOptions.DEFAULT);
//输出:UPDATED
System.out.println(response.getResult());
client.close();
}
}
4.3.4 查询数据
/**
* 查询数据
*/
public class ESTest_Doc_Query {
public static void main(String[] args) throws IOException {
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost", 9200, "http")));
GetRequest request=new GetRequest().index("user").id("1001");
GetResponse response = client.get(request, RequestOptions.DEFAULT);
//打印信息
System.out.println("_index:" + response.getIndex());
System.out.println("_type:" + response.getType());
System.out.println("_id:" + response.getId());
System.out.println("source:" + response.getSourceAsString());
}
}
输出:
_index:user
_type:_doc
_id:1001
source:{"name":"zhangsan","sex":"女","age":30}
4.3.5 数据删除
/**
* 删除数据
*/
public class ESTest_Doc_Delete {
public static void main(String[] args) throws IOException {
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost", 9200, "http")));
//创建请求对象
DeleteRequest request = new DeleteRequest().index("user").id("1001");
//客户端发送请求,获取响应对象
DeleteResponse response = client.delete(request, RequestOptions.DEFAULT);
//打印信息
System.out.println(response.toString());
}
}
输出:
DeleteResponse[index=user,type=_doc,id=1001,version=3,result=deleted,shards=ShardInfo{total=2, successful=1, failures=[]}]
4.3.6 批量增加
public class ESTest_Doc_Insert_Batch {
public static void main(String[] args) throws IOException {
RestHighLevelClient client = 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","lisi"));
bulkRequest.add(new IndexRequest().index("user").id("1002").source(XContentType.JSON,"name","lisi"));
bulkRequest.add(new IndexRequest().index("user").id("1003").source(XContentType.JSON,"name","wangwu"));
BulkResponse response = client.bulk(bulkRequest, RequestOptions.DEFAULT);
System.out.println(response.getTook());// 花费时间
System.out.println(response.getItems());
client.close();
}
}
4.3.7 批量删除
/**
* 批量删除
*/
public class ESTest_Doc_Delete_Batch {
public static void main(String[] args) throws IOException {
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost", 9200, "http")));
//创建批量删除请求对象
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());
client.close();
}
}
4.3.8 查询全部数据
/**
* 条件查询:查询所有
*/
public class ESTest_Doc_Query {
public static void main(String[] args) throws IOException {
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost", 9200, "http")));
// 查询索引中全部数据
SearchRequest request = new SearchRequest().indices("user");
//matchAllQuery查询所有
SearchSourceBuilder builder = new SearchSourceBuilder().query(QueryBuilders.matchAllQuery());
request.source(builder);
SearchResponse response = client.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());
}
client.close();
}
}
里面构造器有个查询条件:
输出:
3 hits
2ms
{"name":"lisi","age":18}
{"name":"lisi"}
{"name":"wangwu"}
4.3.9 条件查询
// 查询年龄为30的数据
SearchSourceBuilder builder = new SearchSourceBuilder().query(QueryBuilders.termQuery("age", 30));
4.3.10 分页查询
package cn.com.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.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import java.io.IOException;
/**
* 分页查询
*/
public class QueryDoc {
public static void main(String[] args) throws IOException {
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost", 9200, "http")));
// 创建搜索请求对象
SearchRequest request = new SearchRequest();
request.indices("user");
// 构建查询的请求体
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("<<========");
}
}
输出:
took:2ms
timeout:false
total:3 hits
MaxScore:1.0
hits========>>
{"name":"lisi","age":18}
{"name":"lisi"}
<<========
4.3.11 排序查询
public class QueryDoc {
public static void main(String[] args) throws IOException {
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost", 9200, "http")));
// 创建搜索请求对象
SearchRequest request = new SearchRequest();
request.indices("user");
// 构建查询的请求体
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("<<========");
client.close();
}
}
输出:
took:529ms
timeout:false
total:3 hits
MaxScore:NaN
hits========>>
{"name":"lisi","age":5}
{"name":"lisi","age":18}
{"name":"wangwu","age":99}
<<========
4.3.12 过滤字段
public class QueryDoc {
public static void main(String[] args) throws IOException {
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost", 9200, "http")));
// 创建搜索请求对象
SearchRequest request = new SearchRequest().indices("user");
// 构建查询的请求体
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
//排除什么
//过滤字段
String[] excludes={};
String[] includes={"name"};
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("<<========");
client.close();
}
}
输出:
took:1ms
timeout:false
total:3 hits
MaxScore:1.0
hits========>>
{"name":"lisi"}
{"name":"lisi"}
{"name":"wangwu"}
<<========
4.3.13 组合查询(多条件)
public class QueryDoc {
public static void main(String[] args) throws IOException {
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost", 9200, "http")));
// 创建搜索请求对象
SearchRequest request = new SearchRequest();
request.indices("user");
// 构建查询的请求体
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("<<========");
client.close();
}
}
输出:
took:2ms
timeout:false
total:1 hits
MaxScore:1.0
hits========>>
{"name":"lisi","age":30}
<<========
4.3.14 范围查询
public class QueryDoc {
public static void main(String[] args) throws IOException {
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost", 9200, "http")));
// 创建搜索请求对象
SearchRequest request = new SearchRequest();
request.indices("user");
// 构建查询的请求体
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("<<========");
client.close();
}
}
4.3.15 模糊查询
public class QueryDoc {
public static void main(String[] args) throws IOException {
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost", 9200, "http")));
// 创建搜索请求对象
SearchRequest request = new SearchRequest();
request.indices("user");
// 构建查询的请求体
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
//有一个字符的不同也可以查出来
sourceBuilder.query(QueryBuilders.fuzzyQuery("name","wangwu").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("<<========");
client.close();
}
}
输出:发现名字wangwu,多一个字符,少一个字符都可以查询出来
took:968ms
timeout:false
total:5 hits
MaxScore:1.8382792
hits========>>
{"name":"wangwu","age":99,"sex":"男"}
{"name":"wangwu1","age":99,"sex":"男"}
{"name":"wangwu2","age":99,"sex":"男"}
{"name":"wangwu3","age":99,"sex":"男"}
{"name":"wangw","age":99,"sex":"男"}
<<========
4.3.16 高亮查询
public class QueryDoc {
public static void main(String[] args) throws IOException {
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost", 9200, "http")));
// 高亮查询
SearchRequest request = new SearchRequest().indices("user");
//2.创建查询请求体构建器
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
//构建查询方式:高亮查询
TermsQueryBuilder termsQueryBuilder =
QueryBuilders.termsQuery("name","wangwu");
//设置查询方式
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("<<::::");
client.close();
}
}
输出:
took::60ms
time_out::false
total::1 hits
max_score::1.0
hits::::>>
{"name":"wangwu","age":99,"sex":"男"}
{name=[name], fragments[[<font color='red'>wangwu</font>]]}
<<::::
4.3.17 聚合查询
public class QueryDoc {
public static void main(String[] args) throws IOException {
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost", 9200, "http")));
SearchRequest request = new SearchRequest().indices("user");
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);
client.close();
}
}
输出:
{
"took": 34,
"timed_out": false,
"_shards": {
"total": 1,
"successful": 1,
"skipped": 0,
"failed": 0
},
"hits": {
"total": {
"value": 7,
"relation": "eq"
},
"max_score": 1.0,
"hits": [{
"_index": "user",
"_type": "_doc",
"_id": "1001",
"_score": 1.0,
"_source": {
"name": "lisi",
"age": 30,
"sex": "男"
}
}, {
"_index": "user",
"_type": "_doc",
"_id": "1002",
"_score": 1.0,
"_source": {
"name": "lisi",
"age": 5,
"sex": "男"
}
}, {
"_index": "user",
"_type": "_doc",
"_id": "1003",
"_score": 1.0,
"_source": {
"name": "wangw",
"age": 99,
"sex": "男"
}
}, {
"_index": "user",
"_type": "_doc",
"_id": "1004",
"_score": 1.0,
"_source": {
"name": "wangwu",
"age": 99,
"sex": "男"
}
}, {
"_index": "user",
"_type": "_doc",
"_id": "1005",
"_score": 1.0,
"_source": {
"name": "wangwu1",
"age": 99,
"sex": "男"
}
}, {
"_index": "user",
"_type": "_doc",
"_id": "1006",
"_score": 1.0,
"_source": {
"name": "wangwu2",
"age": 99,
"sex": "男"
}
}, {
"_index": "user",
"_type": "_doc",
"_id": "1007",
"_score": 1.0,
"_source": {
"name": "wangwu3",
"age": 99,
"sex": "男"
}
}]
},
"aggregations": {
"lterms#age_groupby": {
"doc_count_error_upper_bound": 0,
"sum_other_doc_count": 0,
"buckets": [{
"key": 99,
"doc_count": 5
}, {
"key": 5,
"doc_count": 1
}, {
"key": 30,
"doc_count": 1
}]
}
}
}
分类:
elasticsearch
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构