WebRequestHandler.cpp 76.5 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;
    }
}

G
groot 已提交
81 82
using FloatJson = nlohmann::basic_json<std::map, std::vector, std::string, bool, std::int64_t, std::uint64_t, float>;

83 84 85 86 87 88 89 90
/////////////////////////////////// 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 已提交
91
WebRequestHandler::IsBinaryCollection(const std::string& collection_name, bool& bin) {
J
Jin Hai 已提交
92
    CollectionSchema schema;
93
    auto status = request_handler_.DescribeCollection(context_ptr_, collection_name, schema);
94 95 96
    if (status.ok()) {
        auto metric = engine::MetricType(schema.metric_type_);
        bin = engine::MetricType::HAMMING == metric || engine::MetricType::JACCARD == metric ||
97 98
              engine::MetricType::TANIMOTO == metric || engine::MetricType::SUPERSTRUCTURE == metric ||
              engine::MetricType::SUBSTRUCTURE == metric;
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 133 134
    }

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

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

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

J
Jin Hai 已提交
156
    json_out["collection_name"] = schema.collection_name_;
157 158 159
    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_));
160
    json_out["index_params"] = index_param.extra_params_;
161 162 163 164 165 166 167
    json_out["metric_type"] = MetricMap.at(engine::MetricType(schema.metric_type_));
    json_out["count"] = count;

    return Status::OK();
}

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

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

    return status;
}

Status
185 186
WebRequestHandler::GetSegmentVectors(const std::string& collection_name, const std::string& segment_name,
                                     int64_t page_size, int64_t offset, nlohmann::json& json_out) {
187
    std::vector<int64_t> vector_ids;
188
    auto status = request_handler_.GetVectorIDs(context_ptr_, collection_name, segment_name, vector_ids);
189 190 191 192 193 194 195 196 197
    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;
198
    status = GetVectorsByIDs(collection_name, ids, vectors_json);
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213

    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
214
WebRequestHandler::GetSegmentIds(const std::string& collection_name, const std::string& segment_name, int64_t page_size,
215 216
                                 int64_t offset, nlohmann::json& json_out) {
    std::vector<int64_t> vector_ids;
217
    auto status = request_handler_.GetVectorIDs(context_ptr_, collection_name, segment_name, vector_ids);
218 219 220 221 222 223 224 225 226 227 228 229 230 231 232
    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;
233
}
B
BossZou 已提交
234

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

240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
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 已提交
256
WebRequestHandler::PreLoadCollection(const nlohmann::json& json, std::string& result_str) {
257 258
    if (!json.contains("collection_name")) {
        return Status(BODY_FIELD_LOSS, "Field \"load\" must contains collection_name");
259 260
    }

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

269 270 271 272 273
    return status;
}

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

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

    std::vector<std::string> names;
284
    for (auto& name : collection_names) {
285 286 287 288 289 290 291 292 293 294 295 296 297 298 299
        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) {
300 301
    if (!json.contains("collection_name")) {
        return Status(BODY_FIELD_LOSS, "Field \"compact\" must contains collection_names");
302 303
    }

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

309
    auto name = collection_name.get<std::string>();
310

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

    if (status.ok()) {
        nlohmann::json result;
316
        AddStatusToJson(result, status.code(), status.message());
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 395 396
        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;";
    }

397 398 399
    nlohmann::json result;
    AddStatusToJson(result, StatusCode::SUCCESS, msg);

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

    result_str = result.dump();

    return Status::OK();
}

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

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

421 422 423 424 425 426 427 428 429 430 431 432
    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 已提交
433 434 435 436 437 438
    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");
439
        }
B
BossZou 已提交
440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457

        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>());
            }
458 459
        }

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

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

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

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

    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 已提交
493
    for (int64_t i = 0; i < result.row_num_; i++) {
494 495 496 497 498 499 500 501 502 503 504 505 506 507 508
        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();
}

509 510 511 512 513 514 515 516 517 518 519 520
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};
        }

521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 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 617 618 619 620 621 622 623
        //        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;
        //            }
        //            default:
        //                break;
        //        }
        //
        //        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"];
        //
        //        // 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;
        //        query->AddLeafQuery(leaf_query);
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 688 689
    }
    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 已提交
