WebRequestHandler.cpp 74.9 KB
Newer Older
1
// Copyright (C) 2019-2020 Zilliz. All rights reserved.
B
BossZou 已提交
2
//
3 4
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
B
BossZou 已提交
5
//
6 7 8 9 10
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the License
// is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
// or implied. See the License for the specific language governing permissions and limitations under the License.
B
BossZou 已提交
11 12 13

#include "server/web_impl/handler/WebRequestHandler.h"

14
#include <algorithm>
15
#include <ctime>
B
BossZou 已提交
16
#include <string>
17
#include <unordered_map>
B
BossZou 已提交
18 19
#include <vector>

B
BossZou 已提交
20 21
#include <fiu-local.h>

22
#include "config/Config.h"
C
Cai Yudong 已提交
23
#include "config/Utils.h"
B
BossZou 已提交
24 25 26 27 28
#include "metrics/SystemInfo.h"
#include "server/delivery/request/BaseRequest.h"
#include "server/web_impl/Constants.h"
#include "server/web_impl/Types.h"
#include "server/web_impl/dto/PartitionDto.hpp"
29
#include "server/web_impl/utils/Util.h"
30
#include "thirdparty/nlohmann/json.hpp"
31
#include "utils/StringHelpFunctions.h"
B
BossZou 已提交
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49

