文章目录
- Elasticlient API
- 安装elasticlient
- Elasticsearch Client 核心组件整理
- 1. 核心异常类(Exception Class)
- 2. 核心客户端类(Core Client Class)
- 3. 核心枚举(Enums)
- 4. 配置选项结构体(Client Option Structs)
- 5. Client 类核心构造函数
- 6. Client 类核心成员函数
- 补充说明
- CPR Response 类使用手册
- 类概述
- 构造函数
- 核心成员函数
- 响应数据成员(公开属性)
- 使用示例
- 关键特性
- 新手索引模板
- 新手专用索引模板(7.x 适用)
- 核心字段说明(新手必看)
- 使用方法
Elasticlient API
因为这个API的版本较老,很久没更新了,所以用起来某些语法是必须要写的,不能完全照搬7.x的版本,比如_doc。但是其优点是用起来简单,接口少,适合入门和简单的任务操作。
安装elasticlient
sudo apt-get install libmicrohttpd-dev
git clone https://github.com/seznam/elasticlient
cd elasticlient
git submodule update --init --recursive
mkdir build
cd build
cmake ..
make
make install
错误处理
cd ../external/googletest/
mkdir cmake && cd cmake/
cmake -DCMAKE_INSTALL_PREFIX=/usr ..
make && sudo make install
Elasticsearch Client 核心组件整理
1. 核心异常类(Exception Class)
类名 | 父类 | 作用 | 关键参数 / 方法 |
---|
elasticlient::ConnectionException | std::runtime_error | 处理 Elasticsearch 集群连接相关错误(如所有节点均无响应) | - 构造函数:explicit ConnectionException(const std::string &message) - 接收连接错误描述信息,用于抛出时提示具体异常原因 |
2. 核心客户端类(Core Client Class)
类名 | 作用 | 核心成员 | 关键特性 |
---|
elasticlient::Client | 管理 Elasticsearch 集群连接,提供请求执行接口(搜索、增删改查等) | - 隐藏实现:std::unique_ptr<Implementation> impl (封装底层连接逻辑)- 嵌套枚举 / 结构体:HTTPMethod 、ClientOption 等 | 1. 支持多节点集群(通过节点 URL 列表初始化)2. 支持灵活配置(超时、代理、SSL 等)3. 自动重试(请求失败时遍历节点直到成功)4. 异常安全(移动语义支持,避免资源泄漏) |
3. 核心枚举(Enums)
枚举名 | 所属类 | 枚举值 | 作用 |
---|
HTTPMethod | elasticlient::Client | - GET : HTTP GET 方法- POST : HTTP POST 方法- PUT : HTTP PUT 方法- DELETE : HTTP DELETE 方法- HEAD : HTTP HEAD 方法 | 定义 performRequest 接口支持的 HTTP 请求类型,用于指定请求方式 |
4. 配置选项结构体(Client Option Structs)
所有选项均继承自 ClientOption
,用于初始化 Client
时配置连接参数(超时、代理、SSL 等)。
结构体名 | 父类 | 作用 | 关键参数 / 方法 |
---|
Client::ClientOption | - | 配置选项抽象基类 | - 纯虚方法:virtual void accept(Implementation &) const = 0 (子类需实现具体配置逻辑) |
Client::ClientOptionValue<T> | ClientOption | 带值的配置选项模板(封装通用值存储逻辑) | - 成员变量:T value (存储配置值)- 方法:T getValue() const (获取配置值)- 支持移动语义(默认移动构造) |
Client::TimeoutOption | ClientOptionValue<std::int32_t> | 配置客户端请求超时时间(毫秒) | - 构造函数:explicit TimeoutOption(std::int32_t timeoutMs) - 超时单位:毫秒(默认构造 Client 时超时为 6000ms) |
Client::ConnectTimeoutOption | ClientOptionValue<std::int32_t> | 配置客户端连接超时时间(毫秒) | - 构造函数:explicit ConnectTimeoutOption(std::int32_t timeoutMs) - 区别于 TimeoutOption :仅控制 “连接建立” 阶段超时 |
Client::ProxiesOption | ClientOption | 配置客户端 HTTP 代理 | - 隐藏实现:std::unique_ptr<ProxiesOptionImplementation> impl - 构造函数:explicit ProxiesOption(const std::initializer_list<std::pair<const std::string, std::string>> &proxies) (接收 <协议, 代理URL> 列表,如 {"http", "http://127.0.0.1:8080"} ) |
Client::SSLOption | ClientOption | 配置客户端 SSL 连接(证书、验证等) | - 隐藏实现:std::unique_ptr<SSLOptionImplementation> impl - 支持移动语义(SSLOption(SSLOption &&) )- 核心方法:void setSslOption(const SSLOptionType &) (设置具体 SSL 子选项) |
Client::SSLOption::SSLOptionType | - | SSL 子选项抽象基类(SSLOption 的嵌套类) | - 纯虚方法:virtual void accept(SSLOptionImplementation &) const = 0 (子类实现具体 SSL 配置) |
Client::SSLOption::CertFile | SSLOptionType | 配置 SSL 证书文件路径 | - 成员变量:std::string path (证书文件路径)- 构造函数:explicit CertFile(std::string path) |
Client::SSLOption::KeyFile | SSLOptionType | 配置 SSL 证书密钥文件路径及密码 | - 成员变量:std::string path (密钥路径)、std::string password (密钥密码,可选)- 构造函数:explicit KeyFile(std::string path, std::string password = {}) |
Client::SSLOption::CaInfo | SSLOptionType | 配置自定义 CA 证书 bundle 路径 | - 成员变量:std::string path (CA 文件路径)- 构造函数:explicit CaInfo(std::string path) |
Client::SSLOption::VerifyHost | SSLOptionType | 配置是否验证 SSL 主机名 | - 成员变量:bool verify (true 验证,false 跳过)- 构造函数:explicit VerifyHost(bool verify) |
Client::SSLOption::VerifyPeer | SSLOptionType | 配置是否验证 SSL 对等端证书 | - 成员变量:bool verify (true 验证,false 跳过)- 构造函数:explicit VerifyPeer(bool verify) |
5. Client 类核心构造函数
构造函数签名 | 作用 | 关键参数说明 | 适用场景 |
---|
explicit Client(const std::vector<std::string> &hostUrlList, std::int32_t timeout = 6000) | 基础构造:初始化集群节点 + 请求超时 | - hostUrlList :Elasticsearch 节点 URL 列表(每个 URL 需以 / 结尾)- timeout :请求超时(默认 6000ms) | 简单集群连接(无代理、无 SSL) |
explicit Client(const std::vector<std::string> &hostUrlList, std::int32_t timeout, const std::initializer_list<std::pair<const std::string, std::string>>& proxyUrlList) | 带代理构造:基础配置 + 代理 | - proxyUrlList :代理列表(<协议, 代理URL> ) | 需要通过代理连接集群的场景 |
template <typename... Opts> Client(const std::vector<std::string> &hostUrlList, Opts&&... opts) | 可变参数构造:支持多类型配置选项 | - opts :任意 ClientOption 子类实例(如 TimeoutOption 、SSLOption 等)- 特性:后传入的同类型选项覆盖前一个 | 复杂配置场景(需同时设置超时、SSL、代理等) |
Client(Client &&) | 移动构造 | - 转移 impl 所有权,避免资源拷贝 | 客户端对象移动(如函数返回、容器存储) |
6. Client 类核心成员函数
函数签名 | 作用 | 关键参数 | 返回值 | 异常抛出 |
---|
void setClientOption(const ClientOption &opt) | 动态设置客户端配置(构造后补充配置) | - opt :任意 ClientOption 子类实例(如超时、SSL) | 无 | 无(参数非法时可能间接抛出) |
cpr::Response performRequest(HTTPMethod method, const std::string &urlPath, const std::string &body) | 通用请求接口:发送任意 HTTP 请求到集群 | - method :HTTP 方法(HTTPMethod 枚举)- urlPath :URL 路径(节点 URL 后追加部分,如 _search )- body :请求体(JSON 格式字符串) | cpr::Response (包含响应状态、 headers、body) | ConnectionException (所有节点请求失败) |
cpr::Response search(const std::string &indexName, const std::string &docType, const std::string &body, const std::string &routing = std::string()) | 搜索接口:封装 Elasticsearch 搜索请求 | - indexName :索引名(如 my_index )- docType :文档类型(Elasticsearch 7+ 废弃,传空)- body :搜索条件(JSON,如 {"query":{"match_all":{}}} )- routing :路由键(可选,用于分片路由) | cpr::Response (搜索结果) | ConnectionException (所有节点失败) |
cpr::Response get(const std::string &indexName, const std::string &docType, const std::string &id = std::string(), const std::string &routing = std::string()) | 读取接口:获取指定 ID 的文档 | - id :文档 ID(必传,空则报错)- 其他参数同 search | cpr::Response (文档内容) | ConnectionException |
cpr::Response index(const std::string &indexName, const std::string &docType, const std::string &id, const std::string &body, const std::string &routing = std::string()) | 写入接口:索引(新增 / 更新)文档 | - id :文档 ID(空则由 ES 自动生成)- body :文档内容(JSON)- 其他参数同 search | cpr::Response (索引结果,含 ID、版本) | ConnectionException |
cpr::Response remove(const std::string &indexName, const std::string &docType, const std::string &id, const std::string &routing = std::string()) | 删除接口:删除指定 ID 的文档 | - id :文档 ID(必传)- 其他参数同 search | cpr::Response (删除结果,含是否成功、版本) | ConnectionException |
补充说明
- 隐藏实现(Pimpl 模式):
Client
及 ProxiesOption
/SSLOption
使用 std::unique_ptr<Implementation>
封装底层逻辑,降低接口耦合,便于版本迭代。 - 模板与泛型:
ClientOptionValue<T>
、可变参数构造函数等使用模板,支持灵活扩展配置类型(无需修改原有代码即可新增选项)。 - 依赖项:依赖
cpr
库(HTTP 客户端),cpr::Response
为第三方类型,包含响应状态码(status_code
)、响应体(text
)等字段。
CPR Response 类使用手册
类概述
类别 | 说明 |
---|
类名 | cpr::Response |
功能 | 封装 HTTP 请求的响应数据 |
命名空间 | cpr |
头文件 | #include "cpr/response.h" |
构造函数
函数签名 | 参数说明 | 作用描述 |
---|
Response() | 无参数 | 创建空的响应对象 |
Response(std::shared_ptr<CurlHolder> curl, std::string&& p_text, std::string&& p_header_string, Cookies&& p_cookies, Error&& p_error) | curl : CURL 句柄 p_text : 响应正文 p_header_string : 原始响应头 p_cookies : Cookies 数据 p_error : 错误信息 | 使用已有数据构造响应对象 |
核心成员函数
函数名 | 参数 | 返回值 | 作用描述 |
---|
GetCertInfo() | 无 | std::vector<std::string> | 获取 SSL 证书信息 |
operator=(Response&&) | old : 右值引用 | Response& | 移动赋值运算符 |
operator=(const Response&) | other : 常量引用 | Response& | 拷贝赋值运算符 |
响应数据成员(公开属性)
成员变量 | 类型 | 说明 |
---|
status_code | long | HTTP 状态码 (如 200, 404, 500) |
text | std::string | 响应正文内容 |
header | Header | 解析后的响应头 (键值对形式) |
url | Url | 最终请求的 URL (考虑重定向) |
elapsed | double | 请求耗时 (秒) |
cookies | Cookies | 服务器返回的 Cookies |
error | Error | 错误信息 (请求失败时使用) |
raw_header | std::string | 原始响应头字符串 |
status_line | std::string | HTTP 状态行 |
reason | std::string | 状态码原因短语 |
uploaded_bytes | cpr_off_t | 上传字节数 |
downloaded_bytes | cpr_off_t | 下载字节数 |
redirect_count | long | 重定向次数 |
使用示例
#include "cpr/cpr.h"int main() {cpr::Response r = cpr::Get(cpr::Url{"https://httpbin.org/get"});if (r.status_code == 200) {std::cout << "Status: " << r.status_code << std::endl;std::cout << "Body: " << r.text << std::endl;std::cout << "Content-Type: " << r.header["Content-Type"] << std::endl;std::cout << "Elapsed time: " << r.elapsed << "s" << std::endl;} else {std::cout << "Request failed: " << r.error.message << std::endl;}return 0;
}
关键特性
- 自动资源管理: 使用智能指针管理 CURL 资源
- 移动语义支持: 支持移动构造和移动赋值,提高性能
- 完整响应信息: 提供 HTTP 响应的所有关键信息
- 错误处理: 通过
error
成员提供详细的错误信息 - SSL 支持: 可通过
GetCertInfo()
获取证书信息
新手索引模板
新手专用索引模板(7.x 适用)
# 创建一个名为 "basic_template" 的索引模板
PUT _template/basic_template
{# 1. 匹配的索引名称模式(必填)"index_patterns": ["my-index-*"], # 2. 模板优先级(可选,默认0)"order": 1, # 3. 索引的核心配置(必填,模板的核心内容)"settings": { # 主分片数量(非常重要)"number_of_shards": 1, # 副本分片数量(影响可用性和查询性能)"number_of_replicas": 0, # 刷新频率(可选,影响实时性和性能)"refresh_interval": "5s" "analysis" : { "analyzer" : { "ik" : { "tokenizer" : "ik_max_word" } } } },# 4. 字段映射(定义数据结构,非常重要)"mappings": { # 动态映射开关(控制是否自动创建未定义的字段)"dynamic": "false", # 预定义字段(核心!必须根据自己的数据结构定义)"properties": {# 示例1:时间字段(日志/事件类数据必选)"create_time": {"type": "date", "format": "yyyy-MM-dd HH:mm:ss||yyyy-MM-dd||epoch_millis" },# 示例2:文本字段(需要分词查询的内容,如标题、描述)"title": {"type": "text", "analyzer": "ik_max_word" },# 示例3:关键字字段(精确匹配/聚合,如状态、ID)"status": {"type": "keyword" },# 示例4:数字字段(整数/小数)"count": {"type": "integer" },# 示例5:布尔字段(true/false)"is_active": {"type": "boolean" }}},# 5. 索引别名(可选,方便查询)"aliases": {"my-index-all": {} }
}
核心字段说明(新手必看)
-
index_patterns
- 决定模板作用于哪些索引(如
my-index-*
匹配 my-index-1
、my-index-2023
等)。 - 格式固定为数组,支持通配符
*
。
-
settings
number_of_shards
:创建后不能改,新手单节点环境填 1 即可,多节点可根据数据量增加(如 3)。number_of_replicas
:单节点必须设为 0(否则分片无法分配),多节点建议 1(保证可用性)。
-
mappings
dynamic: false
:避免 Elasticsearch 自动推断字段类型(比如把数字当文本)。properties
:必须根据自己的实际数据定义字段!比如你的数据有 name
、age
,就必须在这里声明它们的类型(text
/keyword
/integer
等)。
-
字段类型选择指南
数据类型 | 对应 Elasticsearch 类型 | 用途示例 | 必要性 |
---|
时间 | date | 创建时间、日志时间 | 有时间数据则必须 |
可分词的文本 | text | 标题、描述、内容 | 需模糊查询则必须 |
不可分词的文本 | keyword | 状态(success/error)、ID | 需精确匹配则必须 |
整数 | integer /long | 数量、年龄 | 数字必须,否则无法计算 |
小数 | float /double | 价格、分数 | 同上 |
布尔值 | boolean | 是否启用、是否删除 | 布尔值必须 |
使用方法
- 把上述模板中的
my-index-*
改成你需要的索引前缀(如 user-*
、log-*
)。 - 在
properties
里删掉示例字段,换成你自己的数据字段(比如你的数据有 username
、age
、register_time
,就定义这三个字段)。 - 通过 Kibana Dev Tools 或 Postman 执行上述请求,创建模板。
- 之后创建匹配前缀的索引(如
my-index-1
)时,会自动应用模板配置。