690
void
691
ConvertRowToColumnJson(const std::vector<engine::AttrsData>& row_attrs, const std::vector<std::string>& field_names,
Y
yukun 已提交
692
                       const int64_t row_num, nlohmann::json& column_attrs_json) {
693 694 695 696 697 698 699 700
    //    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);
    //            }
    //        }
    //    }
Y
yukun 已提交
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 791 792

    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;
            }
        }
    }
}

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

798 799
    milvus::server::HybridCollectionSchema collection_schema;
    status = request_handler_.DescribeHybridCollection(context_ptr_, collection_name, collection_schema);
800 801 802
    if (!status.ok()) {
        return Status{UNEXPECTED_ERROR, "DescribeHybridCollection failed"};
    }
803
    field_type_ = collection_schema.field_types_;
804

Y
yukun 已提交
805 806 807 808 809 810 811 812
    milvus::json extra_params;
    if (json.contains("fields")) {
        if (json["fields"].is_array()) {
            extra_params["fields"] = json["fields"];
        }
    }
    auto query_json = json["query"];

813
    std::vector<std::string> partition_tags;
Y
yukun 已提交
814 815
    if (query_json.contains("partition_tags")) {
        auto tags = query_json["partition_tags"];
816 817 818 819 820 821 822 823 824
        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 已提交
825 826
    if (query_json.contains("bool")) {
        auto boolean_query_json = query_json["bool"];
Y
yukun 已提交
827 828
        auto boolean_query = std::make_shared<query::BooleanQuery>();
        query_ptr_ = std::make_shared<query::Query>();
829 830 831 832 833

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

Y
yukun 已提交
837 838
        query_ptr_->root = general_query->bin;

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

        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 已提交
856
        auto step = result.result_ids_.size() / result.row_num_;
857
        nlohmann::json search_result_json;
C
Cai Yudong 已提交
858
        for (int64_t i = 0; i < result.row_num_; i++) {
859 860 861
            nlohmann::json raw_result_json;
            for (size_t j = 0; j < step; j++) {
                nlohmann::json one_result_json;
Y
yukun 已提交
862 863
                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));
864 865 866 867
                raw_result_json.emplace_back(one_result_json);
            }
            search_result_json.emplace_back(raw_result_json);
        }
Y
yukun 已提交
868 869 870
        nlohmann::json attr_json;
        ConvertRowToColumnJson(result.attrs_, field_names, result.row_num_, attr_json);
        result_json["Entity"] = attr_json;
871 872 873 874 875 876 877
        result_json["result"] = search_result_json;
        result_str = result_json.dump();
    }

    return Status::OK();
}

878
Status
879 880
WebRequestHandler::DeleteByIDs(const std::string& collection_name, const nlohmann::json& json,
                               std::string& result_str) {
881 882 883 884 885 886 887 888 889 890
    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) {
891
        auto id_str = id.get<std::string>();
C
Cai Yudong 已提交
892
        if (!ValidateStringIsNumber(id_str).ok()) {
893 894 895
            return Status(ILLEGAL_BODY, "Members in \"ids\" must be integer string");
        }
        vector_ids.emplace_back(std::stol(id_str));
896 897
    }

898
    auto status = request_handler_.DeleteByID(context_ptr_, collection_name, vector_ids);
899 900 901 902

    nlohmann::json result_json;
    AddStatusToJson(result_json, status.code(), status.message());
    result_str = result_json.dump();
903 904 905 906

    return status;
}

Y
yukun 已提交
907 908
Status
WebRequestHandler::GetEntityByIDs(const std::string& collection_name, const std::vector<int64_t>& ids,
909
                                  std::vector<std::string>& field_names, nlohmann::json& json_out) {
Y
yukun 已提交
910 911
    std::vector<engine::VectorsData> vector_batch;
    std::vector<engine::AttrsData> attr_batch;
912 913
    auto status =
        request_handler_.GetEntityByID(context_ptr_, collection_name, field_names, ids, attr_batch, vector_batch);
Y
yukun 已提交
914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939
    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);
    }
    ConvertRowToColumnJson(attr_batch, field_names, -1, attrs_json);
    json_out["vectors"] = vectors_json;
    json_out["attributes"] = attrs_json;
}

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

    bool bin;