namespace milvus {
namespace server {
namespace web {

StatusCode
WebErrorMap(ErrorCode code) {
    static const std::map<ErrorCode, StatusCode> code_map = {
        {SERVER_UNEXPECTED_ERROR, StatusCode::UNEXPECTED_ERROR},
        {SERVER_UNSUPPORTED_ERROR, StatusCode::UNEXPECTED_ERROR},
        {SERVER_NULL_POINTER, StatusCode::UNEXPECTED_ERROR},
        {SERVER_INVALID_ARGUMENT, StatusCode::ILLEGAL_ARGUMENT},
        {SERVER_FILE_NOT_FOUND, StatusCode::FILE_NOT_FOUND},
        {SERVER_NOT_IMPLEMENT, StatusCode::UNEXPECTED_ERROR},
        {SERVER_CANNOT_CREATE_FOLDER, StatusCode::CANNOT_CREATE_FOLDER},
        {SERVER_CANNOT_CREATE_FILE, StatusCode::CANNOT_CREATE_FILE},
        {SERVER_CANNOT_DELETE_FOLDER, StatusCode::CANNOT_DELETE_FOLDER},
        {SERVER_CANNOT_DELETE_FILE, StatusCode::CANNOT_DELETE_FILE},
G
groot 已提交
50 51 52
        {SERVER_COLLECTION_NOT_EXIST, StatusCode::COLLECTION_NOT_EXISTS},
        {SERVER_INVALID_COLLECTION_NAME, StatusCode::ILLEGAL_COLLECTION_NAME},
        {SERVER_INVALID_COLLECTION_DIMENSION, StatusCode::ILLEGAL_DIMENSION},
B
BossZou 已提交
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
        {SERVER_INVALID_VECTOR_DIMENSION, StatusCode::ILLEGAL_DIMENSION},

        {SERVER_INVALID_INDEX_TYPE, StatusCode::ILLEGAL_INDEX_TYPE},
        {SERVER_INVALID_ROWRECORD, StatusCode::ILLEGAL_ROWRECORD},
        {SERVER_INVALID_ROWRECORD_ARRAY, StatusCode::ILLEGAL_ROWRECORD},
        {SERVER_INVALID_TOPK, StatusCode::ILLEGAL_TOPK},
        {SERVER_INVALID_NPROBE, StatusCode::ILLEGAL_ARGUMENT},
        {SERVER_INVALID_INDEX_NLIST, StatusCode::ILLEGAL_NLIST},
        {SERVER_INVALID_INDEX_METRIC_TYPE, StatusCode::ILLEGAL_METRIC_TYPE},
        {SERVER_INVALID_INDEX_FILE_SIZE, StatusCode::ILLEGAL_ARGUMENT},
        {SERVER_ILLEGAL_VECTOR_ID, StatusCode::ILLEGAL_VECTOR_ID},
        {SERVER_ILLEGAL_SEARCH_RESULT, StatusCode::ILLEGAL_SEARCH_RESULT},
        {SERVER_CACHE_FULL, StatusCode::CACHE_FAILED},
        {SERVER_BUILD_INDEX_ERROR, StatusCode::BUILD_INDEX_ERROR},
        {SERVER_OUT_OF_MEMORY, StatusCode::OUT_OF_MEMORY},

G
groot 已提交
69
        {DB_NOT_FOUND, StatusCode::COLLECTION_NOT_EXISTS},
B
BossZou 已提交
70 71
        {DB_META_TRANSACTION_FAILED, StatusCode::META_FAILED},
    };
72 73 74
    if (code < StatusCode::MAX) {
        return StatusCode(code);
    } else if (code_map.find(code) != code_map.end()) {
B
BossZou 已提交
75 76 77 78 79 80
        return code_map.at(code);
    } else {
        return StatusCode::UNEXPECTED_ERROR;
    }
}

81 82 83 84 85 86 87 88
/////////////////////////////////// Private methods ///////////////////////////////////////
void
WebRequestHandler::AddStatusToJson(nlohmann::json& json, int64_t code, const std::string& msg) {
    json["code"] = (int64_t)code;
    json["message"] = msg;
}

Status
B
BossZou 已提交
89
WebRequestHandler::IsBinaryCollection(const std::string& collection_name, bool& bin) {
J
Jin Hai 已提交
90
    CollectionSchema schema;
91
    auto status = request_handler_.DescribeCollection(context_ptr_, collection_name, schema);
92 93 94
    if (status.ok()) {
        auto metric = engine::MetricType(schema.metric_type_);
        bin = engine::MetricType::HAMMING == metric || engine::MetricType::JACCARD == metric ||
95 96
              engine::MetricType::TANIMOTO == metric || engine::MetricType::SUPERSTRUCTURE == metric ||
              engine::MetricType::SUBSTRUCTURE == metric;
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
    }

    return status;
}

Status
WebRequestHandler::CopyRecordsFromJson(const nlohmann::json& json, engine::VectorsData& vectors, bool bin) {
    if (!json.is_array()) {
        return Status(ILLEGAL_BODY, "field \"vectors\" must be a array");
    }

    vectors.vector_count_ = json.size();

    if (!bin) {
        for (auto& vec : json) {
            if (!vec.is_array()) {
                return Status(ILLEGAL_BODY, "A vector in field \"vectors\" must be a float array");
            }
            for (auto& data : vec) {
                vectors.float_data_.emplace_back(data.get<float>());
            }
        }
    } else {
        for (auto& vec : json) {
            if (!vec.is_array()) {
                return Status(ILLEGAL_BODY, "A vector in field \"vectors\" must be a float array");
            }
            for (auto& data : vec) {
                vectors.binary_data_.emplace_back(data.get<uint8_t>());
            }
        }
    }

    return Status::OK();
}

B
BossZou 已提交
133 134
///////////////////////// WebRequestHandler methods ///////////////////////////////////////
Status
B
BossZou 已提交
135
WebRequestHandler::GetCollectionMetaInfo(const std::string& collection_name, nlohmann::json& json_out) {
J
Jin Hai 已提交
136
    CollectionSchema schema;
137
    auto status = request_handler_.DescribeCollection(context_ptr_, collection_name, schema);
B
BossZou 已提交
138 139 140 141 142
    if (!status.ok()) {
        return status;
    }

    int64_t count;
143
    status = request_handler_.CountCollection(context_ptr_, collection_name, count);
B
BossZou 已提交
144 145 146 147 148
    if (!status.ok()) {
        return status;
    }

    IndexParam index_param;
149
    status = request_handler_.DescribeIndex(context_ptr_, collection_name, index_param);
B
BossZou 已提交
150 151 152 153
    if (!status.ok()) {
        return status;
    }

J
Jin Hai 已提交
154
    json_out["collection_name"] = schema.collection_name_;
155 156 157
    json_out["dimension"] = schema.dimension_;
    json_out["index_file_size"] = schema.index_file_size_;
    json_out["index"] = IndexMap.at(engine::EngineType(index_param.index_type_));
158
    json_out["index_params"] = index_param.extra_params_;
159 160 161 162 163 164 165
    json_out["metric_type"] = MetricMap.at(engine::MetricType(schema.metric_type_));
    json_out["count"] = count;

    return Status::OK();
}

Status
B
BossZou 已提交
166
WebRequestHandler::GetCollectionStat(const std::string& collection_name, nlohmann::json& json_out) {
167
    std::string collection_info;
168
    auto status = request_handler_.ShowCollectionInfo(context_ptr_, collection_name, collection_info);
169 170

    if (status.ok()) {
171 172 173
        try {
            json_out = nlohmann::json::parse(collection_info);
        } catch (std::exception& e) {
B
BossZou 已提交
174 175
            return Status(SERVER_UNEXPECTED_ERROR,
                          "Error occurred when parsing collection stat information: " + std::string(e.what()));
176 177 178 179 180 181 182
        }
    }

    return status;
}

Status
183 184
WebRequestHandler::GetSegmentVectors(const std::string& collection_name, const std::string& segment_name,
                                     int64_t page_size, int64_t offset, nlohmann::json& json_out) {
185
    std::vector<int64_t> vector_ids;
186
    auto status = request_handler_.GetVectorIDs(context_ptr_, collection_name, segment_name, vector_ids);
187 188 189 190 191 192 193 194 195
    if (!status.ok()) {
        return status;
    }

    auto ids_begin = std::min(vector_ids.size(), (size_t)offset);
    auto ids_end = std::min(vector_ids.size(), (size_t)(offset + page_size));

    auto ids = std::vector<int64_t>(vector_ids.begin() + ids_begin, vector_ids.begin() + ids_end);
    nlohmann::json vectors_json;
196
    status = GetVectorsByIDs(collection_name, ids, vectors_json);
197 198 199 200 201 202 203 204 205 206 207 208 209 210 211

    nlohmann::json result_json;
    if (vectors_json.empty()) {
        json_out["vectors"] = std::vector<int64_t>();
    } else {
        json_out["vectors"] = vectors_json;
    }
    json_out["count"] = vector_ids.size();

    AddStatusToJson(json_out, status.code(), status.message());

    return Status::OK();
}

Status
212
WebRequestHandler::GetSegmentIds(const std::string& collection_name, const std::string& segment_name, int64_t page_size,
213 214
                                 int64_t offset, nlohmann::json& json_out) {
    std::vector<int64_t> vector_ids;
215
    auto status = request_handler_.GetVectorIDs(context_ptr_, collection_name, segment_name, vector_ids);
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230
    if (status.ok()) {
        auto ids_begin = std::min(vector_ids.size(), (size_t)offset);
        auto ids_end = std::min(vector_ids.size(), (size_t)(offset + page_size));

        if (ids_begin >= ids_end) {
            json_out["ids"] = std::vector<int64_t>();
        } else {
            for (size_t i = ids_begin; i < ids_end; i++) {
                json_out["ids"].push_back(std::to_string(vector_ids.at(i)));
            }
        }
        json_out["count"] = vector_ids.size();
    }

    return status;
231
}
B
BossZou 已提交
232

233 234 235
Status
WebRequestHandler::CommandLine(const std::string& cmd, std::string& reply) {
    return request_handler_.Cmd(context_ptr_, cmd, reply);
B
BossZou 已提交
236 237
}

238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253
Status
WebRequestHandler::Cmd(const std::string& cmd, std::string& result_str) {
    std::string reply;
    auto status = CommandLine(cmd, reply);

    if (status.ok()) {
        nlohmann::json result;
        AddStatusToJson(result, status.code(), status.message());
        result["reply"] = reply;
        result_str = result.dump();
    }

    return status;
}

Status
B
BossZou 已提交
254
WebRequestHandler::PreLoadCollection(const nlohmann::json& json, std::string& result_str) {
255 256
    if (!json.contains("collection_name")) {
        return Status(BODY_FIELD_LOSS, "Field \"load\" must contains collection_name");
257 258
    }

259
    auto collection_name = json["collection_name"];
260
    auto status = request_handler_.PreloadCollection(context_ptr_, collection_name.get<std::string>());
261 262 263 264 265
    if (status.ok()) {
        nlohmann::json result;
        AddStatusToJson(result, status.code(), status.message());
        result_str = result.dump();
    }
B
BossZou 已提交
266

267 268 269 270 271
    return status;
}

Status
WebRequestHandler::Flush(const nlohmann::json& json, std::string& result_str) {
272 273
    if (!json.contains("collection_names")) {
        return Status(BODY_FIELD_LOSS, "Field \"flush\" must contains collection_names");
274 275
    }

276 277 278
    auto collection_names = json["collection_names"];
    if (!collection_names.is_array()) {
        return Status(BODY_FIELD_LOSS, "Field \"collection_names\" must be and array");
279 280 281
    }

    std::vector<std::string> names;
282
    for (auto& name : collection_names) {
283 284 285 286 287 288 289 290 291 292 293 294 295 296 297
        names.emplace_back(name.get<std::string>());
    }

    auto status = request_handler_.Flush(context_ptr_, names);
    if (status.ok()) {
        nlohmann::json result;
        AddStatusToJson(result, status.code(), status.message());
        result_str = result.dump();
    }

    return status;
}

Status
WebRequestHandler::Compact(const nlohmann::json& json, std::string& result_str) {
298 299
    if (!json.contains("collection_name")) {
        return Status(BODY_FIELD_LOSS, "Field \"compact\" must contains collection_names");
300 301
    }

302 303 304
    auto collection_name = json["collection_name"];
    if (!collection_name.is_string()) {
        return Status(BODY_FIELD_LOSS, "Field \"collection_names\" must be a string");
305 306
    }

307
    auto name = collection_name.get<std::string>();
308

G
groot 已提交
309 310
    double compact_threshold = 0.1;  // compact trigger threshold: delete_counts/segment_counts
    auto status = request_handler_.Compact(context_ptr_, name, compact_threshold);
311 312 313

    if (status.ok()) {
        nlohmann::json result;
314
        AddStatusToJson(result, status.code(), status.message());
315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394
        result_str = result.dump();
    }

    return status;
}

Status
WebRequestHandler::GetConfig(std::string& result_str) {
    std::string cmd = "get_config *";
    std::string reply;
    auto status = CommandLine(cmd, reply);
    if (status.ok()) {
        nlohmann::json j = nlohmann::json::parse(reply);
#ifdef MILVUS_GPU_VERSION
        if (j.contains("gpu_resource_config")) {
            std::vector<std::string> gpus;
            if (j["gpu_resource_config"].contains("search_resources")) {
                auto gpu_search_res = j["gpu_resource_config"]["search_resources"].get<std::string>();
                StringHelpFunctions::SplitStringByDelimeter(gpu_search_res, ",", gpus);
                j["gpu_resource_config"]["search_resources"] = gpus;
            }
            if (j["gpu_resource_config"].contains("build_index_resources")) {
                auto gpu_build_res = j["gpu_resource_config"]["build_index_resources"].get<std::string>();
                gpus.clear();
                StringHelpFunctions::SplitStringByDelimeter(gpu_build_res, ",", gpus);
                j["gpu_resource_config"]["build_index_resources"] = gpus;
            }
        }
#endif
        // check if server require start
        Config& config = Config::GetInstance();
        bool required = false;
        config.GetServerRestartRequired(required);
        j["restart_required"] = required;
        result_str = j.dump();
    }

    return Status::OK();
}

Status
WebRequestHandler::SetConfig(const nlohmann::json& json, std::string& result_str) {
    if (!json.is_object()) {
        return Status(ILLEGAL_BODY, "Payload must be a map");
    }

    std::vector<std::string> cmds;
    for (auto& el : json.items()) {
        auto evalue = el.value();
        if (!evalue.is_object()) {
            return Status(ILLEGAL_BODY, "Invalid payload format, the root value must be json map");
        }

        for (auto& iel : el.value().items()) {
            auto ievalue = iel.value();
            if (!(ievalue.is_string() || ievalue.is_number() || ievalue.is_boolean())) {
                return Status(ILLEGAL_BODY, "Config value must be one of string, numeric or boolean");
            }
            std::ostringstream ss;
            if (ievalue.is_string()) {
                std::string vle = ievalue;
                ss << "set_config " << el.key() << "." << iel.key() << " " << vle;
            } else {
                ss << "set_config " << el.key() << "." << iel.key() << " " << ievalue;
            }
            cmds.emplace_back(ss.str());
        }
    }

    std::string msg;

    for (auto& c : cmds) {
        std::string reply;
        auto status = CommandLine(c, reply);
        if (!status.ok()) {
            return status;
        }
        msg += c + " successfully;";
    }

395 396 397
    nlohmann::json result;
    AddStatusToJson(result, StatusCode::SUCCESS, msg);

398 399 400 401 402 403 404 405 406 407 408
    bool required = false;
    Config& config = Config::GetInstance();
    config.GetServerRestartRequired(required);
    result["restart_required"] = required;

    result_str = result.dump();

    return Status::OK();
}

Status
409
WebRequestHandler::Search(const std::string& collection_name, const nlohmann::json& json, std::string& result_str) {
410 411 412 413 414
    if (!json.contains("topk")) {
        return Status(BODY_FIELD_LOSS, "Field \'topk\' is required");
    }
    int64_t topk = json["topk"];

B
BossZou 已提交
415 416 417 418
    if (!json.contains("params")) {
        return Status(BODY_FIELD_LOSS, "Field \'params\' is required");
    }

419 420 421 422 423 424 425 426 427 428 429 430
    std::vector<std::string> partition_tags;
    if (json.contains("partition_tags")) {
        auto tags = json["partition_tags"];
        if (!tags.is_null() && !tags.is_array()) {
            return Status(BODY_PARSE_FAIL, "Field \"partition_tags\" must be a array");
        }

        for (auto& tag : tags) {
            partition_tags.emplace_back(tag.get<std::string>());
        }
    }

B
BossZou 已提交
431 432 433 434 435 436
    TopKQueryResult result;
    Status status;
    if (json.contains("ids")) {
        auto vec_ids = json["ids"];
        if (!vec_ids.is_array()) {
            return Status(BODY_PARSE_FAIL, "Field \"ids\" must be ad array");
437
        }
B
BossZou 已提交
438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455

        std::vector<int64_t> id_array;
        for (auto& id_str : vec_ids) {
            id_array.emplace_back(std::stol(id_str.get<std::string>()));
        }
        //        std::vector<int64_t> id_array(vec_ids.begin(), vec_ids.end());
        status = request_handler_.SearchByID(context_ptr_, collection_name, id_array, topk, json["params"],
                                             partition_tags, result);
    } else {
        std::vector<std::string> file_id_vec;
        if (json.contains("file_ids")) {
            auto ids = json["file_ids"];
            if (!ids.is_null() && !ids.is_array()) {
                return Status(BODY_PARSE_FAIL, "Field \"file_ids\" must be a array");
            }
            for (auto& id : ids) {
                file_id_vec.emplace_back(id.get<std::string>());
            }
456 457
        }

B
BossZou 已提交
458 459 460 461 462
        bool bin_flag = false;
        status = IsBinaryCollection(collection_name, bin_flag);
        if (!status.ok()) {
            return status;
        }
463

B
BossZou 已提交
464 465 466
        if (!json.contains("vectors")) {
            return Status(BODY_FIELD_LOSS, "Field \"vectors\" is required");
        }
467

B
BossZou 已提交
468 469 470 471 472
        engine::VectorsData vectors_data;
        status = CopyRecordsFromJson(json["vectors"], vectors_data, bin_flag);
        if (!status.ok()) {
            return status;
        }
473

B
BossZou 已提交
474 475
        status = request_handler_.Search(context_ptr_, collection_name, vectors_data, topk, json["params"],
                                         partition_tags, file_id_vec, result);
476 477 478
    }
    if (!status.ok()) {
        return status;
479 480 481 482 483 484 485 486 487 488 489 490
    }

    nlohmann::json result_json;
    result_json["num"] = result.row_num_;
    if (result.row_num_ == 0) {
        result_json["result"] = std::vector<int64_t>();
        result_str = result_json.dump();
        return Status::OK();
    }

    auto step = result.id_list_.size() / result.row_num_;
    nlohmann::json search_result_json;
C
Cai Yudong 已提交
491
    for (int64_t i = 0; i < result.row_num_; i++) {
492 493 494 495 496 497 498 499 500 501 502 503 504 505 506
        nlohmann::json raw_result_json;
        for (size_t j = 0; j < step; j++) {
            nlohmann::json one_result_json;
            one_result_json["id"] = std::to_string(result.id_list_.at(i * step + j));
            one_result_json["distance"] = std::to_string(result.distance_list_.at(i * step + j));
            raw_result_json.emplace_back(one_result_json);
        }
        search_result_json.emplace_back(raw_result_json);
    }
    result_json["result"] = search_result_json;
    result_str = result_json.dump();

    return Status::OK();
}

507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544
Status
WebRequestHandler::ProcessLeafQueryJson(const nlohmann::json& json, milvus::query::BooleanQueryPtr& query) {
    if (json.contains("term")) {
        auto leaf_query = std::make_shared<query::LeafQuery>();
        auto term_json = json["term"];
        std::string field_name = term_json["field_name"];
        auto term_value_json = term_json["values"];
        if (!term_value_json.is_array()) {
            std::string msg = "Term json string is not an array";
            return Status{BODY_PARSE_FAIL, msg};
        }

        auto term_size = term_value_json.size();
        auto term_query = std::make_shared<query::TermQuery>();
        term_query->field_name = field_name;
        term_query->field_value.resize(term_size * sizeof(int64_t));

        switch (field_type_.at(field_name)) {
            case engine::meta::hybrid::DataType::INT8:
            case engine::meta::hybrid::DataType::INT16:
            case engine::meta::hybrid::DataType::INT32:
            case engine::meta::hybrid::DataType::INT64: {
                std::vector<int64_t> term_value(term_size, 0);
                for (uint64_t i = 0; i < term_size; ++i) {
                    term_value[i] = term_value_json[i].get<int64_t>();
                }
                memcpy(term_query->field_value.data(), term_value.data(), term_size * sizeof(int64_t));
                break;
            }
            case engine::meta::hybrid::DataType::FLOAT:
            case engine::meta::hybrid::DataType::DOUBLE: {
                std::vector<double> term_value(term_size, 0);
                for (uint64_t i = 0; i < term_size; ++i) {
                    term_value[i] = term_value_json[i].get<double>();
                }
                memcpy(term_query->field_value.data(), term_value.data(), term_size * sizeof(double));
                break;
            }
C
Cai Yudong 已提交
545 546
            default:
                break;
547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616
        }

        leaf_query->term_query = term_query;
        query->AddLeafQuery(leaf_query);
    } else if (json.contains("range")) {
        auto leaf_query = std::make_shared<query::LeafQuery>();
        auto range_query = std::make_shared<query::RangeQuery>();

        auto range_json = json["range"];
        std::string field_name = range_json["field_name"];
        range_query->field_name = field_name;

        auto range_value_json = range_json["values"];
        if (range_value_json.contains("lt")) {
            query::CompareExpr compare_expr;
            compare_expr.compare_operator = query::CompareOperator::LT;
            compare_expr.operand = range_value_json["lt"].get<std::string>();
            range_query->compare_expr.emplace_back(compare_expr);
        }
        if (range_value_json.contains("lte")) {
            query::CompareExpr compare_expr;
            compare_expr.compare_operator = query::CompareOperator::LTE;
            compare_expr.operand = range_value_json["lte"].get<std::string>();
            range_query->compare_expr.emplace_back(compare_expr);
        }
        if (range_value_json.contains("eq")) {
            query::CompareExpr compare_expr;
            compare_expr.compare_operator = query::CompareOperator::EQ;
            compare_expr.operand = range_value_json["eq"].get<std::string>();
            range_query->compare_expr.emplace_back(compare_expr);
        }
        if (range_value_json.contains("ne")) {
            query::CompareExpr compare_expr;
            compare_expr.compare_operator = query::CompareOperator::NE;
            compare_expr.operand = range_value_json["ne"].get<std::string>();
            range_query->compare_expr.emplace_back(compare_expr);
        }
        if (range_value_json.contains("gt")) {
            query::CompareExpr compare_expr;
            compare_expr.compare_operator = query::CompareOperator::GT;
            compare_expr.operand = range_value_json["gt"].get<std::string>();
            range_query->compare_expr.emplace_back(compare_expr);
        }
        if (range_value_json.contains("gte")) {
            query::CompareExpr compare_expr;
            compare_expr.compare_operator = query::CompareOperator::GTE;
            compare_expr.operand = range_value_json["gte"].get<std::string>();
            range_query->compare_expr.emplace_back(compare_expr);
        }

        leaf_query->range_query = range_query;
        query->AddLeafQuery(leaf_query);
    } else if (json.contains("vector")) {
        auto leaf_query = std::make_shared<query::LeafQuery>();
        auto vector_query = std::make_shared<query::VectorQuery>();

        auto vector_json = json["vector"];
        std::string field_name = vector_json["field_name"];
        vector_query->field_name = field_name;

        engine::VectorsData vectors;
        // TODO(yukun): process binary vector
        CopyRecordsFromJson(vector_json["values"], vectors, false);

        vector_query->query_vector.float_data = vectors.float_data_;
        vector_query->query_vector.binary_data = vectors.binary_data_;

        vector_query->topk = vector_json["topk"].get<int64_t>();
        vector_query->extra_params = vector_json["extra_params"];

Y
yukun 已提交
617 618 619 620
        // TODO(yukun): remove hardcode here
        std::string vector_placeholder = "placeholder_1";
        query_ptr_->vectors.insert(std::make_pair(vector_placeholder, vector_query));
        leaf_query->vector_placeholder = vector_placeholder;
621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687
        query->AddLeafQuery(leaf_query);
    }
    return Status::OK();
}

Status
WebRequestHandler::ProcessBoolQueryJson(const nlohmann::json& query_json, query::BooleanQueryPtr& boolean_query) {
    if (query_json.contains("must")) {
        boolean_query->SetOccur(query::Occur::MUST);
        auto must_json = query_json["must"];
        if (!must_json.is_array()) {
            std::string msg = "Must json string is not an array";
            return Status{BODY_PARSE_FAIL, msg};
        }

        for (auto& json : must_json) {
            auto must_query = std::make_shared<query::BooleanQuery>();
            if (json.contains("must") || json.contains("should") || json.contains("must_not")) {
                ProcessBoolQueryJson(json, must_query);
                boolean_query->AddBooleanQuery(must_query);
            } else {
                ProcessLeafQueryJson(json, boolean_query);
            }
        }
        return Status::OK();
    } else if (query_json.contains("should")) {
        boolean_query->SetOccur(query::Occur::SHOULD);
        auto should_json = query_json["should"];
        if (!should_json.is_array()) {
            std::string msg = "Should json string is not an array";
            return Status{BODY_PARSE_FAIL, msg};
        }

        for (auto& json : should_json) {
            if (json.contains("must") || json.contains("should") || json.contains("must_not")) {
                auto should_query = std::make_shared<query::BooleanQuery>();
                ProcessBoolQueryJson(json, should_query);
                boolean_query->AddBooleanQuery(should_query);
            } else {
                ProcessLeafQueryJson(json, boolean_query);
            }
        }
        return Status::OK();
    } else if (query_json.contains("must_not")) {
        boolean_query->SetOccur(query::Occur::MUST_NOT);
        auto should_json = query_json["must_not"];
        if (!should_json.is_array()) {
            std::string msg = "Must_not json string is not an array";
            return Status{BODY_PARSE_FAIL, msg};
        }

        for (auto& json : should_json) {
            if (json.contains("must") || json.contains("should") || json.contains("must_not")) {
                auto must_not_query = std::make_shared<query::BooleanQuery>();
                ProcessBoolQueryJson(json, must_not_query);
                boolean_query->AddBooleanQuery(must_not_query);
            } else {
                ProcessLeafQueryJson(json, boolean_query);
            }
        }
        return Status::OK();
    } else {
        std::string msg = "Must json string doesnot include right query";
        return Status{BODY_PARSE_FAIL, msg};
    }
}

Y
yukun 已提交
688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790
void
ConvertRowToColumnJson(const std::vector<engine::AttrsData>& row_attrs, std::vector<std::string>& field_names,
                       const int64_t row_num, nlohmann::json& column_attrs_json) {
    if (field_names.size() == 0) {
        if (row_attrs.size() > 0) {
            auto attr_it = row_attrs[0].attr_type_.begin();
            for (; attr_it != row_attrs[0].attr_type_.end(); attr_it++) {
                field_names.emplace_back(attr_it->first);
            }
        }
    }

    for (uint64_t i = 0; i < field_names.size() - 1; i++) {
        std::vector<int64_t> int_data;
        std::vector<double> double_data;
        for (auto& attr : row_attrs) {
            int64_t int_value;
            double double_value;
            auto attr_data = attr.attr_data_.at(field_names[i]);
            switch (attr.attr_type_.at(field_names[i])) {
                case engine::meta::hybrid::DataType::INT8: {
                    if (attr_data.size() == sizeof(int8_t)) {
                        int_value = attr_data[0];
                        int_data.emplace_back(int_value);
                    }
                    break;
                }
                case engine::meta::hybrid::DataType::INT16: {
                    if (attr_data.size() == sizeof(int16_t)) {
                        memcpy(&int_value, attr_data.data(), sizeof(int16_t));
                        int_data.emplace_back(int_value);
                    }
                    break;
                }
                case engine::meta::hybrid::DataType::INT32: {
                    if (attr_data.size() == sizeof(int32_t)) {
                        memcpy(&int_value, attr_data.data(), sizeof(int32_t));
                        int_data.emplace_back(int_value);
                    }
                    break;
                }
                case engine::meta::hybrid::DataType::INT64: {
                    if (attr_data.size() == sizeof(int64_t)) {
                        memcpy(&int_value, attr_data.data(), sizeof(int64_t));
                        int_data.emplace_back(int_value);
                    }
                    break;
                }
                case engine::meta::hybrid::DataType::FLOAT: {
                    if (attr_data.size() == sizeof(float)) {
                        float float_value;
                        memcpy(&float_value, attr_data.data(), sizeof(float));
                        double_value = float_value;
                        double_data.emplace_back(double_value);
                    }
                    break;
                }
                case engine::meta::hybrid::DataType::DOUBLE: {
                    if (attr_data.size() == sizeof(double)) {
                        memcpy(&double_value, attr_data.data(), sizeof(double));
                        double_data.emplace_back(double_value);
                    }
                    break;
                }
                default: { return; }
            }
        }
        if (int_data.size() > 0) {
            if (row_num == -1) {
                nlohmann::json int_data_json(int_data);
                column_attrs_json[field_names[i]] = int_data_json;
            } else {
                nlohmann::json topk_int_result;
                int64_t topk = int_data.size() / row_num;
                for (int64_t j = 0; j < row_num; j++) {
                    std::vector<int64_t> one_int_result(topk);
                    memcpy(one_int_result.data(), int_data.data() + j * topk, sizeof(int64_t) * topk);
                    nlohmann::json one_int_result_json(one_int_result);
                    std::string tag = "top" + std::to_string(j);
                    topk_int_result[tag] = one_int_result_json;
                }
                column_attrs_json[field_names[i]] = topk_int_result;
            }
        } else if (double_data.size() > 0) {
            if (row_num == -1) {
                nlohmann::json double_data_json(double_data);
                column_attrs_json[field_names[i]] = double_data_json;
            } else {
                nlohmann::json topk_double_result;
                int64_t topk = int_data.size() / row_num;
                for (int64_t j = 0; j < row_num; j++) {
                    std::vector<double> one_double_result(topk);
                    memcpy(one_double_result.data(), double_data.data() + j * topk, sizeof(double) * topk);
                    nlohmann::json one_double_result_json(one_double_result);
                    std::string tag = "top" + std::to_string(j);
                    topk_double_result[tag] = one_double_result_json;
                }
                column_attrs_json[field_names[i]] = topk_double_result;
            }
        }
    }
}

791 792 793 794 795 796 797 798 799 800
Status
WebRequestHandler::HybridSearch(const std::string& collection_name, const nlohmann::json& json,
                                std::string& result_str) {
    Status status;

    status = request_handler_.DescribeHybridCollection(context_ptr_, collection_name, field_type_);
    if (!status.ok()) {
        return Status{UNEXPECTED_ERROR, "DescribeHybridCollection failed"};
    }

Y
yukun 已提交
801 802 803 804 805 806 807 808
    milvus::json extra_params;
    if (json.contains("fields")) {
        if (json["fields"].is_array()) {
            extra_params["fields"] = json["fields"];
        }
    }
    auto query_json = json["query"];

809
    std::vector<std::string> partition_tags;
Y
yukun 已提交
810 811
    if (query_json.contains("partition_tags")) {
        auto tags = query_json["partition_tags"];
812 813 814 815 816 817 818 819 820
        if (!tags.is_null() && !tags.is_array()) {
            return Status(BODY_PARSE_FAIL, "Field \"partition_tags\" must be a array");
        }

        for (auto& tag : tags) {
            partition_tags.emplace_back(tag.get<std::string>());
        }
    }

Y
yukun 已提交
821 822
    if (query_json.contains("bool")) {
        auto boolean_query_json = query_json["bool"];
Y
yukun 已提交
823 824
        auto boolean_query = std::make_shared<query::BooleanQuery>();
        query_ptr_ = std::make_shared<query::Query>();
825 826 827 828 829

        status = ProcessBoolQueryJson(boolean_query_json, boolean_query);
        if (!status.ok()) {
            return status;
        }
Y
yukun 已提交
830
        auto general_query = std::make_shared<query::GeneralQuery>();
831 832
        query::GenBinaryQuery(boolean_query, general_query->bin);

Y
yukun 已提交
833 834
        query_ptr_->root = general_query->bin;

Y
yukun 已提交
835 836
        engine::QueryResult result;
        std::vector<std::string> field_names;
Y
yukun 已提交
837 838
        status = request_handler_.HybridSearch(context_ptr_, collection_name, partition_tags, general_query, query_ptr_,
                                               extra_params, field_names, result);
839 840 841 842 843 844 845 846 847 848 849 850 851

        if (!status.ok()) {
            return status;
        }

        nlohmann::json result_json;
        result_json["num"] = result.row_num_;
        if (result.row_num_ == 0) {
            result_json["result"] = std::vector<int64_t>();
            result_str = result_json.dump();
            return Status::OK();
        }

Y
yukun 已提交
852
        auto step = result.result_ids_.size() / result.row_num_;
853
        nlohmann::json search_result_json;
C
Cai Yudong 已提交
854
        for (int64_t i = 0; i < result.row_num_; i++) {
855 856 857
            nlohmann::json raw_result_json;
            for (size_t j = 0; j < step; j++) {
                nlohmann::json one_result_json;
Y
yukun 已提交
858 859
                one_result_json["id"] = std::to_string(result.result_ids_.at(i * step + j));
                one_result_json["distance"] = std::to_string(result.result_distances_.at(i * step + j));
860 861 862 863
                raw_result_json.emplace_back(one_result_json);
            }
            search_result_json.emplace_back(raw_result_json);
        }
Y
yukun 已提交
864 865 866
        nlohmann::json attr_json;
        ConvertRowToColumnJson(result.attrs_, field_names, result.row_num_, attr_json);
        result_json["Entity"] = attr_json;
867 868 869 870 871 872 873
        result_json["result"] = search_result_json;
        result_str = result_json.dump();
    }

    return Status::OK();
}

874
Status
875 876
WebRequestHandler::DeleteByIDs(const std::string& collection_name, const nlohmann::json& json,
                               std::string& result_str) {
877 878 879 880 881 882 883 884 885 886
    std::vector<int64_t> vector_ids;
    if (!json.contains("ids")) {
        return Status(BODY_FIELD_LOSS, "Field \"delete\" must contains \"ids\"");
    }
    auto ids = json["ids"];
    if (!ids.is_array()) {
        return Status(BODY_FIELD_LOSS, "\"ids\" must be an array");
    }

    for (auto& id : ids) {
887
        auto id_str = id.get<std::string>();
C
Cai Yudong 已提交
888
        if (!ValidateStringIsNumber(id_str).ok()) {
889 890 891
            return Status(ILLEGAL_BODY, "Members in \"ids\" must be integer string");
        }
        vector_ids.emplace_back(std::stol(id_str));
892 893
    }

894
    auto status = request_handler_.DeleteByID(context_ptr_, collection_name, vector_ids);
895 896 897 898

    nlohmann::json result_json;
    AddStatusToJson(result_json, status.code(), status.message());
    result_str = result_json.dump();
899 900 901 902

    return status;
}

Y
yukun 已提交
903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935
Status
WebRequestHandler::GetEntityByIDs(const std::string& collection_name, const std::vector<int64_t>& ids,
                                  nlohmann::json& json_out) {
    std::vector<engine::VectorsData> vector_batch;
    std::vector<engine::AttrsData> attr_batch;
    auto status = request_handler_.GetEntityByID(context_ptr_, collection_name, ids, attr_batch, vector_batch);
    if (!status.ok()) {
        return status;
    }

    bool bin;
    status = IsBinaryCollection(collection_name, bin);
    if (!status.ok()) {
        return status;
    }

    nlohmann::json vectors_json, attrs_json;
    for (size_t i = 0; i < vector_batch.size(); i++) {
        nlohmann::json vector_json;
        if (bin) {
            vector_json["vector"] = vector_batch.at(i).binary_data_;
        } else {
            vector_json["vector"] = vector_batch.at(i).float_data_;
        }
        vector_json["id"] = std::to_string(ids[i]);
        vectors_json.push_back(vector_json);
    }
    std::vector<std::string> field_names;
    ConvertRowToColumnJson(attr_batch, field_names, -1, attrs_json);
    json_out["vectors"] = vectors_json;
    json_out["attributes"] = attrs_json;
}

936
Status
937
WebRequestHandler::GetVectorsByIDs(const std::string& collection_name, const std::vector<int64_t>& ids,
938 939
                                   nlohmann::json& json_out) {
    std::vector<engine::VectorsData> vector_batch;
940 941 942
    auto status = request_handler_.GetVectorsByID(context_ptr_, collection_name, ids, vector_batch);
    if (!status.ok()) {
        return status;
943 944 945
    }

    bool bin;
B
BossZou 已提交
946
    status = IsBinaryCollection(collection_name, bin);
947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966
    if (!status.ok()) {
        return status;
    }

    nlohmann::json vectors_json;
    for (size_t i = 0; i < vector_batch.size(); i++) {
        nlohmann::json vector_json;
        if (bin) {
            vector_json["vector"] = vector_batch.at(i).binary_data_;
        } else {
            vector_json["vector"] = vector_batch.at(i).float_data_;
        }
        vector_json["id"] = std::to_string(ids[i]);
        json_out.push_back(vector_json);
    }

    return Status::OK();
}

////////////////////////////////// Router methods ////////////////////////////////////////////
B
BossZou 已提交
967 968 969 970 971
StatusDto::ObjectWrapper
WebRequestHandler::GetDevices(DevicesDto::ObjectWrapper& devices_dto) {
    auto system_info = SystemInfo::GetInstance();

    devices_dto->cpu = devices_dto->cpu->createShared();
972
    devices_dto->cpu->memory = system_info.GetPhysicalMemory() >> 30;
B
BossZou 已提交
973 974 975 976 977

    devices_dto->gpus = devices_dto->gpus->createShared();

#ifdef MILVUS_GPU_VERSION
    size_t count = system_info.num_device();
C
Cai Yudong 已提交
978
    std::vector<int64_t> device_mems = system_info.GPUMemoryTotal();
B
BossZou 已提交
979 980

    if (count != device_mems.size()) {
981
        RETURN_STATUS_DTO(UNEXPECTED_ERROR, "Can't obtain GPU info");
B
BossZou 已提交
982 983 984 985
    }

    for (size_t i = 0; i < count; i++) {
        auto device_dto = DeviceInfoDto::createShared();
986
        device_dto->memory = device_mems.at(i) >> 30;
B
BossZou 已提交
987 988 989 990 991 992 993 994 995
        devices_dto->gpus->put("GPU" + OString(std::to_string(i).c_str()), device_dto);
    }
#endif

    ASSIGN_RETURN_STATUS_DTO(Status::OK());
}

StatusDto::ObjectWrapper
WebRequestHandler::GetAdvancedConfig(AdvancedConfigDto::ObjectWrapper& advanced_config) {
996 997
    std::string reply;
    std::string cache_cmd_prefix = "get_config " + std::string(CONFIG_CACHE) + ".";
B
BossZou 已提交
998

999 1000
    std::string cache_cmd_string = cache_cmd_prefix + std::string(CONFIG_CACHE_CPU_CACHE_CAPACITY);
    auto status = CommandLine(cache_cmd_string, reply);
B
BossZou 已提交
1001
    if (!status.ok()) {
1002
        ASSIGN_RETURN_STATUS_DTO(status)
B
BossZou 已提交
1003
    }
1004
    advanced_config->cpu_cache_capacity = std::stol(reply);
B
BossZou 已提交
1005

1006 1007
    cache_cmd_string = cache_cmd_prefix + std::string(CONFIG_CACHE_CACHE_INSERT_DATA);
    CommandLine(cache_cmd_string, reply);
B
BossZou 已提交
1008 1009 1010
    if (!status.ok()) {
        ASSIGN_RETURN_STATUS_DTO(status)
    }
1011
    advanced_config->cache_insert_data = ("1" == reply || "true" == reply);
B
BossZou 已提交
1012

1013 1014 1015
    auto engine_cmd_prefix = "get_config " + std::string(CONFIG_ENGINE) + ".";
    auto engine_cmd_string = engine_cmd_prefix + std::string(CONFIG_ENGINE_USE_BLAS_THRESHOLD);
    CommandLine(engine_cmd_string, reply);
B
BossZou 已提交
1016 1017 1018
    if (!status.ok()) {
        ASSIGN_RETURN_STATUS_DTO(status)
    }
1019
    advanced_config->use_blas_threshold = std::stol(reply);
B
BossZou 已提交
1020 1021

#ifdef MILVUS_GPU_VERSION
W
Wang XiangYu 已提交
1022
    engine_cmd_string = engine_cmd_prefix + std::string(CONFIG_GPU_RESOURCE_GPU_SEARCH_THRESHOLD);
1023
    CommandLine(engine_cmd_string, reply);
B
BossZou 已提交
1024 1025 1026
    if (!status.ok()) {
        ASSIGN_RETURN_STATUS_DTO(status)
    }
1027
    advanced_config->gpu_search_threshold = std::stol(reply);
B
BossZou 已提交
1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050
#endif

    ASSIGN_RETURN_STATUS_DTO(status)
}

StatusDto::ObjectWrapper
WebRequestHandler::SetAdvancedConfig(const AdvancedConfigDto::ObjectWrapper& advanced_config) {
    if (nullptr == advanced_config->cpu_cache_capacity.get()) {
        RETURN_STATUS_DTO(BODY_FIELD_LOSS, "Field \'cpu_cache_capacity\' miss.");
    }

    if (nullptr == advanced_config->cache_insert_data.get()) {
        RETURN_STATUS_DTO(BODY_FIELD_LOSS, "Field \'cache_insert_data\' miss.");
    }

    if (nullptr == advanced_config->use_blas_threshold.get()) {
        RETURN_STATUS_DTO(BODY_FIELD_LOSS, "Field \'use_blas_threshold\' miss.");
    }

#ifdef MILVUS_GPU_VERSION
    if (nullptr == advanced_config->gpu_search_threshold.get()) {
        RETURN_STATUS_DTO(BODY_FIELD_LOSS, "Field \'gpu_search_threshold\' miss.");
    }
1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074
#endif

    std::string reply;
    std::string cache_cmd_prefix = "set_config " + std::string(CONFIG_CACHE) + ".";

    std::string cache_cmd_string = cache_cmd_prefix + std::string(CONFIG_CACHE_CPU_CACHE_CAPACITY) + " " +
                                   std::to_string(advanced_config->cpu_cache_capacity->getValue());
    auto status = CommandLine(cache_cmd_string, reply);
    if (!status.ok()) {
        ASSIGN_RETURN_STATUS_DTO(status)
    }

    cache_cmd_string = cache_cmd_prefix + std::string(CONFIG_CACHE_CACHE_INSERT_DATA) + " " +
                       std::to_string(advanced_config->cache_insert_data->getValue());
    status = CommandLine(cache_cmd_string, reply);
    if (!status.ok()) {
        ASSIGN_RETURN_STATUS_DTO(status)
    }

    auto engine_cmd_prefix = "set_config " + std::string(CONFIG_ENGINE) + ".";

    auto engine_cmd_string = engine_cmd_prefix + std::string(CONFIG_ENGINE_USE_BLAS_THRESHOLD) + " " +
                             std::to_string(advanced_config->use_blas_threshold->getValue());
    status = CommandLine(engine_cmd_string, reply);
B
BossZou 已提交
1075 1076 1077 1078
    if (!status.ok()) {
        ASSIGN_RETURN_STATUS_DTO(status)
    }

1079
#ifdef MILVUS_GPU_VERSION
W
Wang XiangYu 已提交
1080 1081 1082 1083
    auto gpu_cmd_prefix = "set_config " + std::string(CONFIG_GPU_RESOURCE) + ".";
    auto gpu_cmd_string = gpu_cmd_prefix + std::string(CONFIG_GPU_RESOURCE_GPU_SEARCH_THRESHOLD) + " " +
                          std::to_string(advanced_config->gpu_search_threshold->getValue());
    status = CommandLine(gpu_cmd_string, reply);
1084 1085 1086
    if (!status.ok()) {
        ASSIGN_RETURN_STATUS_DTO(status)
    }
B
BossZou 已提交
1087 1088 1089 1090 1091 1092 1093 1094
#endif

    ASSIGN_RETURN_STATUS_DTO(status)
}

#ifdef MILVUS_GPU_VERSION
StatusDto::ObjectWrapper
WebRequestHandler::GetGpuConfig(GPUConfigDto::ObjectWrapper& gpu_config_dto) {
1095 1096
    std::string reply;
    std::string gpu_cmd_prefix = "get_config " + std::string(CONFIG_GPU_RESOURCE) + ".";
B
BossZou 已提交
1097

1098 1099
    std::string gpu_cmd_request = gpu_cmd_prefix + std::string(CONFIG_GPU_RESOURCE_ENABLE);
    auto status = CommandLine(gpu_cmd_request, reply);
B
BossZou 已提交
1100 1101 1102
    if (!status.ok()) {
        ASSIGN_RETURN_STATUS_DTO(status);
    }
1103
    gpu_config_dto->enable = reply == "1" || reply == "true";
B
BossZou 已提交
1104

1105
    if (!gpu_config_dto->enable->getValue()) {
B
BossZou 已提交
1106 1107 1108
        ASSIGN_RETURN_STATUS_DTO(Status::OK());
    }

1109 1110
    gpu_cmd_request = gpu_cmd_prefix + std::string(CONFIG_GPU_RESOURCE_CACHE_CAPACITY);
    status = CommandLine(gpu_cmd_request, reply);
B
BossZou 已提交
1111 1112 1113
    if (!status.ok()) {
        ASSIGN_RETURN_STATUS_DTO(status);
    }
1114
    gpu_config_dto->cache_capacity = std::stol(reply);
B
BossZou 已提交
1115

1116 1117
    gpu_cmd_request = gpu_cmd_prefix + std::string(CONFIG_GPU_RESOURCE_SEARCH_RESOURCES);
    status = CommandLine(gpu_cmd_request, reply);
B
BossZou 已提交
1118 1119 1120 1121
    if (!status.ok()) {
        ASSIGN_RETURN_STATUS_DTO(status);
    }

1122 1123 1124
    std::vector<std::string> gpu_entry;
    StringHelpFunctions::SplitStringByDelimeter(reply, ",", gpu_entry);

B
BossZou 已提交
1125
    gpu_config_dto->search_resources = gpu_config_dto->search_resources->createShared();
1126 1127
    for (auto& device_id : gpu_entry) {
        gpu_config_dto->search_resources->pushBack(OString(device_id.c_str())->toUpperCase());
B
BossZou 已提交
1128
    }
1129
    gpu_entry.clear();
B
BossZou 已提交
1130

1131 1132
    gpu_cmd_request = gpu_cmd_prefix + std::string(CONFIG_GPU_RESOURCE_BUILD_INDEX_RESOURCES);
    status = CommandLine(gpu_cmd_request, reply);
B
BossZou 已提交
1133 1134 1135 1136
    if (!status.ok()) {
        ASSIGN_RETURN_STATUS_DTO(status);
    }

1137
    StringHelpFunctions::SplitStringByDelimeter(reply, ",", gpu_entry);
B
BossZou 已提交
1138
    gpu_config_dto->build_index_resources = gpu_config_dto->build_index_resources->createShared();
1139 1140
    for (auto& device_id : gpu_entry) {
        gpu_config_dto->build_index_resources->pushBack(OString(device_id.c_str())->toUpperCase());
B
BossZou 已提交
1141 1142 1143 1144 1145 1146 1147
    }

    ASSIGN_RETURN_STATUS_DTO(Status::OK());
}

StatusDto::ObjectWrapper
WebRequestHandler::SetGpuConfig(const GPUConfigDto::ObjectWrapper& gpu_config_dto) {
1148
    // Step 1: Check config param
B
BossZou 已提交
1149 1150 1151
    if (nullptr == gpu_config_dto->enable.get()) {
        RETURN_STATUS_DTO(BODY_FIELD_LOSS, "Field \'enable\' miss")
    }
1152 1153 1154

    if (nullptr == gpu_config_dto->cache_capacity.get()) {
        RETURN_STATUS_DTO(BODY_FIELD_LOSS, "Field \'cache_capacity\' miss")
B
BossZou 已提交
1155 1156
    }

1157 1158 1159
    if (nullptr == gpu_config_dto->search_resources.get()) {
        gpu_config_dto->search_resources = gpu_config_dto->search_resources->createShared();
        gpu_config_dto->search_resources->pushBack("GPU0");
B
BossZou 已提交
1160 1161
    }

1162 1163 1164
    if (nullptr == gpu_config_dto->build_index_resources.get()) {
        gpu_config_dto->build_index_resources = gpu_config_dto->build_index_resources->createShared();
        gpu_config_dto->build_index_resources->pushBack("GPU0");
B
BossZou 已提交
1165
    }
1166 1167 1168 1169 1170 1171 1172

    // Step 2: Set config
    std::string reply;
    std::string gpu_cmd_prefix = "set_config " + std::string(CONFIG_GPU_RESOURCE) + ".";
    std::string gpu_cmd_request = gpu_cmd_prefix + std::string(CONFIG_GPU_RESOURCE_ENABLE) + " " +
                                  std::to_string(gpu_config_dto->enable->getValue());
    auto status = CommandLine(gpu_cmd_request, reply);
B
BossZou 已提交
1173 1174 1175 1176
    if (!status.ok()) {
        ASSIGN_RETURN_STATUS_DTO(status);
    }

1177 1178 1179 1180 1181 1182 1183 1184 1185
    if (!gpu_config_dto->enable->getValue()) {
        RETURN_STATUS_DTO(SUCCESS, "Set Gpu resources to false");
    }

    gpu_cmd_request = gpu_cmd_prefix + std::string(CONFIG_GPU_RESOURCE_CACHE_CAPACITY) + " " +
                      std::to_string(gpu_config_dto->cache_capacity->getValue());
    status = CommandLine(gpu_cmd_request, reply);
    if (!status.ok()) {
        ASSIGN_RETURN_STATUS_DTO(status);
B
BossZou 已提交
1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199
    }

    std::vector<std::string> search_resources;
    gpu_config_dto->search_resources->forEach(
        [&search_resources](const OString& res) { search_resources.emplace_back(res->toLowerCase()->std_str()); });

    std::string search_resources_value;
    for (auto& res : search_resources) {
        search_resources_value += res + ",";
    }
    auto len = search_resources_value.size();
    if (len > 0) {
        search_resources_value.erase(len - 1);
    }
1200 1201 1202

    gpu_cmd_request = gpu_cmd_prefix + std::string(CONFIG_GPU_RESOURCE_SEARCH_RESOURCES) + " " + search_resources_value;
    status = CommandLine(gpu_cmd_request, reply);
B
BossZou 已提交
1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219
    if (!status.ok()) {
        ASSIGN_RETURN_STATUS_DTO(status);
    }

    std::vector<std::string> build_resources;
    gpu_config_dto->build_index_resources->forEach(
        [&build_resources](const OString& res) { build_resources.emplace_back(res->toLowerCase()->std_str()); });

    std::string build_resources_value;
    for (auto& res : build_resources) {
        build_resources_value += res + ",";
    }
    len = build_resources_value.size();
    if (len > 0) {
        build_resources_value.erase(len - 1);
    }

1220 1221 1222
    gpu_cmd_request =
        gpu_cmd_prefix + std::string(CONFIG_GPU_RESOURCE_BUILD_INDEX_RESOURCES) + " " + build_resources_value;
    status = CommandLine(gpu_cmd_request, reply);
B
BossZou 已提交
1223 1224 1225 1226 1227 1228 1229 1230
    if (!status.ok()) {
        ASSIGN_RETURN_STATUS_DTO(status);
    }

    ASSIGN_RETURN_STATUS_DTO(Status::OK());
}
#endif

1231 1232
/*************
 *
J
Jin Hai 已提交
1233
 * Collection {
1234
 */
B
BossZou 已提交
1235
StatusDto::ObjectWrapper
B
BossZou 已提交
1236
WebRequestHandler::CreateCollection(const CollectionRequestDto::ObjectWrapper& collection_schema) {
1237 1238
    if (nullptr == collection_schema->collection_name.get()) {
        RETURN_STATUS_DTO(BODY_FIELD_LOSS, "Field \'collection_name\' is missing")
B
BossZou 已提交
1239 1240
    }

1241
    if (nullptr == collection_schema->dimension.get()) {
B
BossZou 已提交
1242 1243 1244
        RETURN_STATUS_DTO(BODY_FIELD_LOSS, "Field \'dimension\' is missing")
    }

1245
    if (nullptr == collection_schema->index_file_size.get()) {
B
BossZou 已提交
1246 1247 1248
        RETURN_STATUS_DTO(BODY_FIELD_LOSS, "Field \'index_file_size\' is missing")
    }

1249
    if (nullptr == collection_schema->metric_type.get()) {
B
BossZou 已提交
1250 1251 1252
        RETURN_STATUS_DTO(BODY_FIELD_LOSS, "Field \'metric_type\' is missing")
    }

1253
    if (MetricNameMap.find(collection_schema->metric_type->std_str()) == MetricNameMap.end()) {
B
BossZou 已提交
1254 1255 1256
        RETURN_STATUS_DTO(ILLEGAL_METRIC_TYPE, "metric_type is illegal")
    }

1257 1258 1259 1260
    auto status = request_handler_.CreateCollection(
        context_ptr_, collection_schema->collection_name->std_str(), collection_schema->dimension,
        collection_schema->index_file_size,
        static_cast<int64_t>(MetricNameMap.at(collection_schema->metric_type->std_str())));
B
BossZou 已提交
1261 1262 1263 1264

    ASSIGN_RETURN_STATUS_DTO(status)
}

1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308
StatusDto::ObjectWrapper
WebRequestHandler::CreateHybridCollection(const milvus::server::web::OString& body) {
    auto json_str = nlohmann::json::parse(body->c_str());
    std::string collection_name = json_str["collection_name"];

    // TODO(yukun): do checking
    std::vector<std::pair<std::string, engine::meta::hybrid::DataType>> field_types;
    std::vector<std::pair<std::string, std::string>> field_extra_params;
    std::vector<std::pair<std::string, uint64_t>> vector_dimensions;
    for (auto& field : json_str["fields"]) {
        std::string field_name = field["field_name"];
        std::string field_type = field["field_type"];
        auto extra_params = field["extra_params"];
        if (field_type == "int8") {
            field_types.emplace_back(std::make_pair(field_name, engine::meta::hybrid::DataType::INT8));
        } else if (field_type == "int16") {
            field_types.emplace_back(std::make_pair(field_name, engine::meta::hybrid::DataType::INT16));
        } else if (field_type == "int32") {
            field_types.emplace_back(std::make_pair(field_name, engine::meta::hybrid::DataType::INT32));
        } else if (field_type == "int64") {
            field_types.emplace_back(std::make_pair(field_name, engine::meta::hybrid::DataType::INT64));
        } else if (field_type == "float") {
            field_types.emplace_back(std::make_pair(field_name, engine::meta::hybrid::DataType::FLOAT));
        } else if (field_type == "double") {
            field_types.emplace_back(std::make_pair(field_name, engine::meta::hybrid::DataType::DOUBLE));
        } else if (field_type == "vector") {
        } else {
            std::string msg = field_name + " has wrong field_type";
            RETURN_STATUS_DTO(BODY_PARSE_FAIL, msg.c_str());
        }

        field_extra_params.emplace_back(std::make_pair(field_name, extra_params.dump()));

        if (extra_params.contains("dimension")) {
            vector_dimensions.emplace_back(std::make_pair(field_name, extra_params["dimension"].get<uint64_t>()));
        }
    }

    auto status = request_handler_.CreateHybridCollection(context_ptr_, collection_name, field_types, vector_dimensions,
                                                          field_extra_params);

    ASSIGN_RETURN_STATUS_DTO(status)
}

B
BossZou 已提交
1309
StatusDto::ObjectWrapper
B
BossZou 已提交
1310
WebRequestHandler::ShowCollections(const OQueryParams& query_params, OString& result) {
1311 1312 1313 1314
    int64_t offset = 0;
    auto status = ParseQueryInteger(query_params, "offset", offset);
    if (!status.ok()) {
        RETURN_STATUS_DTO(status.code(), status.message().c_str());
B
BossZou 已提交
1315 1316
    }

1317 1318 1319 1320
    int64_t page_size = 10;
    status = ParseQueryInteger(query_params, "page_size", page_size);
    if (!status.ok()) {
        RETURN_STATUS_DTO(status.code(), status.message().c_str());
1321 1322
    }

1323
    if (offset < 0 || page_size < 0) {
1324
        RETURN_STATUS_DTO(ILLEGAL_QUERY_PARAM, "Query param 'offset' or 'page_size' should equal or bigger than 0");
B
BossZou 已提交
1325
    }
1326

1327
    bool all_required = false;
1328 1329 1330
    ParseQueryBool(query_params, "all_required", all_required);
    if (!status.ok()) {
        RETURN_STATUS_DTO(status.code(), status.message().c_str());
1331 1332
    }

1333
    std::vector<std::string> collections;
1334
    status = request_handler_.ShowCollections(context_ptr_, collections);
1335 1336 1337
    if (!status.ok()) {
        ASSIGN_RETURN_STATUS_DTO(status)
    }
B
BossZou 已提交
1338

1339
    if (all_required) {
1340
        offset = 0;
1341
        page_size = collections.size();
1342
    } else {
1343 1344
        offset = std::min((size_t)offset, collections.size());
        page_size = std::min(collections.size() - offset, (size_t)page_size);
1345 1346
    }

1347
    nlohmann::json collections_json;
1348
    for (int64_t i = offset; i < page_size + offset; i++) {
1349
        nlohmann::json collection_json;
B
BossZou 已提交
1350
        status = GetCollectionMetaInfo(collections.at(i), collection_json);
B
BossZou 已提交
1351
        if (!status.ok()) {
1352
            ASSIGN_RETURN_STATUS_DTO(status)
B
BossZou 已提交
1353
        }
1354
        collections_json.push_back(collection_json);
1355
    }
1356

1357
    nlohmann::json result_json;
1358 1359 1360
    result_json["count"] = collections.size();
    if (collections_json.empty()) {
        result_json["collections"] = std::vector<int64_t>();
1361
    } else {
1362
        result_json["collections"] = collections_json;
B
BossZou 已提交
1363 1364
    }

1365 1366
    result = result_json.dump().c_str();

B
BossZou 已提交
1367 1368 1369
    ASSIGN_RETURN_STATUS_DTO(status)
}

1370
StatusDto::ObjectWrapper
B
BossZou 已提交
1371
WebRequestHandler::GetCollection(const OString& collection_name, const OQueryParams& query_params, OString& result) {
1372 1373
    if (nullptr == collection_name.get()) {
        RETURN_STATUS_DTO(PATH_PARAM_LOSS, "Path param \'collection_name\' is required!");
1374 1375
    }

1376 1377 1378 1379 1380
    std::string stat;
    auto status = ParseQueryStr(query_params, "info", stat);
    if (!status.ok()) {
        RETURN_STATUS_DTO(status.code(), status.message().c_str());
    }
1381

1382
    if (!stat.empty() && stat == "stat") {
1383
        nlohmann::json json;
B
BossZou 已提交
1384
        status = GetCollectionStat(collection_name->std_str(), json);
1385
        result = status.ok() ? json.dump().c_str() : "NULL";
1386 1387
    } else {
        nlohmann::json json;
B
BossZou 已提交
1388
        status = GetCollectionMetaInfo(collection_name->std_str(), json);
1389
        result = status.ok() ? json.dump().c_str() : "NULL";
1390 1391 1392 1393 1394
    }

    ASSIGN_RETURN_STATUS_DTO(status);
}

B
BossZou 已提交
1395
StatusDto::ObjectWrapper
B
BossZou 已提交
1396
WebRequestHandler::DropCollection(const OString& collection_name) {
1397
    auto status = request_handler_.DropCollection(context_ptr_, collection_name->std_str());
B
BossZou 已提交
1398 1399 1400 1401

    ASSIGN_RETURN_STATUS_DTO(status)
}

1402 1403 1404 1405 1406
/***********
 *
 * Index {
 */

B
BossZou 已提交
1407
StatusDto::ObjectWrapper
J
Jin Hai 已提交
1408
WebRequestHandler::CreateIndex(const OString& collection_name, const OString& body) {
1409 1410 1411 1412 1413
    try {
        auto request_json = nlohmann::json::parse(body->std_str());
        if (!request_json.contains("index_type")) {
            RETURN_STATUS_DTO(BODY_FIELD_LOSS, "Field \'index_type\' is required");
        }
B
BossZou 已提交
1414

1415 1416 1417 1418 1419 1420 1421 1422
        std::string index_type = request_json["index_type"];
        if (IndexNameMap.find(index_type) == IndexNameMap.end()) {
            RETURN_STATUS_DTO(ILLEGAL_INDEX_TYPE, "The index type is invalid.")
        }
        auto index = static_cast<int64_t>(IndexNameMap.at(index_type));
        if (!request_json.contains("params")) {
            RETURN_STATUS_DTO(BODY_FIELD_LOSS, "Field \'params\' is required")
        }
J
Jin Hai 已提交
1423 1424
        auto status =
            request_handler_.CreateIndex(context_ptr_, collection_name->std_str(), index, request_json["params"]);
1425 1426
        ASSIGN_RETURN_STATUS_DTO(status);
    } catch (nlohmann::detail::parse_error& e) {
Y
Yhz 已提交
1427
        RETURN_STATUS_DTO(BODY_PARSE_FAIL, e.what())
1428
    } catch (nlohmann::detail::type_error& e) {
Y
Yhz 已提交
1429
        RETURN_STATUS_DTO(BODY_PARSE_FAIL, e.what())
B
BossZou 已提交
1430 1431
    }

1432
    ASSIGN_RETURN_STATUS_DTO(Status::OK())
B
BossZou 已提交
1433 1434 1435
}

StatusDto::ObjectWrapper
1436
WebRequestHandler::GetIndex(const OString& collection_name, OString& result) {
B
BossZou 已提交
1437
    IndexParam param;
1438
    auto status = request_handler_.DescribeIndex(context_ptr_, collection_name->std_str(), param);
B
BossZou 已提交
1439 1440

    if (status.ok()) {
1441 1442 1443 1444 1445
        nlohmann::json json_out;
        auto index_type = IndexMap.at(engine::EngineType(param.index_type_));
        json_out["index_type"] = index_type;
        json_out["params"] = nlohmann::json::parse(param.extra_params_);
        result = json_out.dump().c_str();
B
BossZou 已提交
1446 1447 1448 1449 1450 1451
    }

    ASSIGN_RETURN_STATUS_DTO(status)
}

StatusDto::ObjectWrapper
1452 1453
WebRequestHandler::DropIndex(const OString& collection_name) {
    auto status = request_handler_.DropIndex(context_ptr_, collection_name->std_str());
B
BossZou 已提交
1454 1455 1456 1457 1458

    ASSIGN_RETURN_STATUS_DTO(status)
}

StatusDto::ObjectWrapper
1459
WebRequestHandler::CreatePartition(const OString& collection_name, const PartitionRequestDto::ObjectWrapper& param) {
B
BossZou 已提交
1460 1461 1462 1463
    if (nullptr == param->partition_tag.get()) {
        RETURN_STATUS_DTO(BODY_FIELD_LOSS, "Field \'partition_tag\' is required")
    }

1464
    auto status =
1465
        request_handler_.CreatePartition(context_ptr_, collection_name->std_str(), param->partition_tag->std_str());
B
BossZou 已提交
1466 1467 1468 1469 1470

    ASSIGN_RETURN_STATUS_DTO(status)
}

StatusDto::ObjectWrapper
B
BossZou 已提交
1471
WebRequestHandler::ShowPartitions(const OString& collection_name, const OQueryParams& query_params,
B
BossZou 已提交
1472
                                  PartitionListDto::ObjectWrapper& partition_list_dto) {
1473 1474 1475 1476
    int64_t offset = 0;
    auto status = ParseQueryInteger(query_params, "offset", offset);
    if (!status.ok()) {
        RETURN_STATUS_DTO(status.code(), status.message().c_str());
B
BossZou 已提交
1477 1478
    }

1479 1480 1481 1482
    int64_t page_size = 10;
    status = ParseQueryInteger(query_params, "page_size", page_size);
    if (!status.ok()) {
        RETURN_STATUS_DTO(status.code(), status.message().c_str());
1483 1484
    }

1485
    if (offset < 0 || page_size < 0) {
1486 1487
        ASSIGN_RETURN_STATUS_DTO(
            Status(SERVER_UNEXPECTED_ERROR, "Query param 'offset' or 'page_size' should equal or bigger than 0"));
B
BossZou 已提交
1488 1489
    }

1490 1491 1492 1493
    bool all_required = false;
    auto required = query_params.get("all_required");
    if (nullptr != required.get()) {
        auto required_str = required->std_str();
C
Cai Yudong 已提交
1494
        if (!ValidateStringIsBool(required_str).ok()) {
1495 1496 1497 1498 1499
            RETURN_STATUS_DTO(ILLEGAL_QUERY_PARAM, "Query param \'all_required\' must be a bool")
        }
        all_required = required_str == "True" || required_str == "true";
    }

B
BossZou 已提交
1500
    std::vector<PartitionParam> partitions;
1501
    status = request_handler_.ShowPartitions(context_ptr_, collection_name->std_str(), partitions);
1502 1503 1504
    if (!status.ok()) {
        ASSIGN_RETURN_STATUS_DTO(status)
    }
B
BossZou 已提交
1505

1506
    if (all_required) {
1507 1508
        offset = 0;
        page_size = partitions.size();
1509
    } else {
1510 1511
        offset = std::min((size_t)offset, partitions.size());
        page_size = std::min(partitions.size() - offset, (size_t)page_size);
1512 1513
    }

1514
    partition_list_dto->count = partitions.size();
1515 1516
    partition_list_dto->partitions = partition_list_dto->partitions->createShared();

C
Cai Yudong 已提交
1517
    if (offset < (int64_t)(partitions.size())) {
1518
        for (int64_t i = offset; i < page_size + offset; i++) {
1519 1520 1521
            auto partition_dto = PartitionFieldsDto::createShared();
            partition_dto->partition_tag = partitions.at(i).tag_.c_str();
            partition_list_dto->partitions->pushBack(partition_dto);
B
BossZou 已提交
1522 1523 1524 1525 1526 1527 1528
        }
    }

    ASSIGN_RETURN_STATUS_DTO(status)
}

StatusDto::ObjectWrapper
1529
WebRequestHandler::DropPartition(const OString& collection_name, const OString& body) {
1530 1531 1532 1533 1534 1535 1536 1537 1538
    std::string tag;
    try {
        auto json = nlohmann::json::parse(body->std_str());
        tag = json["partition_tag"].get<std::string>();
    } catch (nlohmann::detail::parse_error& e) {
        RETURN_STATUS_DTO(BODY_PARSE_FAIL, e.what())
    } catch (nlohmann::detail::type_error& e) {
        RETURN_STATUS_DTO(BODY_PARSE_FAIL, e.what())
    }
1539
    auto status = request_handler_.DropPartition(context_ptr_, collection_name->std_str(), tag);
B
BossZou 已提交
1540 1541 1542 1543

    ASSIGN_RETURN_STATUS_DTO(status)
}

1544 1545 1546 1547
/***********
 *
 * Segment {
 */
B
BossZou 已提交
1548
StatusDto::ObjectWrapper
1549
WebRequestHandler::ShowSegments(const OString& collection_name, const OQueryParams& query_params, OString& response) {
1550 1551 1552 1553
    int64_t offset = 0;
    auto status = ParseQueryInteger(query_params, "offset", offset);
    if (!status.ok()) {
        RETURN_STATUS_DTO(status.code(), status.message().c_str());
1554 1555
    }

1556 1557 1558 1559
    int64_t page_size = 10;
    status = ParseQueryInteger(query_params, "page_size", page_size);
    if (!status.ok()) {
        RETURN_STATUS_DTO(status.code(), status.message().c_str());
1560 1561
    }

1562
    if (offset < 0 || page_size < 0) {
1563 1564 1565
        RETURN_STATUS_DTO(ILLEGAL_QUERY_PARAM, "Query param 'offset' or 'page_size' should equal or bigger than 0");
    }

1566 1567 1568 1569
    bool all_required = false;
    auto required = query_params.get("all_required");
    if (nullptr != required.get()) {
        auto required_str = required->std_str();
C
Cai Yudong 已提交
1570
        if (!ValidateStringIsBool(required_str).ok()) {
1571 1572 1573 1574 1575
            RETURN_STATUS_DTO(ILLEGAL_QUERY_PARAM, "Query param \'all_required\' must be a bool")
        }
        all_required = required_str == "True" || required_str == "true";
    }

1576 1577 1578 1579 1580
    std::string tag;
    if (nullptr != query_params.get("partition_tag").get()) {
        tag = query_params.get("partition_tag")->std_str();
    }

1581
    std::string info;
1582
    status = request_handler_.ShowCollectionInfo(context_ptr_, collection_name->std_str(), info);
1583 1584 1585 1586
    if (!status.ok()) {
        ASSIGN_RETURN_STATUS_DTO(status)
    }

1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615
    nlohmann::json info_json = nlohmann::json::parse(info);
    nlohmann::json segments_json = nlohmann::json::array();
    for (auto& par : info_json["partitions"]) {
        if (!(all_required || tag.empty() || tag == par["tag"])) {
            continue;
        }

        auto segments = par["segments"];
        if (!segments.is_null()) {
            for (auto& seg : segments) {
                seg["partition_tag"] = par["tag"];
                segments_json.push_back(seg);
            }
        }
    }
    nlohmann::json result_json;
    if (!all_required) {
        int64_t size = segments_json.size();
        int iter_begin = std::min(size, offset);
        int iter_end = std::min(size, offset + page_size);

        nlohmann::json segments_slice_json = nlohmann::json::array();
        segments_slice_json.insert(segments_slice_json.begin(), segments_json.begin() + iter_begin,
                                   segments_json.begin() + iter_end);
        result_json["segments"] = segments_slice_json;  // segments_json;
    } else {
        result_json["segments"] = segments_json;
    }
    result_json["count"] = segments_json.size();
1616 1617 1618
    AddStatusToJson(result_json, status.code(), status.message());
    response = result_json.dump().c_str();

B
BossZou 已提交
1619 1620 1621 1622
    ASSIGN_RETURN_STATUS_DTO(status)
}

StatusDto::ObjectWrapper
1623
WebRequestHandler::GetSegmentInfo(const OString& collection_name, const OString& segment_name, const OString& info,
1624
                                  const OQueryParams& query_params, OString& result) {
1625 1626 1627 1628
    int64_t offset = 0;
    auto status = ParseQueryInteger(query_params, "offset", offset);
    if (!status.ok()) {
        RETURN_STATUS_DTO(status.code(), status.message().c_str());
1629 1630
    }

1631 1632 1633 1634
    int64_t page_size = 10;
    status = ParseQueryInteger(query_params, "page_size", page_size);
    if (!status.ok()) {
        RETURN_STATUS_DTO(status.code(), status.message().c_str());
B
BossZou 已提交
1635 1636
    }

1637
    if (offset < 0 || page_size < 0) {
1638 1639 1640 1641 1642
        ASSIGN_RETURN_STATUS_DTO(
            Status(SERVER_UNEXPECTED_ERROR, "Query param 'offset' or 'page_size' should equal or bigger than 0"));
    }

    std::string re = info->std_str();
1643
    status = Status::OK();
1644 1645 1646
    nlohmann::json json;
    // Get vectors
    if (re == "vectors") {
1647
        status = GetSegmentVectors(collection_name->std_str(), segment_name->std_str(), page_size, offset, json);
1648 1649
        // Get vector ids
    } else if (re == "ids") {
1650
        status = GetSegmentIds(collection_name->std_str(), segment_name->std_str(), page_size, offset, json);
B
BossZou 已提交
1651 1652
    }

1653
    result = status.ok() ? json.dump().c_str() : "NULL";
B
BossZou 已提交
1654

1655 1656 1657 1658 1659 1660 1661 1662
    ASSIGN_RETURN_STATUS_DTO(status)
}

/**********
 *
 * Vector {
 */
StatusDto::ObjectWrapper
1663
WebRequestHandler::Insert(const OString& collection_name, const OString& body, VectorIdsDto::ObjectWrapper& ids_dto) {
1664 1665
    if (nullptr == body.get() || body->getSize() == 0) {
        RETURN_STATUS_DTO(BODY_FIELD_LOSS, "Request payload is required.")
B
BossZou 已提交
1666 1667
    }

1668 1669
    // step 1: copy vectors
    bool bin_flag;
B
BossZou 已提交
1670
    auto status = IsBinaryCollection(collection_name->std_str(), bin_flag);
1671 1672
    if (!status.ok()) {
        ASSIGN_RETURN_STATUS_DTO(status)
B
BossZou 已提交
1673 1674
    }

1675 1676 1677 1678
    auto body_json = nlohmann::json::parse(body->std_str());
    if (!body_json.contains("vectors")) {
        RETURN_STATUS_DTO(BODY_FIELD_LOSS, "Field \'vectors\' is required");
    }
G
groot 已提交
1679
    engine::VectorsData vectors;
1680 1681 1682 1683
    CopyRecordsFromJson(body_json["vectors"], vectors, bin_flag);
    if (!status.ok()) {
        ASSIGN_RETURN_STATUS_DTO(status)
    }
1684

1685 1686 1687 1688 1689
    // step 2: copy id array
    if (body_json.contains("ids")) {
        auto& ids_json = body_json["ids"];
        if (!ids_json.is_array()) {
            RETURN_STATUS_DTO(ILLEGAL_BODY, "Field \"ids\" must be a array");
1690
        }
1691 1692
        auto& id_array = vectors.id_array_;
        id_array.clear();
1693 1694 1695 1696 1697 1698 1699 1700
        try {
            for (auto& id_str : ids_json) {
                int64_t id = std::stol(id_str.get<std::string>());
                id_array.emplace_back(id);
            }
        } catch (std::exception& e) {
            std::string err_msg = std::string("Cannot convert vectors id. details: ") + e.what();
            RETURN_STATUS_DTO(SERVER_UNEXPECTED_ERROR, err_msg.c_str());
1701
        }
G
groot 已提交
1702
    }
B
BossZou 已提交
1703

1704 1705 1706 1707
    // step 3: copy partition tag
    std::string tag;
    if (body_json.contains("partition_tag")) {
        tag = body_json["partition_tag"];
1708
    }
B
BossZou 已提交
1709

1710
    // step 4: construct result
1711
    status = request_handler_.Insert(context_ptr_, collection_name->std_str(), vectors, tag);
1712 1713 1714 1715 1716 1717 1718 1719 1720 1721
    if (status.ok()) {
        ids_dto->ids = ids_dto->ids->createShared();
        for (auto& id : vectors.id_array_) {
            ids_dto->ids->pushBack(std::to_string(id).c_str());
        }
    }

    ASSIGN_RETURN_STATUS_DTO(status)
}

1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788
StatusDto::ObjectWrapper
WebRequestHandler::InsertEntity(const OString& collection_name, const milvus::server::web::OString& body,
                                VectorIdsDto::ObjectWrapper& ids_dto) {
    if (nullptr == body.get() || body->getSize() == 0) {
        RETURN_STATUS_DTO(BODY_FIELD_LOSS, "Request payload is required.")
    }

    auto body_json = nlohmann::json::parse(body->c_str());
    std::string partition_tag = body_json["partition_tag"];

    uint64_t row_num = body_json["row_num"];

    std::unordered_map<std::string, engine::meta::hybrid::DataType> field_types;
    auto status = request_handler_.DescribeHybridCollection(context_ptr_, collection_name->c_str(), field_types);

    auto entities = body_json["entity"];
    if (!entities.is_array()) {
        RETURN_STATUS_DTO(ILLEGAL_BODY, "An entity must be an array");
    }

    std::vector<std::string> field_names;
    std::vector<std::vector<uint8_t>> attr_values;
    size_t attr_size = 0;
    std::unordered_map<std::string, engine::VectorsData> vector_datas;
    for (auto& entity : entities) {
        std::string field_name = entity["field_name"];
        field_names.emplace_back(field_name);
        auto field_value = entity["field_value"];
        std::vector<uint8_t> attr_value;
        switch (field_types.at(field_name)) {
            case engine::meta::hybrid::DataType::INT8:
            case engine::meta::hybrid::DataType::INT16:
            case engine::meta::hybrid::DataType::INT32:
            case engine::meta::hybrid::DataType::INT64: {
                std::vector<int64_t> value;
                auto size = field_value.size();
                value.resize(size);
                attr_value.resize(size * sizeof(int64_t));
                size_t offset = 0;
                for (auto data : field_value) {
                    value[offset] = data.get<int64_t>();
                    ++offset;
                }
                memcpy(attr_value.data(), value.data(), size * sizeof(int64_t));
                attr_size += size * sizeof(int64_t);
                attr_values.emplace_back(attr_value);
                break;
            }
            case engine::meta::hybrid::DataType::FLOAT:
            case engine::meta::hybrid::DataType::DOUBLE: {
                std::vector<double> value;
                auto size = field_value.size();
                value.resize(size);
                attr_value.resize(size * sizeof(double));
                size_t offset = 0;
                for (auto data : field_value) {
                    value[offset] = data.get<double>();
                    ++offset;
                }
                memcpy(attr_value.data(), value.data(), size * sizeof(double));
                attr_size += size * sizeof(double);

                attr_values.emplace_back(attr_value);
                break;
            }
            case engine::meta::hybrid::DataType::VECTOR: {
                bool bin_flag;
B
BossZou 已提交
1789
                status = IsBinaryCollection(collection_name->c_str(), bin_flag);
1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821
                if (!status.ok()) {
                    ASSIGN_RETURN_STATUS_DTO(status)
                }

                engine::VectorsData vectors;
                CopyRecordsFromJson(field_value, vectors, bin_flag);
                vector_datas.insert(std::make_pair(field_name, vectors));
            }
            default: {}
        }
    }

    std::vector<uint8_t> attrs(attr_size, 0);
    size_t attr_offset = 0;
    for (auto& data : attr_values) {
        memcpy(attrs.data() + attr_offset, data.data(), data.size());
        attr_offset += data.size();
    }

    status = request_handler_.InsertEntity(context_ptr_, collection_name->c_str(), partition_tag, row_num, field_names,
                                           attrs, vector_datas);

    if (status.ok()) {
        ids_dto->ids = ids_dto->ids->createShared();
        for (auto& id : vector_datas.begin()->second.id_array_) {
            ids_dto->ids->pushBack(std::to_string(id).c_str());
        }
    }

    ASSIGN_RETURN_STATUS_DTO(status)
}

Y
yukun 已提交
1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859
StatusDto::ObjectWrapper
WebRequestHandler::GetEntity(const milvus::server::web::OString& collection_name,
                             const milvus::server::web::OQueryParams& query_params,
                             milvus::server::web::OString& response) {
    auto status = Status::OK();
    try {
        auto query_ids = query_params.get("ids");
        if (query_ids == nullptr || query_ids.get() == nullptr) {
            RETURN_STATUS_DTO(QUERY_PARAM_LOSS, "Query param ids is required.");
        }

        std::vector<std::string> ids;
        StringHelpFunctions::SplitStringByDelimeter(query_ids->c_str(), ",", ids);
        std::vector<int64_t> entity_ids;
        for (auto& id : ids) {
            entity_ids.push_back(std::stol(id));
        }
        nlohmann::json entity_result_json;
        status = GetEntityByIDs(collection_name->std_str(), entity_ids, entity_result_json);
        if (!status.ok()) {
            response = "NULL";
            ASSIGN_RETURN_STATUS_DTO(status)
        }

        nlohmann::json json;
        AddStatusToJson(json, status.code(), status.message());
        if (entity_result_json.empty()) {
            json["entities"] = std::vector<int64_t>();
        } else {
            json["entities"] = entity_result_json;
        }
    } catch (std::exception& e) {
        RETURN_STATUS_DTO(SERVER_UNEXPECTED_ERROR, e.what());
    }

    ASSIGN_RETURN_STATUS_DTO(status);
}

1860
StatusDto::ObjectWrapper
1861
WebRequestHandler::GetVector(const OString& collection_name, const OQueryParams& query_params, OString& response) {
B
BossZou 已提交
1862 1863
    auto status = Status::OK();
    try {
1864 1865 1866
        auto query_ids = query_params.get("ids");
        if (query_ids == nullptr || query_ids.get() == nullptr) {
            RETURN_STATUS_DTO(QUERY_PARAM_LOSS, "Query param ids is required.");
B
BossZou 已提交
1867
        }
1868

1869 1870 1871
        std::vector<std::string> ids;
        StringHelpFunctions::SplitStringByDelimeter(query_ids->c_str(), ",", ids);

B
BossZou 已提交
1872 1873
        std::vector<int64_t> vector_ids;
        for (auto& id : ids) {
1874
            vector_ids.push_back(std::stol(id));
B
BossZou 已提交
1875 1876 1877 1878 1879 1880 1881 1882
        }
        engine::VectorsData vectors;
        nlohmann::json vectors_json;
        status = GetVectorsByIDs(collection_name->std_str(), vector_ids, vectors_json);
        if (!status.ok()) {
            response = "NULL";
            ASSIGN_RETURN_STATUS_DTO(status)
        }
B
BossZou 已提交
1883

B
BossZou 已提交
1884 1885 1886 1887 1888 1889 1890 1891 1892 1893
        nlohmann::json json;
        AddStatusToJson(json, status.code(), status.message());
        if (vectors_json.empty()) {
            json["vectors"] = std::vector<int64_t>();
        } else {
            json["vectors"] = vectors_json;
        }
        response = json.dump().c_str();
    } catch (std::exception& e) {
        RETURN_STATUS_DTO(SERVER_UNEXPECTED_ERROR, e.what());
B
BossZou 已提交
1894 1895
    }

B
BossZou 已提交
1896
    ASSIGN_RETURN_STATUS_DTO(status);
1897 1898 1899
}

StatusDto::ObjectWrapper
1900
WebRequestHandler::VectorsOp(const OString& collection_name, const OString& payload, OString& response) {
1901 1902 1903 1904 1905 1906 1907
    auto status = Status::OK();
    std::string result_str;

    try {
        nlohmann::json payload_json = nlohmann::json::parse(payload->std_str());

        if (payload_json.contains("delete")) {
1908
            status = DeleteByIDs(collection_name->std_str(), payload_json["delete"], result_str);
1909
        } else if (payload_json.contains("search")) {
1910
            status = Search(collection_name->std_str(), payload_json["search"], result_str);
1911
        } else if (payload_json.contains("query")) {
Y
yukun 已提交
1912
            status = HybridSearch(collection_name->c_str(), payload_json, result_str);
1913 1914
        } else {
            status = Status(ILLEGAL_BODY, "Unknown body");
B
BossZou 已提交
1915
        }
1916 1917 1918 1919 1920 1921 1922 1923 1924 1925
    } catch (nlohmann::detail::parse_error& e) {
        std::string emsg = "json error: code=" + std::to_string(e.id) + ", reason=" + e.what();
        RETURN_STATUS_DTO(BODY_PARSE_FAIL, emsg.c_str());
    } catch (nlohmann::detail::type_error& e) {
        std::string emsg = "json error: code=" + std::to_string(e.id) + ", reason=" + e.what();
        RETURN_STATUS_DTO(BODY_PARSE_FAIL, emsg.c_str());
    } catch (std::exception& e) {
        RETURN_STATUS_DTO(SERVER_UNEXPECTED_ERROR, e.what());
    }

1926
    response = status.ok() ? result_str.c_str() : "NULL";
B
BossZou 已提交
1927 1928 1929 1930

    ASSIGN_RETURN_STATUS_DTO(status)
}

1931 1932 1933 1934
/**********
 *
 * System {
 */
B
BossZou 已提交
1935
StatusDto::ObjectWrapper
1936
WebRequestHandler::SystemInfo(const OString& cmd, const OQueryParams& query_params, OString& response_str) {
1937
    std::string info = cmd->std_str();
1938

1939 1940
    auto status = Status::OK();
    std::string result_str;
1941

1942 1943 1944 1945 1946 1947
    try {
        if (info == "config") {
            status = GetConfig(result_str);
        } else {
            if ("info" == info) {
                info = "get_system_info";
1948
            }
1949
            status = Cmd(info, result_str);
1950
        }
1951 1952
    } catch (nlohmann::detail::parse_error& e) {
        std::string emsg = "json error: code=" + std::to_string(e.id) + ", reason=" + e.what();
1953
        RETURN_STATUS_DTO(BODY_PARSE_FAIL, emsg.c_str());
1954 1955
    } catch (nlohmann::detail::type_error& e) {
        std::string emsg = "json error: code=" + std::to_string(e.id) + ", reason=" + e.what();
1956
        RETURN_STATUS_DTO(BODY_PARSE_FAIL, emsg.c_str());
1957
    }
1958

1959
    response_str = status.ok() ? result_str.c_str() : "NULL";
1960

1961 1962
    ASSIGN_RETURN_STATUS_DTO(status);
}
B
BossZou 已提交
1963

1964 1965 1966 1967 1968
StatusDto::ObjectWrapper
WebRequestHandler::SystemOp(const OString& op, const OString& body_str, OString& response_str) {
    if (nullptr == body_str.get() || body_str->getSize() == 0) {
        RETURN_STATUS_DTO(BODY_FIELD_LOSS, "Payload is empty.");
    }
1969 1970 1971

    Status status = Status::OK();
    std::string result_str;
1972
    try {
B
BossZou 已提交
1973 1974 1975
        fiu_do_on("WebRequestHandler.SystemOp.raise_parse_error",
                  throw nlohmann::detail::parse_error::create(0, 0, ""));
        fiu_do_on("WebRequestHandler.SystemOp.raise_type_error", throw nlohmann::detail::type_error::create(0, ""));
1976 1977 1978
        nlohmann::json j = nlohmann::json::parse(body_str->c_str());
        if (op->equals("task")) {
            if (j.contains("load")) {
B
BossZou 已提交
1979
                status = PreLoadCollection(j["load"], result_str);
1980 1981
            } else if (j.contains("flush")) {
                status = Flush(j["flush"], result_str);
1982 1983
            }
            if (j.contains("compact")) {
1984
                status = Compact(j["compact"], result_str);
1985 1986
            }
        } else if (op->equals("config")) {
1987
            status = SetConfig(j, result_str);
1988 1989
        } else {
            status = Status(UNKNOWN_PATH, "Unknown path: /system/" + op->std_str());
1990 1991 1992
        }
    } catch (nlohmann::detail::parse_error& e) {
        std::string emsg = "json error: code=" + std::to_string(e.id) + ", reason=" + e.what();
1993
        RETURN_STATUS_DTO(BODY_PARSE_FAIL, emsg.c_str());
1994 1995
    } catch (nlohmann::detail::type_error& e) {
        std::string emsg = "json error: code=" + std::to_string(e.id) + ", reason=" + e.what();
1996
        RETURN_STATUS_DTO(BODY_PARSE_FAIL, emsg.c_str());
1997 1998
    }

1999
    response_str = status.ok() ? result_str.c_str() : "NULL";
B
BossZou 已提交
2000 2001 2002 2003 2004 2005 2006

    ASSIGN_RETURN_STATUS_DTO(status);
}

}  // namespace web
}  // namespace server
}  // namespace milvus