Elasticsearch C++ 客户端:elasticlient 完整指南
Elasticsearch 是一个基于 Apache Lucene 构建的强大分布式搜索引擎。有多个库可用于从 C++ 与其交互。在本文中,我们将详细介绍 elasticlient——一个轻量级、现代化且便捷的客户端,它使用 libcurl 库进行 HTTP 请求,并使用 nlohmann/json 处理 JSON。它非常适合将搜索功能嵌入到原生应用程序、服务器组件和数据分析工具中。
elasticlient 的主要功能
- 支持所有 Elasticsearch 基本操作:索引、更新、删除文档。
- 执行包含全文搜索、过滤器和聚合的搜索查询。
- 索引管理:创建、删除、配置映射。
- 批量处理 (bulk) 以实现高性能。
- 支持 SSL/TLS 和基本身份验证。
- 通过回调机制实现异步请求。
库的安装
要构建 elasticlient,需要支持 C++17 的编译器以及已安装的依赖项:libcurl(开发版)和 nlohmann-json。通过包管理器安装 (Ubuntu/Debian):
sudo apt install libcurl4-openssl-dev nlohmann-json3-dev cmake g++从源码构建:
git clone https://github.com/elastic/elasticlient.gitcd elasticlientmkdir build && cd buildcmake .. -DCMAKE_BUILD_TYPE=Releasemake -j4sudo make install基本连接与配置
要开始使用,请创建一个客户端实例,并指定 Elasticsearch 集群的 URL:
#include <elasticlient/client.h>#include <iostream>
int main() { elasticlient::Client client({"http://localhost:9200"}); // 检查连接 auto ping = client.ping(); if (ping.status() == 200) { std::cout << "连接已建立!" << std::endl; } return 0;}对于包含多个节点的集群,请传递 URL 列表:
elasticlient::Client client({ "http://node1:9200", "http://node2:9200", "http://node3:9200"});文档操作
索引新文档(创建或更新):
#include <nlohmann/json.hpp>using json = nlohmann::json;
json doc = { {"title", "Elasticsearch 用于 C++"}, {"content", "使用 elasticlient 客户端的详细指南"}, {"tags", {"cpp", "elasticsearch", "搜索"}}, {"views", 0}};
auto result = client.index("articles", "article", doc.dump(), "1");if (result.status() == 201) { std::cout << "文档已创建: " << result.body() << std::endl;}根据 ID 获取文档:
auto getResult = client.get("articles", "article", "1");if (getResult.status() == 200) { json docJson = json::parse(getResult.body()); std::cout << "标题: " << docJson["_source"]["title"] << std::endl;}更新现有文档(部分更新):
json updateFields = { {"doc", {{"views", 42}}}};auto updateResult = client.update("articles", "article", "1", updateFields.dump());搜索与过滤
使用 Query DSL 执行全文搜索:
json searchQuery = { {"query", { {"bool", { {"must", { {{"match", {{"content", "指南"}}}} }}, {"filter", { {{"term", {{"tags", "cpp"}}}} }} }} }}, {"size", 10}};
auto searchResult = client.search("articles", searchQuery.dump());if (searchResult.status() == 200) { json