B
BossZou 已提交
950
    status = IsBinaryCollection(collection_name, bin);
951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970
    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 已提交
971 972 973 974 975
StatusDto::ObjectWrapper
WebRequestHandler::GetDevices(DevicesDto::ObjectWrapper& devices_dto) {
    auto system_info = SystemInfo::GetInstance();

    devices_dto->cpu = devices_dto->cpu->createShared();
976
    devices_dto->cpu->memory = system_info.GetPhysicalMemory() >> 30;
B
BossZou 已提交
977 978 979 980 981

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

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

    if (count != device_mems.size()) {
985
        RETURN_STATUS_DTO(UNEXPECTED_ERROR, "Can't obtain GPU info");
B
BossZou 已提交
986 987 988 989
    }

    for (size_t i = 0; i < count; i++) {
        auto device_dto = DeviceInfoDto::createShared();
990
        device_dto->memory = device_mems.at(i) >> 30;
B
BossZou 已提交
991 992 993 994 995 996 997 998 999
        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) {
1000 1001
    std::string reply;
    std::string cache_cmd_prefix = "get_config " + std::string(CONFIG_CACHE) + ".";
B
BossZou 已提交
1002

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

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

1017 1018 1019
    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 已提交
1020 1021 1022
    if (!status.ok()) {
        ASSIGN_RETURN_STATUS_DTO(status)
    }
1023
    advanced_config->use_blas_threshold = std::stol(reply);
B
BossZou 已提交
1024 1025

#ifdef MILVUS_GPU_VERSION
W
Wang XiangYu 已提交
1026
    engine_cmd_string = engine_cmd_prefix + std::string(CONFIG_GPU_RESOURCE_GPU_SEARCH_THRESHOLD);
1027
    CommandLine(engine_cmd_string, reply);
B
BossZou 已提交
1028 1029 1030
    if (!status.ok()) {
        ASSIGN_RETURN_STATUS_DTO(status)
    }
1031
    advanced_config->gpu_search_threshold = std::stol(reply);
B
BossZou 已提交
1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054
#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.");
    }
1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078
#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 已提交
1079 1080 1081 1082
    if (!status.ok()) {
        ASSIGN_RETURN_STATUS_DTO(status)
    }

1083
#ifdef MILVUS_GPU_VERSION
W
Wang XiangYu 已提交
1084 1085 1086 1087
    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);
1088 1089 1090
    if (!status.ok()) {
        ASSIGN_RETURN_STATUS_DTO(status)
    }
B
BossZou 已提交
1091 1092 1093 1094 1095 1096 1097 1098
#endif

    ASSIGN_RETURN_STATUS_DTO(status)
}

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

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

1109
    if (!gpu_config_dto->enable->getValue()) {
B
BossZou 已提交
1110 1111 1112
        ASSIGN_RETURN_STATUS_DTO(Status::OK());
    }

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

1120 1121
    gpu_cmd_request = gpu_cmd_prefix + std::string(CONFIG_GPU_RESOURCE_SEARCH_RESOURCES);
    status = CommandLine(gpu_cmd_request, reply);
B
BossZou 已提交
1122 1123 1124 1125
    if (!status.ok()) {
        ASSIGN_RETURN_STATUS_DTO(status);
    }

1126 1127 1128
    std::vector<std::string> gpu_entry;
    StringHelpFunctions::SplitStringByDelimeter(reply, ",", gpu_entry);

B
BossZou 已提交
1129
    gpu_config_dto->search_resources = gpu_config_dto->search_resources->createShared();
1130 1131
    for (auto& device_id : gpu_entry) {
        gpu_config_dto->search_resources->pushBack(OString(device_id.c_str())->toUpperCase());
B
BossZou 已提交
1132
    }
1133
    gpu_entry.clear();
B
BossZou 已提交
1134

1135 1136
    gpu_cmd_request = gpu_cmd_prefix + std::string(CONFIG_GPU_RESOURCE_BUILD_INDEX_RESOURCES);
    status = CommandLine(gpu_cmd_request, reply);
B
BossZou 已提交
1137 1138 1139 1140
    if (!status.ok()) {
        ASSIGN_RETURN_STATUS_DTO(status);
    }

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

    ASSIGN_RETURN_STATUS_DTO(Status::OK());
}

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

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

