Elasticsearch C++ 客户端:高性能搜索的强大工具
Elasticsearch 是一个基于 Apache Lucene 的分布式搜索引擎,广泛用于全文搜索、日志分析和大数据处理。虽然官方没有提供 C++ 客户端,但开发者可以通过 elasticlient 库(一个专为与 Elasticsearch 配合使用而创建的轻量级 C++ 客户端)利用 REST API 有效地与 Elasticsearch 进行交互。
elasticlient 库为所有基本操作提供了便捷的接口:文档索引、搜索、更新、删除和集群管理。它构建在用于 HTTP 请求的 libcurl 库和用于处理 JSON 的 nlohmann/json 库之上,确保了高性能以及与 C++17/20 现代标准的兼容性。
elasticlient 的主要功能
- 完全支持 Elasticsearch REST API(6.x、7.x 和 8.x 版本)
- 异步和同步请求
- 通过 nlohmann/json 自动进行 JSON 序列化/反序列化
- 支持用于批量数据加载的 bulk 操作
- 索引管理(创建、删除、映射配置)
- 处理搜索查询(match、term、range、bool 等)
- 错误处理和连接重试
安装与配置
要安装 elasticlient,可以使用 CMake 和 vcpkg,或者手动编译。推荐通过 vcpkg 的方式:
# 通过 vcpkg 安装vcpkg install elasticlient
# 在 CMakeLists.txt 中连接find_package(elasticlient REQUIRED)target_link_libraries(my_app PRIVATE elasticlient::elasticlient)还需要以下依赖项:
- libcurl(支持 HTTPS)
- nlohmann/json(3.9+ 版本)
- 支持 C++17 的 C++ 编译器(GCC 8+、Clang 7+、MSVC 2019+)
基本使用示例
连接到 Elasticsearch
#include <elasticlient/client.h>
int main() { // 创建客户端并连接到本地实例 elasticlient::Client client("http://localhost:9200"); // 检查连接 auto status = client.get("/"); if (status.statusCode() == 200) { std::cout << "已连接到 Elasticsearch!" << std::endl; } return 0;}索引文档
#include <elasticlient/client.h>#include <nlohmann/json.hpp>
using json = nlohmann::json;
int main() { elasticlient::Client client("http://localhost:9200"); // 创建文档 json document = { {"title", "C++ 入门"}, {"author", "伊万·彼得罗夫"}, {"year", 2023}, {"tags", {"编程", "C++", "教程"}} }; // 将文档索引到 "books" 索引,ID 为 "1" auto response = client.index("books", "_doc", "1", document.dump()); if (response.statusCode() == 201) { std::cout << "文档索引成功!" << std::endl; } return 0;}搜索文档
#include <elasticlient/client.h>#include <iostream>
int main() { elasticlient::Client client("http://localhost:9200"); // 搜索查询 json query = { {"query", { {"match", { {"title", "C++"} }} }} }; auto response = client.search("books", "_search", query.dump()); if (response.statusCode() == 200) { auto results = json::parse(response.body()); for (const auto& hit : results["hits"]["hits"]) { std::cout << "找到:" << hit["_source"]["title"] << std::endl; } } retu