ADD file via upload

main
pr4ku3p2c 7 months ago
parent 01557ca5ec
commit 35ebaa52b6

@ -0,0 +1,75 @@
#include "search_engine.h"
#include <httplib.h>
#include <nlohmann/json.hpp>
#include <filesystem>
#include "file_monitor.h"
using json = nlohmann::json;
int main() {
SearchEngine engine("./search_db");
// 启动文件监控
FileMonitor monitor("./docs", [&](const std::string& path, const std::string& content) {
engine.addDocument(path, content);
engine.commit();
});
monitor.start();
httplib::Server svr;
// 更新搜索接口
svr.Get("/search", [&](const httplib::Request& req, httplib::Response& res) {
auto query = req.get_param_value("q");
auto limit_str = req.get_param_value("limit", "10");
auto offset_str = req.get_param_value("offset", "0");
auto sort_field = req.get_param_value("sort", "relevance");
auto sort_order = req.get_param_value("order", "desc");
auto file_type = req.get_param_value("type", "");
SearchOptions options;
options.limit = std::stoul(limit_str);
options.offset = std::stoul(offset_str);
options.file_type = file_type;
// 设置排序选项
if (sort_field == "path")
options.sort_field = SortField::PATH;
else if (sort_field == "size")
options.sort_field = SortField::SIZE;
else if (sort_field == "modified")
options.sort_field = SortField::MODIFIED_TIME;
options.sort_order = (sort_order == "desc") ?
SortOrder::DESC : SortOrder::ASC;
auto results = engine.search(query, options);
json response = json::array();
for (const auto& result : results) {
response.push_back({
{"path", result.path},
{"snippet", result.snippet},
{"score", result.score},
{"positions", result.positions}
});
}
res.set_content(response.dump(), "application/json");
});
// 索引接口
svr.Post("/index", [&](const httplib::Request& req, httplib::Response& res) {
auto j = json::parse(req.body);
std::string path = j["path"];
std::string content = j["content"];
engine.addDocument(path, content);
engine.commit();
res.set_content("{\"status\":\"ok\"}", "application/json");
});
svr.listen("localhost", 3000);
return 0;
}
Loading…
Cancel
Save