1161 1162 1163
    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 已提交
1164 1165
    }

1166 1167 1168
    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 已提交
1169
    }
1170 1171 1172 1173 1174 1175 1176

    // 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 已提交
1177 1178 1179 1180
    if (!status.ok()) {
        ASSIGN_RETURN_STATUS_DTO(status);
    }

1181 1182 1183 1184 1185 1186 1187 1188 1189
    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 已提交
1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203
    }

    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);
    }
1204 1205 1206

    gpu_cmd_request = gpu_cmd_prefix + std::string(CONFIG_GPU_RESOURCE_SEARCH_RESOURCES) + " " + search_resources_value;
    status = CommandLine(gpu_cmd_request, reply);
B
BossZou 已提交
1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223
    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);
    }

1224 1225 1226
    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 已提交
1227 1228 1229 1230 1231 1232 1233 1234
    if (!status.ok()) {
        ASSIGN_RETURN_STATUS_DTO(status);
    }

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

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

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

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

1253
    if (nullptr == collection_schema->metric_type.get()) {
B
BossZou 已提交
1254 1255 1256
        RETURN_STATUS_DTO(BODY_FIELD_LOSS, "Field \'metric_type\' is missing")
    }

1257
    if (MetricNameMap.find(collection_schema->metric_type->std_str()) == MetricNameMap.end()) {
B
BossZou 已提交
1258 1259 1260
        RETURN_STATUS_DTO(ILLEGAL_METRIC_TYPE, "metric_type is illegal")
    }

1261 1262 1263 1264
    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 已提交
1265 1266 1267 1268

    ASSIGN_RETURN_STATUS_DTO(status)
}

1269 1270 1271 1272 1273 1274
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
1275 1276 1277
    std::unordered_map<std::string, engine::meta::hybrid::DataType> field_types;
    std::unordered_map<std::string, milvus::json> field_index_params;
    std::unordered_map<std::string, std::string> field_extra_params;
1278 1279 1280 1281 1282
    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") {
1283
            field_types.insert(std::make_pair(field_name, engine::meta::hybrid::DataType::INT8));
1284
        } else if (field_type == "int16") {
1285
            field_types.insert(std::make_pair(field_name, engine::meta::hybrid::DataType::INT16));
1286
        } else if (field_type == "int32") {
1287
            field_types.insert(std::make_pair(field_name, engine::meta::hybrid::DataType::INT32));
1288
        } else if (field_type == "int64") {
1289
            field_types.insert(std::make_pair(field_name, engine::meta::hybrid::DataType::INT64));
1290
        } else if (field_type == "float") {
1291
            field_types.insert(std::make_pair(field_name, engine::meta::hybrid::DataType::FLOAT));
1292
        } else if (field_type == "double") {
1293
            field_types.insert(std::make_pair(field_name, engine::meta::hybrid::DataType::DOUBLE));
1294 1295 1296 1297 1298 1299
        } else if (field_type == "vector") {
        } else {
            std::string msg = field_name + " has wrong field_type";
            RETURN_STATUS_DTO(BODY_PARSE_FAIL, msg.c_str());
        }

1300
        field_extra_params.insert(std::make_pair(field_name, extra_params.dump()));
1301 1302
    }

1303 1304 1305 1306
    milvus::json json_params;

    auto status = request_handler_.CreateHybridCollection(context_ptr_, collection_name, field_types,
                                                          field_index_params, field_extra_params, json_params);
1307 1308 1309 1310

    ASSIGN_RETURN_STATUS_DTO(status)
}

B
BossZou 已提交
1311
StatusDto::ObjectWrapper
B
BossZou 已提交
1312
WebRequestHandler::ShowCollections(const OQueryParams& query_params, OString& result) {
1313 1314 1315 1316
    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 已提交
1317 1318
    }

1319 1320 1321 1322
    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());
1323 1324
    }

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

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

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

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

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

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

1367 1368
    result = result_json.dump().c_str();

B
BossZou 已提交
1369 1370 1371
    ASSIGN_RETURN_STATUS_DTO(status)
}

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

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

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

    ASSIGN_RETURN_STATUS_DTO(status);
}

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

    ASSIGN_RETURN_STATUS_DTO(status)
}

