ES 介紹與安裝
Elasticsearch, 簡稱 ES,它是個開源分布式搜索引擎,它的特點有:分布式,零配置,自動發現,索引自動分片,索引副本機制,restful 風格接口,多數據源,自動搜索負載等。它可以近乎實時的存儲、檢索數據;本身擴展性很好,可以擴展到上百臺服務器,處理 PB 級別的數據。es 也使用 Java 開發并使用 Lucene 作為其核心來實現所有索引和搜索的功能,但是它的目的是通過簡單的 RESTful API 來隱藏 Lucene 的復雜性,從而讓全文搜索變得簡單。
Elasticsearch 是面向文檔(document oriented)的,這意味著它可以存儲整個對象或文檔(document)。然而它不僅僅是存儲,還會索引(index)每個文檔的內容使之可以被搜索。在 Elasticsearch 中,你可以對文檔(而非成行成列的數據)進行索引、搜索、排序、過濾。
ES 安裝
# 添加倉庫秘鑰
wget -qO - https://artifacts.elastic.co/GPG-KEY-elasticsearch | sudo apt-key add -
# 上邊的添加方式會導致一個 apt-key 的警告,如果不想報警告使用下邊這個
curl -s https://artifacts.elastic.co/GPG-KEY-elasticsearch | sudo gpg --no-default-keyring --keyring gnupg-ring:/etc/apt/trusted.gpg.d/icsearch.gpg --import
# 添加鏡像源倉庫
echo "deb https://artifacts.elastic.co/packages/7.x/apt stable main" | sudo tee /etc/apt/sources.list.d/elasticsearch.list
# 更新軟件包列表
sudo apt update
# 安裝 es
sudo apt-get install elasticsearch=7.17.21
# 啟動 es
sudo systemctl start elasticsearch
# 安裝 ik 分詞器插件
sudo /usr/share/elasticsearch/bin/elasticsearch-plugin install https://get.infini.cloud/elasticsearch/analysis-ik/7.17.21
若 apt update 更新源報錯:
安裝 kibana
使用 apt 命令安裝 Kibana。
sudo apt install kibana
sudo apt install kibana配置 Kibana(可選):
根據需要配置 Kibana。配置文件通常位于 /etc/kibana/kibana.yml。可能需要
設置如服務器地址、端口、Elasticsearch URL 等。
sudo vim /etc/kibana/kibana.yml
例如,你可能需要設置 Elasticsearch 服務的 URL: 大概 32 行左右
elasticsearch.host: “http://localhost:9200”
啟動 Kibana 服務:
安裝完成后,啟動 Kibana 服務。
sudo systemctl start kibana
設置開機自啟(可選):
如果你希望 Kibana 在系統啟動時自動啟動,可以使用以下命令來啟用自啟動。
sudo systemctl enable kibana
驗證安裝:
使用以下命令檢查 Kibana 服務的狀態。
sudo systemctl status kibana
訪問 Kibana:
在瀏覽器中訪問 Kibana,通常是 http://:5601
ES 客戶端的安裝
代碼:https://github.com/seznam/elasticlient
官網:https://seznam.github.io/elasticlient/index.html
ES C++的客戶端選擇并不多, 我們這里使用 elasticlient 庫, 下面進行安裝。
# 克隆代碼
git clone https://github.com/seznam/elasticlient
# 切換目錄
cd elasticlient
# 更新子模塊
git submodule update --init --recursive
# 編譯代碼
mkdir build
cd build
cmake ..
make
# 安裝
make install
cmake 生成 makefile 的過程會遇到一個問題
解決:需要安裝 MicroHTTPD 庫
sudo apt-get install libmicrohttpd-dev
make 的時候編譯出錯:這是子模塊 googletest 沒有編譯安裝
collect2: error: ld returned 1 exit status
make[2]: *** [external/httpmockserver/test/CMakeFiles/testserver.dir/build.make:105: bin/test-server] Error 1
make[1]: *** [CMakeFiles/Makefile2:675:
external/httpmockserver/test/CMakeFiles/test-server.dir/all] Error
2
make: *** [Makefile:146: all] Error 2
解決:手動安裝子模塊
cd ../external/googletest/
mkdir cmake && cd cmake/
cmake -DCMAKE_INSTALL_PREFIX=/usr ..
make && sudo make install
安裝好重新 cmake 即可。
ES 核心概念
索引(Index)
一個索引就是一個擁有幾分相似特征的文檔的集合。比如說,你可以有一個客戶數據的索引,一個產品目錄的索引,還有一個訂單數據的索引。一個索引由一個名字來標識(必須全部是小寫字母的),并且當我們要對應于這個索引中的文檔進行索引、搜索、更新和刪除的時候,都要使用到這個名字。在一個集群中,可以定義任意多的索引。
字段(Field)
字段相當于是數據表的字段,對文檔數據根據不同屬性進行的分類標識。
名稱 | 數值 | 備注 |
---|---|---|
enabled | true(默認) | false | 是否僅作存儲,不做搜索和分析 |
index | true(默認) | false | 是否構建倒排索引(決定了是否分詞,是否被索引 |
index_option | ||
dynamic | true(缺省)| false | 控制 mapping 的自動更新 |
doc_value | true(默認) | false | 是否開啟 doc_value,用戶聚合和排序分析,分詞字段不能使用 |
fielddata | fielddata": {“format”:“disabled”} | 是否為 text 類型啟動 fielddata,實現排序和聚合分析針對分詞字段,參與排序或聚合時能提高性能,不分詞字段統一建議使用 doc_value |
store | true | false(默認) | 是否單獨設置此字段的是否存儲而從_source 字段中分離,只能搜索,不能獲取值 |
coerce | true(默認) | false | 是否開啟自動數據類型轉換功能,比如:字符串轉數字,浮點轉整型 |
analyzer | “analyzer”: “ik” | 指定分詞器,默認分詞器為 standard analyzer |
boost | “boost”: 1.23 | 字段級別的分數加權,默認值是 1.0 |
fields | “fields”: {“raw”: {“type”:“text”,“index”:“not_analyzed”}} | 對一個字段提供多種索引模式,同一個字段的值,一個分詞,一個不分詞 |
data_detection | true(默認) | false | 是否自動識別日期類型 |
文檔 (document)
一個文檔是一個可被索引的基礎信息單元。比如,你可以擁有某一個客戶的文檔,某一個產品的一個文檔或者某個訂單的一個文檔。文檔以 JSON(Javascript Object Notation)格式來表示,而 JSON 是一個到處存在的互聯網數據交互格式。在一個index/type 里面,你可以存儲任意多的文檔。一個文檔必須被索引或者賦予一個索引的 type。
Elasticsearch與傳統關系型數據庫相比如下:
DB | Database | Table | Row | Column |
---|---|---|---|---|
ES | Index | Type | Document | Field |
Kibana 訪問 es 進行測試
通過網頁訪問 kibana:
創建索引庫
POST /user/_doc
{"settings": {"analysis": {"analyzer": {"ik": {"tokenizer": "ik_max_word"}}}},"mappings": {"dynamic": true,"properties": {"nickname": {"type": "text","analyzer": "ik_max_word"},"user_id": {"type": "keyword","analyzer": "standard"},"phone": {"type": "keyword","analyzer": "standard"},"description": {"type": "text","enabled": false},"avatar_id": {"type": "keyword","enabled": false}}}
}
新增數據:
POST /user/_doc/_bulk
{"index":{"_id":"1"}}
{"user_id" : "USER4b862aaa-2df8654a-7eb4bb65-e3507f66","nickname" : "昵稱 1","phone" : "手機號 1","description" : "簽名 1","avatar_id" : "頭像 1"}
{"index":{"_id":"2"}}
{"user_id" : "USER14eeeaa5-442771b9-0262e455-e4663d1d","nickname" : "昵稱 2","phone" : "手機號 2","description" : "簽名 2","avatar_id" : "頭像 2"}
{"index":{"_id":"3"}}
{"user_id" : "USER484a6734-03a124f0-996c169d-d05c1869","nickname" : "昵稱 3","phone" : "手機號 3","description" : "簽名 3","avatar_id" : "頭像 3"}
{"index":{"_id":"4"}}
{"user_id" : "USER186ade83-4460d4a6-8c08068f-83127b5d","nickname" : "昵稱 4","phone" : "手機號 4","description" : "簽名 4","avatar_id" : "頭像 4"}
{"index":{"_id":"5"}}
{"user_id" : "USER6f19d074-c33891cf-23bf5a83-57189a19","nickname" : "昵稱 5","phone" : "手機號 5","description" : "簽名 5","avatar_id" : "頭像 5"}
{"index":{"_id":"6"}}
{"user_id" : "USER97605c64-9833ebb7-d0455353-35a59195","nickname" : "昵稱 6","phone" : "手機號 6","description" : "簽名 6","avatar_id" : "頭像 6"}
查看并搜索數據
GET /user/_doc/_search?pretty
{"query": {"bool": {"must_not": [{"terms": {"user_id.keyword": ["USER4b862aaa-2df8654a-7eb4bb65-e3507f66","USER14eeeaa5-442771b9-0262e455-e4663d1d","USER484a6734-03a124f0-996c169d-d05c1869"]}}],"should": [{"match": {"user_id": "昵稱"}},{"match": {"nickname": "昵稱"}},{"match": {"phone": "昵稱"}}]}}
}
刪除索引:
DELETE /user
檢索全部數據:
GET /user/_search
{"query": {"match_all": {}}
}
ES 客戶端接口介紹
// 創建客戶端對象
explicit Client(const std::vector < std::string >> &hostUrlList,std::int32_t timeout = 6000);// 應用于索引創建,以及新增數據
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());// 檢索數據
cpr::Response search(const std::string &indexName,const std::string &docType,const std::string &body,const std::string &routing = std::string());// 刪除數據
cpr::Response remove(const std::string &indexName,const std::string &docType,const std::string &id,const std::string &routing = std::string());
使用案例,數據為上面的數據:
#include <elasticlient/client.h>
#include <cpr/cpr.h>
#include <iostream>int main()
{// 構造ES客戶端elasticlient::Client client({"http://127.0.0.1:9200/"});// 發起搜索請求try{auto rsp = client.search("user", "_doc", "{\"query\":{\"match_all\":{} }}");std::cout << rsp.status_code << std::endl;std::cout << rsp.text << std::endl;}catch (std::exception &e){std::cout << "請求失敗: " << e.what() << std::endl;return -1;}return 0;
}
測試結果:
二次封裝
使用jsoncpp庫實現數據的序列化和反序列化
Json::Value:用于進行中間數據存儲
將多個字段數據進行序列化,需要先將數據存儲到Value對象中
若要對一個json格式字符串進行解析,解析結果也是存放在Value中
常用接口:
#include <json/json.h>Value &operator=(Value &other);
Value &operator[](const char *key); // Value["name"] = "張三";
Value &append(const Value &value); // 數組數據的新增,Value["score"].append(100);
std::string asString() const; // Value["name"].asString();
ArrayIndex size() const; // 獲取數組元素的個數
Value &operator[](ArrayIndex index); // 通過下標獲取數組元素,Value["socre"][0].asFloat();// Write類
class Json_API StreamWriter
{virtual write(Value const &root, JSONCPP_OSTREAM *sout) = 0; // 序列化接口
};
class Json_API StreamWriterBuilder
{StreamWriter *newStreamWriter(); // StreamWriter 對象生產接口
};// Reader類
class JSON_API CharReader
{virtual bool parse(char const *beginDoc, char const *endDoc, Value *root, JSONCPP_STRING *errs) = 0;
};class JSON_API CharReaderBuilder
{CharReader *newCharReader(); // 創建CharReader對象接口
};
Jsoncpp使用案例:
#include <json/json.h>
#include <iostream>
#include <string>
#include <sstream>
#include <memory>bool serialize(const Json::Value &root, std::string &str)
{Json::StreamWriterBuilder swb;std::unique_ptr<Json::StreamWriter> sw(swb.newStreamWriter());std::stringstream ss;int ret = sw->write(root, &ss);if (ret < 0){std::cout << "json serialize failed" << std::endl;return false;}str = ss.str();return true;
}bool deserialize(const std::string &body, Json::Value &val)
{Json::CharReaderBuilder crb;std::unique_ptr<Json::CharReader> cr(crb.newCharReader());std::string err;bool ret = cr->parse(body.c_str(), body.c_str() + body.size(), &val, &err);if (ret == false){std::cout << "json deserialize failed " << err << std::endl;return false;}return true;
}int main()
{std::string name = "小明";int age = 18;float score[3] = {91, 99, 100};Json::Value stu;stu["name"] = name;stu["age"] = age;stu["score"].append(score[0]);stu["score"].append(score[1]);stu["score"].append(score[2]);std::string json_str;bool ret = serialize(stu, json_str);if (ret == false){std::cout << "json serialize failed" << std::endl;return -1;}std::cout << json_str << std::endl;Json::Value root;ret = deserialize(json_str, root);if (ret == false){std::cout << "json deserialize failed" << std::endl;return -1;}std::cout << "姓名:" << root["name"].asString() << std::endl;std::cout << "年齡:" << root["age"].asInt() << std::endl;std::cout << "成績分別是: ";int sz = root["score"].size();for (int i = 0; i < sz; i++){std::cout << root["score"][i].asFloat() << " ";}std::cout << std::endl;return 0;
}
ES客戶端API二次封裝
封裝四個操作:索引創建,數據新增,數據查詢,數據刪除
封裝最主要完成的是請求正文的構造過程,Json::Value對象數據新增過程
索引創建:
1.能夠動態設定索引名稱,索引類型
2.能夠動態的添加字段,并設置字段類型,設置分詞器類型,是否構造索引
構造思想:根據固定的Json格式構造Value對象即可
數據新增:
1.提供用戶一個新增字段及數據的接口即可
2.提供一個發起請求的接口
封裝代碼實現:
#pragma once
#include <json/json.h>
#include <elasticlient/client.h>
#include <cpr/cpr.h>
#include <iostream>
#include <string>
#include <sstream>
#include <memory>
#include "logger.hpp"namespace hdp
{bool serialize(const Json::Value &root, std::string &str){Json::StreamWriterBuilder swb;std::unique_ptr<Json::StreamWriter> sw(swb.newStreamWriter());std::stringstream ss;int ret = sw->write(root, &ss);if (ret < 0){LOG_ERROR("json serialize failed");return false;}str = ss.str();return true;}bool deserialize(const std::string &body, Json::Value &val){Json::CharReaderBuilder crb;std::unique_ptr<Json::CharReader> cr(crb.newCharReader());std::string err;bool ret = cr->parse(body.c_str(), body.c_str() + body.size(), &val, &err);if (ret == false){LOG_ERROR("json deserialize failed: {} ", err);return false;}return true;}class ESIndex{public:ESIndex(const std::shared_ptr<elasticlient::Client> &client,const std::string &name,const std::string &type = "_doc"): _name(name), _type(type), _client(client){Json::Value analysis;Json::Value analyzer;Json::Value ik;Json::Value tokenizer;tokenizer["tokenizer"] = "ik_max_word";ik["ik"] = tokenizer;analyzer["analyzer"] = ik;analysis["analysis"] = analyzer;_index["settings"] = analysis;}ESIndex &append(const std::string &key, const std::string &type = "text",const std::string &analyzer = "ik_max_word",bool enabled = true){Json::Value field;field["type"] = type;field["analyzer"] = analyzer;if (enabled == false)field["enabled"] = enabled;_properties[key] = field;return *this;}bool create(const std::string &index_id = "default_index_id"){Json::Value mappings;mappings["dynamic"] = true;mappings["properties"] = _properties;_index["mappings"] = mappings;std::string body;bool ret = serialize(_index, body);if (ret == false){LOG_ERROR("索引序列化失敗");return false;}try{cpr::Response rsp = _client->index(_name, _type, index_id, body);if (rsp.status_code < 200 || rsp.status_code >= 300){LOG_ERROR("創建ES索引 {} 失敗,響應狀態碼異常: {}", _name, rsp.status_code);return false;}}catch (std::exception &e){LOG_ERROR("創建ES索引 {} 失敗: {}", _name, e.what());return false;}return true;}private:std::string _name;std::string _type;Json::Value _index;Json::Value _properties;std::shared_ptr<elasticlient::Client> _client;};class ESInsert{public:ESInsert(const std::shared_ptr<elasticlient::Client> client,const std::string &name,const std::string &type = "_doc"): _name(name),_type(type), _client(client) {}template <class T>ESInsert &append(const std::string &key, const T &val){_item[key] = val;return *this;}bool insert(const std::string &id = ""){std::string body;bool ret = serialize(_item, body);if (ret == false){LOG_ERROR("索引序列化失敗");return false;}try{cpr::Response rsp = _client->index(_name, _type, id, body);if (rsp.status_code < 200 || rsp.status_code >= 300){LOG_ERROR("新增數據 {} 失敗,響應狀態碼為: {}", body, rsp.status_code);return false;}}catch (std::exception &e){LOG_ERROR("新增數據 {} 失敗: {}", body, e.what());return false;}return true;}private:std::string _name;std::string _type;Json::Value _item;std::shared_ptr<elasticlient::Client> _client;};class ESRemove{public:ESRemove(const std::shared_ptr<elasticlient::Client> &client,const std::string &name, const std::string &type = "_doc"): _name(name), _type(type), _client(client) {}bool remove(const std::string &id){try{cpr::Response rsp = _client->remove(_name, _type, id);if (rsp.status_code < 200 || rsp.status_code >= 300){LOG_ERROR("刪除數據{}失敗:響應狀態碼異常: {}", rsp.status_code);return false;}}catch (std::exception &e){LOG_ERROR("刪除數據 {} 異常: {}", id, e.what());return false;}return true;}private:std::string _name;std::string _type;std::shared_ptr<elasticlient::Client> _client;};class ESSearch{public:ESSearch(const std::shared_ptr<elasticlient::Client> &client,const std::string &name, const std::string &type = "_doc"): _name(name), _type(type), _client(client) {}ESSearch &append_must_not_terms(const std::string &key, const std::vector<std::string> &vals){Json::Value fields;for (const auto& val : vals){fields[key].append(val);}Json::Value terms;terms["terms"] = fields;_must_not.append(terms);return *this;}ESSearch &append_should_match(const std::string &key, const std::string &val){Json::Value field;field[key] = val;Json::Value match;match["match"] = field;_should.append(match);return *this;}ESSearch &append_must_term(const std::string &key, const std::string &val){Json::Value field;field[key] = val;Json::Value term;term["term"] = field;_must.append(term);return *this;}ESSearch &append_must_match(const std::string &key, const std::string &val){Json::Value field;field[key] = val;Json::Value match;match["match"] = field;_must.append(match);return *this;}Json::Value search(){Json::Value cond;if(_must_not.empty() == false)cond["must_not"] = _must_not;if(_should.empty() == false)cond["should"] = _should;if(_must.empty() == false)cond["must"] = _must;Json::Value query;query["bool"] = cond;Json::Value root;root["query"] = query;std::string body;bool ret = serialize(root, body);if (ret == false){LOG_ERROR("索引序列化失敗");return Json::Value();}cpr::Response rsp;try{rsp = _client->search(_name, _type, body);if (rsp.status_code < 200 || rsp.status_code >= 300){LOG_ERROR("檢索數據 {} 失敗,響應狀態碼異常: {}", body, rsp.status_code);return Json::Value();}}catch (std::exception &e){LOG_ERROR("檢索數據 {} 失敗: {}", body, e.what());return Json::Value();}// 需要對響應正文進行反序列化Json::Value json_res;ret = deserialize(rsp.text, json_res);if (ret == false){LOG_ERROR("檢索數據 {} 結果反序列化失敗", rsp.text);return Json::Value();}serialize(json_res, body);LOG_DEBUG("檢索響應正文: [{}]", body);return json_res["hits"]["hits"];}private:std::string _name;std::string _type;Json::Value _must_not;Json::Value _should;Json::Value _must;std::shared_ptr<elasticlient::Client> _client;};
}
二次封裝測試代碼:
#include "../../../common/icsearch.hpp"
#include <gflags/gflags.h>DEFINE_int32(run_mode, 0, "程序的運行模式,0-調試,1-發布");
DEFINE_string(log_file, "", "發布模式下,用于指定日志的輸出文件");
DEFINE_int32(log_level, 0, "發布模式下,用于指定日志的輸出等級");int main(int argc, char *argv[])
{google::ParseCommandLineFlags(&argc, &argv, true);hdp::init_logger(FLAGS_run_mode, FLAGS_log_file, FLAGS_log_level);std::vector<std::string> host_list = {"http://127.0.0.1:9200/"};std::shared_ptr<elasticlient::Client> client = std::make_shared<elasticlient::Client>(host_list);// 創建索引bool ret = hdp::ESIndex(client, "test_user").append("nickname").append("phone", "keyword", "standard", true).create();if (ret == false){LOG_ERROR("創建索引失敗");return -1;}else{LOG_DEBUG("創建索引成功");}// 新增數據ret = hdp::ESInsert(client, "test_user").append("nickname", "張三").append("phone", "123456").insert("0001");if (ret == false){LOG_ERROR("新增數據失敗");return -1;}else{LOG_DEBUG("新增數據成功");}ret = hdp::ESInsert(client, "test_user").append("nickname", "李四").append("phone", "112233").insert("0002");if (ret == false){LOG_ERROR("新增數據失敗");return -1;}else{LOG_DEBUG("新增數據成功");}std::this_thread::sleep_for(std::chrono::seconds(1));// 檢索數據Json::Value user = hdp::ESSearch(client, "test_user").append_should_match("nickname", "李四").search();if (user.empty() || user.isArray() == false){LOG_ERROR("檢索結果為空,或者結果不是數組類型");return -1;}else{LOG_DEBUG("數據檢索成功");}int size = user.size();for (int i = 0; i < size; ++i){LOG_INFO("nickname: {}", user[i]["_source"]["nickname"].asString());LOG_INFO("phone: {}", user[i]["_source"]["phone"].asString());}// 更新數據ret = hdp::ESInsert(client, "test_user").append("nickname", "李四").append("phone", "123456789").insert("0002");if (ret == false){LOG_ERROR("更新數據失敗");return -1;}else{LOG_DEBUG("更新數據成功");}std::this_thread::sleep_for(std::chrono::seconds(1));user = hdp::ESSearch(client, "test_user").append_should_match("phone.keyword", "123456789").search();if (user.empty() || user.isArray() == false){LOG_ERROR("檢索結果為空,或者結果不是數組類型");return -1;}else{LOG_DEBUG("數據檢索成功");}size = user.size();for (int i = 0; i < size; ++i){LOG_INFO("nickname: {}", user[i]["_source"]["nickname"].asString());LOG_INFO("phone: {}", user[i]["_source"]["phone"].asString());}// 刪除數據ret = hdp::ESRemove(client, "test_user").remove("0002");if (ret == false){LOG_ERROR("刪除數據失敗");return -1;}else{LOG_DEBUG("刪除數據成功");}std::this_thread::sleep_for(std::chrono::seconds(1));user = hdp::ESSearch(client, "test_user").append_should_match("phone.keyword", "123456789").search();if (user.empty() || user.isArray() == false){LOG_ERROR("檢索結果為空,或者結果不是數組類型");return -1;}else{LOG_DEBUG("數據檢索成功");}size = user.size();for (int i = 0; i < size; ++i){LOG_INFO("nickname: {}", user[i]["_source"]["nickname"].asString());LOG_INFO("phone: {}", user[i]["_source"]["phone"].asString());}return 0;
}
測試結果:
ES客戶端API使用注意事項:
1.地址后面不要忘了相對根目錄: http://127.0.0.1:9200/
tring());
}
// 刪除數據
ret = hdp::ESRemove(client, "test_user").remove("0002");
if (ret == false)
{LOG_ERROR("刪除數據失敗");return -1;
}
else
{LOG_DEBUG("刪除數據成功");
}std::this_thread::sleep_for(std::chrono::seconds(1));
user = hdp::ESSearch(client, "test_user").append_should_match("phone.keyword", "123456789").search();
if (user.empty() || user.isArray() == false)
{LOG_ERROR("檢索結果為空,或者結果不是數組類型");return -1;
}
else
{LOG_DEBUG("數據檢索成功");
}
size = user.size();
for (int i = 0; i < size; ++i)
{LOG_INFO("nickname: {}", user[i]["_source"]["nickname"].asString());LOG_INFO("phone: {}", user[i]["_source"]["phone"].asString());
}
return 0;
}
測試結果:[外鏈圖片轉存中...(img-v3LOnflV-1753877627079)]ES客戶端API使用注意事項:1.地址后面不要忘了相對根目錄: http://127.0.0.1:9200/2.ES客戶端API使用,要進行異常捕捉,否則操作失敗會導致程序異常退出