各语言客户端操作 ES
命令行玩得再熟,最后都要落到业务代码。ES 官方为各语言维护了客户端,但版本演进快、API 变动大,这篇按语言讲清楚「用什么、怎么连、坑在哪」。以 ES 8.x 为主线。
一、Java 客户端:HLRC 已死,新 API Client 当立
Java 生态的客户端历史有点乱,先理清:
| 客户端 | 状态 | 说明 |
|---|---|---|
| TransportClient | 已移除(7.0 删除) | 古老遗产,别找了 |
| High Level REST Client(HLRC) | 8.x 已废弃 | 7.x 时代主力,8.x 标记 deprecated |
| Java API Client(co.elastic.clients) | 8.x 官方主力 | 8.0 起推荐,全新的 fluent API |
1.1 Java API Client(8.x 推荐)
<!-- pom.xml -->
<dependency>
<groupId>co.elastic.clients</groupId>
<artifactId>elasticsearch-java</artifactId>
<version>8.13.4</version>
</dependency>连接和基本操作:
// 创建客户端(默认读取 ELASTICSEARCH_URL 等环境变量,也可代码指定)
RestClient restClient = RestClient.builder(
HttpHost.create("http://localhost:9200")).build();
ElasticsearchTransport transport = new RestClientTransport(
restClient, new JacksonJsonpMapper());
ElasticsearchClient client = new ElasticsearchClient(transport);
// 索引一篇文档
Product product = new Product("1", "机械键盘", 429.0);
IndexResponse response = client.index(i -> i
.index("products")
.id(product.getId())
.document(product)
);
System.out.println(response.result()); // Created / Updated
// 按 ID 查
GetResponse<Product> get = client.get(g -> g
.index("products")
.id("1"),
Product.class
);
System.out.println(get.source().getName());
// 搜索
SearchResponse<Product> search = client.search(s -> s
.index("products")
.query(q -> q
.bool(b -> b
.must(m -> m.match(match -> match.field("name").query("键盘")))
.filter(f -> f.range(r -> r.number(n -> n.field("price").gte(300.0).lte(500.0))))
)
),
Product.class
);
for (Hit<Product> hit : search.hits().hits()) {
System.out.println(hit.source().getName() + " score=" + hit.score());
}Lambda 风格的 builder API 是最大特点——写起来像流式 DSL,编译期就能查出字段名拼错(如果用了带类型信息的映射对象)。比 HLRC 的 SearchRequest 链式 setter 可读性好一个档次。
连接池注意:ElasticsearchClient 线程安全,整个应用一个单例。每个请求新建 client 会耗尽连接。Spring 环境下注册为 Bean。
1.2 HLRC(遗留项目维护)
还在 7.x 老项目里维护的,HLRC 的写法要知道,但新项目别用:
// 7.x HLRC 的典型写法(8.x 已废弃,仅维护遗留代码时参考)
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(HttpHost.create("http://localhost:9200")));
SearchRequest request = new SearchRequest("products");
SearchSourceBuilder source = new SearchSourceBuilder();
source.query(QueryBuilders.matchQuery("name", "键盘"));
request.source(source);
SearchResponse response = client.search(request, RequestOptions.DEFAULT);迁移到新客户端的成本主要是 API 重写,没有自动转换工具。升级 ES 8.x 时把客户端升级一起排期,别让废弃依赖拖到安全漏洞爆出来。
1.3 Spring Boot 集成
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>@Document(indexName = "products")
public class Product {
@Id
private String id;
private String name;
private Double price;
// getter/setter
}
public interface ProductRepository extends ElasticsearchRepository<Product, String> {
List<Product> findByName(String name);
}ElasticsearchRepository 提供开箱即用的 CRUD + 方法名派生查询。但复杂查询还是要写 ElasticsearchOperations 或 NativeSearchQuery:
@Autowired
private ElasticsearchOperations operations;
public List<Product> searchByPrice(double min, double max) {
Query query = NativeQuery.builder()
.withQuery(q -> q.range(r -> r.number(n -> n.field("price").gte(min).lte(max))))
.withPageable(PageRequest.of(0, 20))
.build();
SearchHits<Product> hits = operations.search(query, Product.class);
return hits.stream().map(SearchHit::getContent).collect(Collectors.toList());
}版本匹配铁律:spring-data-elasticsearch 的版本和 ES 服务端版本强绑定。Spring Boot 3.x 默认带的客户端兼容 ES 8.x;ES 服务端升级后客户端不升,各种序列化错误。查 Spring Boot 官网的版本对应表,别拍脑袋。
二、Python:elasticsearch-py 8.x
pip install elasticsearch==8.13.0from elasticsearch import Elasticsearch
# 连接(8.x 默认开启安全时需要认证)
es = Elasticsearch(
"http://localhost:9200",
basic_auth=("elastic", "your_password")
)
# 索引文档
es.index(index="products", id="1", document={
"name": "机械键盘", "price": 429.0, "on_sale": True
})
# 按 ID 查
doc = es.get(index="products", id="1")
print(doc["_source"])
# 搜索
resp = es.search(index="products", query={
"bool": {
"must": [{"match": {"name": "键盘"}}],
"filter": [{"range": {"price": {"gte": 300, "lte": 500}}}]
}
})
for hit in resp["hits"]["hits"]:
print(hit["_source"]["name"], hit["_score"])
# bulk
from elasticsearch.helpers import bulk
actions = [
{"_index": "products", "_id": str(i), "_source": {"name": f"商品{i}", "price": i * 10}}
for i in range(1000)
]
success, failed = bulk(es, actions)
print(f"成功 {success},失败 {len(failed)}")8.x 的变化(从 7.x 迁移必看):
Elasticsearch(...)构造参数变了,http_auth→basic_auth;doc_type参数全面移除(7 尾期已废弃);es.index()的body参数改名document;- helpers(bulk/scan/streaming_bulk)保留,是批量写入的正道。
scan() helper 对应 scroll 全量遍历,写导出脚本用:
from elasticsearch.helpers import scan
for doc in scan(es, index="logs", query={"match_all": {}}, size=1000):
process(doc["_source"])连接管理:Elasticsearch 对象线程安全,全局一个。超时设置 request_timeout=30(默认无超时,慢查询会挂死你的脚本)。
三、Go 客户端
Go 生态两个选择:
| 库 | 状态 |
|---|---|
| olivere/elastic/v7 | 社区老牌,功能全,但停在 ES 7.x |
| elastic/go-elasticsearch(官方) | 8.x 官方维护,只封装 HTTP,查询自己拼 JSON |
官方客户端的哲学是「薄封装」——它只负责 HTTP 连接管理,请求体还是你自己构造:
package main
import (
"bytes"
"encoding/json"
"fmt"
"strings"
"github.com/elastic/go-elasticsearch/v8"
)
func main() {
cfg := elasticsearch.Config{
Addresses: []string{"http://localhost:9200"},
Username: "elastic",
Password: "your_password",
}
es, _ := elasticsearch.NewClient(cfg)
// 索引
doc := `{"name":"机械键盘","price":429}`
es.Index("products", strings.NewReader(doc), es.Index.WithDocumentID("1"))
// 搜索
var buf bytes.Buffer
query := map[string]interface{}{
"query": map[string]interface{}{
"bool": map[string]interface{}{
"must": []map[string]interface{}{{"match": map[string]interface{}{"name": "键盘"}}},
"filter": []map[string]interface{}{{"range": map[string]interface{}{"price": map[string]interface{}{"gte": 300, "lte": 500}}}},
},
},
}
json.NewEncoder(&buf).Encode(query)
res, _ := es.Search(
es.Search.WithIndex("products"),
es.Search.WithBody(&buf),
)
fmt.Println(res.String())
}Go 的选型建议:新项目用官方 go-elasticsearch v8。查询体手写 JSON 是缺点也是优点——DSL 结构完全可控,不被客户端的抽象层限制。olivere/elastic 只适合维护 7.x 遗留项目。
四、跨语言的通用原则
不管什么语言,这几条都适用:
- 客户端版本和服务端版本匹配。客户端向后兼容服务端一个 minor 版本,跨大版本必出问题。升级策略:先升客户端还是先升服务端,查官方 compatibility 表。
- 连接对象全局单例。线程安全,复用连接池。每个请求新建 client 是性能自杀。
- bulk 走 helpers/official API,别自己循环单条 index。
- 错误分类处理:4xx 是请求问题(DSL 写错、mapping 冲突),重试没用;409 版本冲突要重试;429/503 集群限流,退避重试;5xx 集群故障,重试 + 告警。
- 读超时要设。慢查询无限等会把应用线程池打满。超时后降级(返回空/走缓存),别死等。
- 搜索用 filter 缓存的思想写查询:和 curl 里的原则完全一样,客户端的查询构建器只是 DSL 的包装。
五、常见坑汇总
- HLRC 在 ES 8.x 上弃用还继续用:能用但不再修 bug。新项目 Java API Client,遗留项目排期迁移。
- spring-data-elasticsearch 版本和服务端不匹配:序列化报错五花八门。对照版本表升级。
- Python 客户端 8.x 用
body=传参:参数改名document,旧代码直接 400。 - Go 客户端以为有类型安全的 DSL:官方客户端就是 JSON 构造,拼错字段名运行期才知道。用 struct + json tag 组织请求体,或干脆接受动态 JSON。
- 客户端不开认证连 8.x:8.x 默认开 security,不带认证 401。要么
basic_auth,要么服务端关(仅限开发)。 - 每个请求新建 client:连接池耗尽,端口占满。单例!
- bulk 失败不处理:和 curl 一样,逐项检查响应,重试失败的。
下一篇《性能优化、监控与运维排错》进入压轴:怎么让集群又快又稳,以及出事了怎么查。