1404 1405 1406 1407 1408
/***********
 *
 * Index {
 */

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

1418 1419 1420 1421 1422 1423 1424 1425
        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")
        }
1426 1427 1428 1429 1430

        auto status = Status::OK();
        //        auto status =
        //            request_handler_.CreateIndex(context_ptr_, collection_name->std_str(), index,
        //            request_json["params"]);
1431 1432
        ASSIGN_RETURN_STATUS_DTO(status);
    } catch (nlohmann::detail::parse_error& e) {
Y
Yhz 已提交
1433
        RETURN_STATUS_DTO(BODY_PARSE_FAIL, e.what())
1434
    } catch (nlohmann::detail::type_error& e) {
Y
Yhz 已提交
1435
        RETURN_STATUS_DTO(BODY_PARSE_FAIL, e.what())
B
BossZou 已提交
1436 1437
    }

1438
    ASSIGN_RETURN_STATUS_DTO(Status::OK())
B
BossZou 已提交
1439 1440 1441
}

StatusDto::ObjectWrapper
1442
WebRequestHandler::GetIndex(const OString& collection_name, OString& result) {
B
BossZou 已提交
1443
    IndexParam param;
1444
    auto status = request_handler_.DescribeIndex(context_ptr_, collection_name->std_str(), param);
B
BossZou 已提交
1445 1446

    if (status.ok()) {
1447 1448 1449 1450 1451
        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 已提交
1452 1453 1454 1455 1456 1457
    }

    ASSIGN_RETURN_STATUS_DTO(status)
}

StatusDto::ObjectWrapper
1458
WebRequestHandler::DropIndex(const OString& collection_name) {
1459 1460
    auto status = Status::OK();
    //    auto status = request_handler_.DropIndex(context_ptr_, collection_name->std_str());
B
BossZou 已提交
1461 1462 1463 1464 1465

    ASSIGN_RETURN_STATUS_DTO(status)
}

StatusDto::ObjectWrapper
1466
WebRequestHandler::CreatePartition(const OString& collection_name, const PartitionRequestDto::ObjectWrapper& param) {
B
BossZou 已提交
1467 1468 1469 1470
    if (nullptr == param->partition_tag.get()) {
        RETURN_STATUS_DTO(BODY_FIELD_LOSS, "Field \'partition_tag\' is required")
    }

1471
    auto status =
1472
        request_handler_.CreatePartition(context_ptr_, collection_name->std_str(), param->partition_tag->std_str());
B
BossZou 已提交
1473 1474 1475 1476 1477

    ASSIGN_RETURN_STATUS_DTO(status)
}

StatusDto::ObjectWrapper
B
BossZou 已提交
1478
WebRequestHandler::ShowPartitions(const OString& collection_name, const OQueryParams& query_params,
B
BossZou 已提交
1479
                                  PartitionListDto::ObjectWrapper& partition_list_dto) {
1480 1481 1482 1483
    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 已提交
1484 1485
    }

1486 1487 1488 1489
    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());
1490 1491
    }

1492
    if (offset < 0 || page_size < 0) {
1493 1494
        ASSIGN_RETURN_STATUS_DTO(
            Status(SERVER_UNEXPECTED_ERROR, "Query param 'offset' or 'page_size' should equal or bigger than 0"));
B
BossZou 已提交
1495 1496
    }

1497 1498 1499 1500
    bool all_required = false;
    auto required = query_params.get("all_required");
    if (nullptr != required.get()) {
        auto required_str = required->std_str();
C
Cai Yudong 已提交
1501
        if (!ValidateStringIsBool(required_str).ok()) {
1502 1503 1504 1505 1506
            RETURN_STATUS_DTO(ILLEGAL_QUERY_PARAM, "Query param \'all_required\' must be a bool")
        }
        all_required = required_str == "True" || required_str == "true";
    }

B
BossZou 已提交
1507
    std::vector<PartitionParam> partitions;
1508
    status = request_handler_.ShowPartitions(context_ptr_, collection_name->std_str(), partitions);
1509 1510 1511
    if (!status.ok()) {
        ASSIGN_RETURN_STATUS_DTO(status)
    }
B
BossZou 已提交
1512

