1. elasticsearch 简介
elasticsearch 是一个分布式搜索和分析引擎,基于 apache lucene 构建,能够实现实时数据的存储、搜索、和分析。它广泛应用于全文搜索、日志分析、性能监控等领域。elasticsearch 的核心概念包括文档(document)、索引(index)、和分片(shard)。
2. 环境准备
2.1 安装 elasticsearch
从 elasticsearch 官方网站 下载并安装适合你操作系统的版本。
安装完成后,通过以下命令启动 elasticsearch 服务:
./bin/elasticsearch
默认情况下,elasticsearch 运行在 http://localhost:9200。
2.2 java 开发环境配置
- 安装 java sdk(jdk 11 或更高版本)。
- 安装 maven 或 gradle。
- 创建一个 maven 项目,添加 elasticsearch java 客户端的依赖。
2.3 添加 elasticsearch 客户端依赖
在 maven 项目的 pom.xml 文件中添加以下依赖:
<dependencies>
<!-- elasticsearch java client -->
<dependency>
<groupid>co.elastic.clients</groupid>
<artifactid>elasticsearch-java</artifactid>
<version>8.10.0</version>
</dependency>
</dependencies>如果你使用 gradle,可以在 build.gradle 文件中添加以下依赖:
dependencies {
implementation 'co.elastic.clients:elasticsearch-java:8.10.0'
}添加依赖后,确保项目能够正常编译。
3. 使用 java 连接 elasticsearch
接下来,我们将编写一个简单的 java 程序来连接 elasticsearch。
3.1 编写连接代码
创建一个 java 类,例如 elasticsearchconnection.java,并编写以下代码:
import co.elastic.clients.elasticsearch.elasticsearchclient;
import co.elastic.clients.elasticsearch.core.inforesponse;
import co.elastic.clients.transport.rest_client.restclienttransport;
import co.elastic.clients.json.jackson.jacksonjsonpmapper;
import org.apache.http.httphost;
import org.elasticsearch.client.restclient;
public class elasticsearchconnection {
public static void main(string[] args) throws exception {
// 创建 rest 客户端
restclient restclient = restclient.builder(
new httphost("localhost", 9200, "http")).build();
// 创建传输层
restclienttransport transport = new restclienttransport(
restclient, new jacksonjsonpmapper());
// 创建 elasticsearch 客户端
elasticsearchclient client = new elasticsearchclient(transport);
// 获取集群信息
inforesponse info = client.info();
system.out.println("connected to elasticsearch cluster: " + info.clustername());
// 关闭客户端
transport.close();
}
}3.2 运行代码
编译并运行这个程序,如果成功,你将看到类似如下的输出:
connected to elasticsearch cluster: elasticsearch
这表明你已经成功连接到了 elasticsearch。
4. 基本 crud 操作
elasticsearch 的 crud 操作主要涉及对索引中的文档进行增(create)、查(read)、改(update)、删(delete)操作。
4.1 创建索引和插入文档
import co.elastic.clients.elasticsearch.elasticsearchclient;
import co.elastic.clients.elasticsearch.core.indexresponse;
import co.elastic.clients.transport.rest_client.restclienttransport;
import co.elastic.clients.json.jackson.jacksonjsonpmapper;
import org.apache.http.httphost;
import org.elasticsearch.client.restclient;
import co.elastic.clients.elasticsearch.core.indexrequest;
public class elasticsearchcrud {
public static void main(string[] args) throws exception {
// 创建 rest 客户端
restclient restclient = restclient.builder(
new httphost("localhost", 9200, "http")).build();
// 创建传输层
restclienttransport transport = new restclienttransport(
restclient, new jacksonjsonpmapper());
// 创建 elasticsearch 客户端
elasticsearchclient client = new elasticsearchclient(transport);
// 创建文档
string json = "{ \"name\": \"john doe\", \"age\": 30, \"city\": \"new york\" }";
// 插入文档到索引
indexrequest<object> request = new indexrequest.builder<>()
.index("users")
.id("1")
.document(json)
.build();
indexresponse response = client.index(request);
system.out.println("document inserted with id: " + response.id());
// 关闭客户端
transport.close();
}
}4.2 查询文档
import co.elastic.clients.elasticsearch.elasticsearchclient;
import co.elastic.clients.elasticsearch.core.getresponse;
import co.elastic.clients.transport.rest_client.restclienttransport;
import co.elastic.clients.json.jackson.jacksonjsonpmapper;
import org.apache.http.httphost;
import org.elasticsearch.client.restclient;
import co.elastic.clients.elasticsearch.core.getrequest;
public class elasticsearchread {
public static void main(string[] args) throws exception {
restclient restclient = restclient.builder(
new httphost("localhost", 9200, "http")).build();
restclienttransport transport = new restclienttransport(
restclient, new jacksonjsonpmapper());
elasticsearchclient client = new elasticsearchclient(transport);
// 查询文档
getrequest getrequest = new getrequest.builder()
.index("users")
.id("1")
.build();
getresponse<object> response = client.get(getrequest, object.class);
if (response.found()) {
system.out.println("document found: " + response.source());
} else {
system.out.println("document not found");
}
transport.close();
}
}4.3 更新文档
import co.elastic.clients.elasticsearch.elasticsearchclient;
import co.elastic.clients.elasticsearch.core.updateresponse;
import co.elastic.clients.transport.rest_client.restclienttransport;
import co.elastic.clients.json.jackson.jacksonjsonpmapper;
import org.apache.http.httphost;
import org.elasticsearch.client.restclient;
import co.elastic.clients.elasticsearch.core.updaterequest;
import java.util.map;
public class elasticsearchupdate {
public static void main(string[] args) throws exception {
restclient restclient = restclient.builder(
new httphost("localhost", 9200, "http")).build();
restclienttransport transport = new restclienttransport(
restclient, new jacksonjsonpmapper());
elasticsearchclient client = new elasticsearchclient(transport);
// 更新文档
map<string, object> updatejson = map.of(
"age", 31,
"city", "san francisco"
);
updaterequest<object, map<string, object>> updaterequest = new updaterequest.builder<>()
.index("users")
.id("1")
.doc(updatejson)
.build();
updateresponse<object> updateresponse = client.update(updaterequest, object.class);
system.out.println("document updated: " + updateresponse.result());
transport.close();
}
}4.4 删除文档
import co.elastic.clients.elasticsearch.elasticsearchclient;
import co.elastic.clients.elasticsearch.core.deleteresponse;
import co.elastic.clients.transport.rest_client.restclienttransport;
import co.elastic.clients.json.jackson.jacksonjsonpmapper;
import org.apache.http.httphost;
import org.elasticsearch.client.restclient;
import co.elastic.clients.elasticsearch.core.deleterequest;
public class elasticsearchdelete {
public static void main(string[] args) throws exception {
restclient restclient = restclient.builder(
new httphost("localhost", 9200, "http")).build();
restclienttransport transport = new restclienttransport(
restclient, new jacksonjsonpmapper());
elasticsearchclient client = new elasticsearchclient(transport);
// 删除文档
deleterequest deleterequest = new deleterequest.builder()
.index("users")
.id("1")
.build();
deleteresponse deleteresponse = client.delete(deleterequest);
system.out.println("document deleted: " + deleteresponse.result());
transport.close();
}
}5. 复杂查询操作
elasticsearch 提供了强大的查询 dsl(domain specific language),支持布尔查询、范围查询、聚合查询等。
5.1 布尔查询
import co.elastic.clients.elasticsearch.elasticsearchclient;
import co.elastic.clients.elasticsearch.core.searchresponse;
import co.elastic.clients.elasticsearch.core.search.hit;
import co.elastic.clients.transport.rest_client.restclienttransport;
import co.elastic.clients.json.jackson.jacksonjsonpmapper;
import org.apache.http.httphost;
import org.elasticsearch.client.restclient;
import co.elastic.clients.elasticsearch.core.searchrequest;
import co.elastic.clients.elasticsearch.core.search.query;
public class elasticsearchbooleanquery {
public static void main(string[] args) throws exception {
restclient restclient = restclient.builder(
new httphost("localhost", 9200, "http")).build();
restclienttransport transport = new restclienttransport(
restclient, new jacksonjsonpmapper());
elasticsearchclient client = new elasticsearchclient(transport);
// 布尔查询
searchrequest searchrequest = new searchrequest.builder()
.index("users")
.query(query
.bool(b -> b
.must(m -> m.match(match -> match.field("name").query("john doe")))
.filter(f -> f.range(r -> r.field("age").gte(30)))
))
.build();
searchresponse<object> searchresponse = client.search(searchrequest, object.class);
for (hit<object> hit : searchresponse.hits().hits()) {
system.out.println("document found: " + hit.source());
}
transport.close();
}
}5.2 范围查询
import co.elastic.clients.elasticsearch.elasticsearchclient;
import co.elastic.clients.elasticsearch.core.searchresponse;
import co.elastic.clients.elasticsearch.core.search.hit;
import co.elastic.clients.transport.rest_client.restclienttransport;
import co.elastic.clients.json.jackson.jacksonjsonpmapper;
import org.apache.http.httphost;
import org.elasticsearch.client.restclient;
import co.elastic.clients.elasticsearch.core.searchrequest;
import co.elastic.clients.elasticsearch.core.search.query;
public class elasticsearchrangequery {
public static void main(string[] args) throws exception {
restclient restclient = restclient.builder(
new httphost("localhost", 9200, "http")).build();
restclienttransport transport = new restclienttransport(
restclient, new jacksonjsonpmapper());
elasticsearchclient client = new elasticsearchclient(transport);
// 范围查询:查询 age 在 25 到 35 之间的文档
searchrequest searchrequest = new searchrequest.builder()
.index("users")
.query(query.range(r -> r.field("age").gte(25).lte(35)))
.build();
searchresponse<object> searchresponse = client.search(searchrequest, object.class);
for (hit<object> hit : searchresponse.hits().hits()) {
system.out.println("document found: " + hit.source());
}
transport.close();
}
}6. 索引管理与优化
在 elasticsearch 中,索引管理是非常重要的操作,合理的索引设置和优化可以大幅提升查询性能。
6.1 创建索引并设置映射
import co.elastic.clients.elasticsearch.elasticsearchclient;
import co.elastic.clients.elasticsearch.indices.createindexresponse;
import co.elastic.clients.transport.rest_client.restclienttransport;
import co.elastic.clients.json.jackson.jacksonjsonpmapper;
import org.apache.http.httphost;
import org.elasticsearch.client.restclient;
import co.elastic.clients.elasticsearch.indices.createindexrequest;
public class elasticsearchcreateindex {
public static void main(string[] args) throws exception {
restclient restclient = restclient.builder(
new httphost("localhost", 9200, "http")).build();
restclienttransport transport = new restclienttransport(
restclient, new jacksonjsonpmapper());
elasticsearchclient client = new elasticsearchclient(transport);
// 创建索引并设置映射
createindexrequest createindexrequest = new createindexrequest.builder()
.index("users")
.mappings(m -> m
.properties("name", p -> p.text(t -> t))
.properties("age", p -> p.integer(i -> i))
.properties("city", p -> p.text(t -> t))
)
.build();
createindexresponse createindexresponse = client.indices().create(createindexrequest);
if (createindexresponse.acknowledged()) {
system.out.println("index created successfully!");
}
transport.close();
}
}6.2 删除索引
import co.elastic.clients.elasticsearch.elasticsearchclient;
import co.elastic.clients.elasticsearch.indices.deleteindexresponse;
import co.elastic.clients.transport.rest_client.restclienttransport;
import co.elastic.clients.json.jackson.jacksonjsonpmapper;
import org.apache.http.httphost;
import org.elasticsearch.client.restclient;
import co.elastic.clients.elasticsearch.indices.deleteindexrequest;
public class elasticsearchdeleteindex {
public static void main(string[] args) throws exception {
restclient restclient = restclient.builder(
new httphost("localhost", 9200, "http")).build();
restclienttransport transport = new restclienttransport(
restclient, new jacksonjsonpmapper());
elasticsearchclient client = new elasticsearchclient(transport);
// 删除索引
deleteindexrequest deleteindexrequest = new deleteindexrequest.builder()
.index("users")
.build();
deleteindexresponse deleteindexresponse = client.indices().delete(deleteindexrequest);
if (deleteindexresponse.acknowledged()) {
system.out.println("index deleted successfully!");
}
transport.close();
}
}7. 聚合操作
elasticsearch 的聚合功能非常强大,能够对数据进行分组统计、计算平均值、最大值、最小值等操作。
7.1 聚合查询:计算年龄的平均值
import co.elastic.clients.elasticsearch.elasticsearchclient;
import co.elastic.clients.elasticsearch.core.searchresponse;
import co.elastic.clients.elasticsearch.core.search.hit;
import co.elastic.clients.elasticsearch.core.search.aggregation;
import co.elastic.clients.elasticsearch.core.search.bucket;
import co.elastic.clients.transport.rest_client.restclienttransport;
import co.elastic.clients.json.jackson.jacksonjsonpmapper;
import org.apache.http.httphost;
import org.elasticsearch.client.restclient;
import co.elastic.clients.elasticsearch.core.searchrequest;
public class elasticsearchaggregation {
public static void main(string[] args) throws exception {
restclient restclient = restclient.builder(
new httphost("localhost", 9200, "http")).build();
restclienttransport transport = new restclienttransport(
restclient, new jacksonjsonpmapper());
elasticsearchclient client = new elasticsearchclient(transport);
// 聚合查询:计算年龄的平均值
searchrequest searchrequest = new searchrequest.builder()
.index("users")
.size(0) // 不返回文档,只返回聚合结果
.aggregations("average_age", a -> a.avg(avg -> avg.field("age")))
.build();
searchresponse<object> searchresponse = client.search(searchrequest, object.class);
double averageage = searchresponse.aggregations().get("average_age").avg().value();
system.out.println("average age: " + averageage);
transport.close();
}
}8. 总结
本教程详细介绍了如何在 java 中使用 elasticsearch,涵盖了连接、基本 crud 操作、复杂查询、索引管理和聚合操作等方面的内容。通过这些示例,开发者可以一步步地掌握如何在 java 项目中集成 elasticsearch,并利用其强大的搜索和分析功能来构建高效的应用程序。
到此这篇关于elasticsearch 在 java 中的使用教程的文章就介绍到这了,更多相关java 使用elasticsearch内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论