1513
    if (all_required) {
1514 1515
        offset = 0;
        page_size = partitions.size();
1516
    } else {
1517 1518
        offset = std::min((size_t)offset, partitions.size());
        page_size = std::min(partitions.size() - offset, (size_t)page_size);
1519 1520
    }

1521
    partition_list_dto->count = partitions.size();
1522 1523
    partition_list_dto->partitions = partition_list_dto->partitions->createShared();

C
Cai Yudong 已提交
1524
    if (offset < (int64_t)(partitions.size())) {
1525
        for (int64_t i = offset; i < page_size + offset; i++) {
1526 1527 1528
            auto partition_dto = PartitionFieldsDto::createShared();
            partition_dto->partition_tag = partitions.at(i).tag_.c_str();
            partition_list_dto->partitions->pushBack(partition_dto);
B
BossZou 已提交
1529 1530 1531 1532 1533 1534 1535
        }
    }

    ASSIGN_RETURN_STATUS_DTO(status)
}

StatusDto::ObjectWrapper
1536
WebRequestHandler::DropPartition(const OString& collection_name, const OString& body) {
1537 1538 1539 1540 1541 1542 1543 1544 1545
    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())
    }
1546
    auto status = request_handler_.DropPartition(context_ptr_, collection_name->std_str(), tag);
B
BossZou 已提交
1547 1548 1549 1550

    ASSIGN_RETURN_STATUS_DTO(status)
}

1551 1552 1553 1554
/***********
 *
 * Segment {
 */
B
BossZou 已提交
1555
StatusDto::ObjectWrapper
1556
WebRequestHandler::ShowSegments(const OString& collection_name, const OQueryParams& query_params, OString& response) {
1557 1558 1559 1560
    int64_t offset = 0;
    auto status = ParseQueryInteger(query_params, "offset", offset);
    if (!status.ok()) {
        RETURN_STATUS_DTO(status.code(), status.message().c_str());
1561 1562
    }

1563 1564 1565 1566
    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());
1567 1568
    }

1569
    if (offset < 0 || page_size < 0) {
1570 1571 1572
        RETURN_STATUS_DTO(ILLEGAL_QUERY_PARAM, "Query param 'offset' or 'page_size' should equal or bigger than 0");
    }

1573 1574 1575 1576
    bool all_required = false;
    auto required = query_params.get("all_required");
    if (nullptr != required.get()) {
        auto required_str = required->std_str();
C
Cai Yudong 已提交
1577
        if (!ValidateStringIsBool(required_str).ok()) {
1578 1579 1580 1581 1582
            RETURN_STATUS_DTO(ILLEGAL_QUERY_PARAM, "Query param \'all_required\' must be a bool")
        }
        all_required = required_str == "True" || required_str == "true";
    }

1583 1584 1585 1586 1587
    std::string tag;
    if (nullptr != query_params.get("partition_tag").get()) {
        tag = query_params.get("partition_tag")->std_str();
    }

1588
    std::string info;
1589
    status = request_handler_.ShowCollectionInfo(context_ptr_, collection_name->std_str(), info);
1590 1591 1592 1593
    if (!status.ok()) {
        ASSIGN_RETURN_STATUS_DTO(status)
    }

1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622
    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();
1623 1624 1625
    AddStatusToJson(result_json, status.code(), status.message());
    response = result_json.dump().c_str();

B
BossZou 已提交
1626 1627 1628 1629
    ASSIGN_RETURN_STATUS_DTO(status)
}

StatusDto::ObjectWrapper
1630
WebRequestHandler::GetSegmentInfo(const OString& collection_name, const OString& segment_name, const OString& info,
1631
                                  const OQueryParams& query_params, OString& result) {
1632 1633 1634 1635
    int64_t offset = 0;
    auto status = ParseQueryInteger(query_params, "offset", offset);
    if (!status.ok()) {
        RETURN_STATUS_DTO(status.code(), status.message().c_str());
1636 1637
    }

1638 1639 1640 1641
    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 已提交
1642 1643
    }

1644
    if (offset < 0 || page_size < 0) {
1645 1646 1647 1648 1649
        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();
1650
    status = Status::OK();
1651 1652 1653
    nlohmann::json json;
    // Get vectors
    if (re == "vectors") {
1654
        status = GetSegmentVectors(collection_name->std_str(), segment_name->std_str(), page_size, offset, json);
1655 1656
        // Get vector ids
    } else if (re == "ids") {
1657
        status = GetSegmentIds(collection_name->std_str(), segment_name->std_str(), page_size, offset, json);
B
BossZou 已提交
1658 1659
    }

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

1662 1663 1664 1665 1666 1667 1668 1669
    ASSIGN_RETURN_STATUS_DTO(status)
}

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

1675 1676
    // step 1: copy vectors
    bool bin_flag;
B
BossZou 已提交
1677
    auto status = IsBinaryCollection(collection_name->std_str(), bin_flag);
1678 1679
    if (!status.ok()) {
        ASSIGN_RETURN_STATUS_DTO(status)
B
BossZou 已提交
1680 1681
    }

1682 1683 1684 1685
    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 已提交
1686
    engine::VectorsData vectors;
1687 1688 1689 1690
    CopyRecordsFromJson(body_json["vectors"], vectors, bin_flag);
    if (!status.ok()) {
        ASSIGN_RETURN_STATUS_DTO(status)
    }
1691

1692 1693 1694 1695 1696
    // 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");
1697
        }
1698 1699
        auto& id_array = vectors.id_array_;
        id_array.clear();
1700 1701 1702 1703 1704 1705 1706 1707
        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());
1708
        }
G
groot 已提交
1709
    }
B
BossZou 已提交
1710

1711 1712 1713 1714
    // step 3: copy partition tag
    std::string tag;
    if (body_json.contains("partition_tag")) {
        tag = body_json["partition_tag"];
1715
    }
B
BossZou 已提交
1716

1717
    // step 4: construct result
1718
    status = request_handler_.Insert(context_ptr_, collection_name->std_str(), vectors, tag);
1719 1720 1721 1722 1723 1724 1725 1726 1727 1728
    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)
}

1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741
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;
1742 1743
    auto status = Status::OK();
    //    auto status = request_handler_.DescribeHybridCollection(context_ptr_, collection_name->c_str(), field_types);
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 1789 1790 1791 1792 1793 1794

    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;
            }
1795
            case engine::meta::hybrid::DataType::VECTOR_FLOAT: {
1796
                bool bin_flag;
B
BossZou 已提交
1797
                status = IsBinaryCollection(collection_name->c_str(), bin_flag);
1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829
                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 已提交
1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846
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));
        }
1847 1848 1849 1850 1851 1852 1853

        std::vector<std::string> field_names;
        auto query_fields = query_params.get("fields");
        if (query_fields != nullptr && query_fields.get() != nullptr) {
            StringHelpFunctions::SplitStringByDelimeter(query_fields->c_str(), ",", field_names);
        }

Y
yukun 已提交
1854
        nlohmann::json entity_result_json;
1855
        status = GetEntityByIDs(collection_name->std_str(), entity_ids, field_names, entity_result_json);
Y
yukun 已提交
1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874
        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);
}

1875
StatusDto::ObjectWrapper
1876
WebRequestHandler::GetVector(const OString& collection_name, const OQueryParams& query_params, OString& response) {
B
BossZou 已提交
1877 1878
    auto status = Status::OK();
    try {
1879 1880 1881
        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 已提交
1882
        }
1883

1884 1885 1886
        std::vector<std::string> ids;
        StringHelpFunctions::SplitStringByDelimeter(query_ids->c_str(), ",", ids);

B
BossZou 已提交
1887 1888
        std::vector<int64_t> vector_ids;
        for (auto& id : ids) {
1889
            vector_ids.push_back(std::stol(id));
B
BossZou 已提交
1890 1891 1892 1893 1894 1895 1896 1897
        }
        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 已提交
1898

G
groot 已提交
1899 1900 1901
        FloatJson json;
        json["code"] = (int64_t)status.code();
        json["message"] = status.message();
B
BossZou 已提交
1902 1903 1904 1905 1906 1907 1908 1909
        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 已提交
1910 1911
    }

B
BossZou 已提交
1912
    ASSIGN_RETURN_STATUS_DTO(status);
1913 1914 1915
}

StatusDto::ObjectWrapper
1916
WebRequestHandler::VectorsOp(const OString& collection_name, const OString& payload, OString& response) {
1917 1918 1919 1920 1921 1922 1923
    auto status = Status::OK();
    std::string result_str;

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

        if (payload_json.contains("delete")) {
1924
            status = DeleteByIDs(collection_name->std_str(), payload_json["delete"], result_str);
1925
        } else if (payload_json.contains("search")) {
1926
            status = Search(collection_name->std_str(), payload_json["search"], result_str);
1927
        } else if (payload_json.contains("query")) {
Y
yukun 已提交
1928
            status = HybridSearch(collection_name->c_str(), payload_json, result_str);
1929 1930
        } else {
            status = Status(ILLEGAL_BODY, "Unknown body");
B
BossZou 已提交
1931
        }
1932 1933 1934 1935 1936 1937 1938 1939 1940 1941
    } 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());
    }

1942
    response = status.ok() ? result_str.c_str() : "NULL";
B
BossZou 已提交
1943 1944 1945 1946

    ASSIGN_RETURN_STATUS_DTO(status)
}

1947 1948 1949 1950
/**********
 *
 * System {
 */
B
BossZou 已提交
1951
StatusDto::ObjectWrapper
1952
WebRequestHandler::SystemInfo(const OString& cmd, const OQueryParams& query_params, OString& response_str) {
1953
    std::string info = cmd->std_str();
1954

1955 1956
    auto status = Status::OK();
    std::string result_str;
1957

1958 1959 1960 1961 1962 1963
    try {
        if (info == "config") {
            status = GetConfig(result_str);
        } else {
            if ("info" == info) {
                info = "get_system_info";
1964
            }
1965
            status = Cmd(info, result_str);
1966
        }
1967 1968
    } catch (nlohmann::detail::parse_error& e) {
        std::string emsg = "json error: code=" + std::to_string(e.id) + ", reason=" + e.what();
1969
        RETURN_STATUS_DTO(BODY_PARSE_FAIL, emsg.c_str());
1970 1971
    } catch (nlohmann::detail::type_error& e) {
        std::string emsg = "json error: code=" + std::to_string(e.id) + ", reason=" + e.what();
1972
        RETURN_STATUS_DTO(BODY_PARSE_FAIL, emsg.c_str());
1973
    }
1974

1975
    response_str = status.ok() ? result_str.c_str() : "NULL";
1976

1977 1978
    ASSIGN_RETURN_STATUS_DTO(status);
}
B
BossZou 已提交
1979

1980 1981 1982 1983 1984
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.");
    }
1985 1986 1987

    Status status = Status::OK();
    std::string result_str;
1988
    try {
B
BossZou 已提交
1989 1990 1991
        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, ""));
1992 1993 1994
        nlohmann::json j = nlohmann::json::parse(body_str->c_str());
        if (op->equals("task")) {
            if (j.contains("load")) {
B
BossZou 已提交
1995
                status = PreLoadCollection(j["load"], result_str);
1996 1997
            } else if (j.contains("flush")) {
                status = Flush(j["flush"], result_str);
1998 1999
            }
            if (j.contains("compact")) {
2000
                status = Compact(j["compact"], result_str);
2001 2002
            }
        } else if (op->equals("config")) {
2003
            status = SetConfig(j, result_str);
2004 2005
        } else {
            status = Status(UNKNOWN_PATH, "Unknown path: /system/" + op->std_str());
2006 2007 2008
        }
    } catch (nlohmann::detail::parse_error& e) {
        std::string emsg = "json error: code=" + std::to_string(e.id) + ", reason=" + e.what();
2009
        RETURN_STATUS_DTO(BODY_PARSE_FAIL, emsg.c_str());
2010 2011
    } catch (nlohmann::detail::type_error& e) {
        std::string emsg = "json error: code=" + std::to_string(e.id) + ", reason=" + e.what();
2012
        RETURN_STATUS_DTO(BODY_PARSE_FAIL, emsg.c_str());
2013 2014
    }

2015
    response_str = status.ok() ? result_str.c_str() : "NULL";
B
BossZou 已提交
2016 2017 2018 2019 2020 2021 2022

    ASSIGN_RETURN_STATUS_DTO(status);
}

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