WebRequestHandler.cpp 77.6 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>

W
Wang XiangYu 已提交
22
#include "config/ServerConfig.h"
B
BossZou 已提交
23 24 25 26 27
#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"
28
#include "server/web_impl/utils/Util.h"
29
#include "thirdparty/nlohmann/json.hpp"
W
Wang XiangYu 已提交
30
#include "utils/ConfigUtils.h"
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 83 84 85 86 87 88 89 90 91 92 93 94 95
template <typename T>
void
CopyStructuredData(const nlohmann::json& json, std::vector<uint8_t>& raw) {
    std::vector<T> values;
    auto size = json.size();
    values.resize(size);
    raw.resize(size * sizeof(T));
    size_t offset = 0;
    for (auto data : json) {
        values[offset] = data.get<T>();
        ++offset;
    }
    memcpy(raw.data(), values.data(), size * sizeof(T));
}

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

98 99 100 101 102 103 104 105
/////////////////////////////////// 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 已提交
106
WebRequestHandler::IsBinaryCollection(const std::string& collection_name, bool& bin) {
J
Jin Hai 已提交
107
    CollectionSchema schema;
108 109
    auto status = Status::OK();
    // status = request_handler_.DescribeCollection(context_ptr_, collection_name, schema);
110 111 112
    if (status.ok()) {
        auto metric = engine::MetricType(schema.metric_type_);
        bin = engine::MetricType::HAMMING == metric || engine::MetricType::JACCARD == metric ||
113 114
              engine::MetricType::TANIMOTO == metric || engine::MetricType::SUPERSTRUCTURE == metric ||
              engine::MetricType::SUBSTRUCTURE == metric;
115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
    }

    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 已提交
151 152
///////////////////////// WebRequestHandler methods ///////////////////////////////////////
Status
B
BossZou 已提交
153
WebRequestHandler::GetCollectionMetaInfo(const std::string& collection_name, nlohmann::json& json_out) {
J
Jin Hai 已提交
154
    CollectionSchema schema;
155 156
    auto status = Status::OK();
    // status = request_handler_.DescribeCollection(context_ptr_, collection_name, schema);
B
BossZou 已提交
157 158 159 160 161
    if (!status.ok()) {
        return status;
    }

    int64_t count;
162
    status = request_handler_.CountCollection(context_ptr_, collection_name, count);
B
BossZou 已提交
163 164 165 166 167
    if (!status.ok()) {
        return status;
    }

    IndexParam index_param;
168
    status = request_handler_.DescribeIndex(context_ptr_, collection_name, index_param);
B
BossZou 已提交
169 170 171 172
    if (!status.ok()) {
        return status;
    }

J
Jin Hai 已提交
173
    json_out["collection_name"] = schema.collection_name_;
174 175 176
    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_));
177
    json_out["index_params"] = index_param.extra_params_;
178 179 180 181 182 183 184
    json_out["metric_type"] = MetricMap.at(engine::MetricType(schema.metric_type_));
    json_out["count"] = count;

    return Status::OK();
}

Status
B
BossZou 已提交
185
WebRequestHandler::GetCollectionStat(const std::string& collection_name, nlohmann::json& json_out) {
186
    std::string collection_info;
187
    auto status = request_handler_.ShowCollectionInfo(context_ptr_, collection_name, collection_info);
188 189

    if (status.ok()) {
190 191 192
        try {
            json_out = nlohmann::json::parse(collection_info);
        } catch (std::exception& e) {
B
BossZou 已提交
193 194
            return Status(SERVER_UNEXPECTED_ERROR,
                          "Error occurred when parsing collection stat information: " + std::string(e.what()));
195 196 197 198 199 200 201
        }
    }

    return status;
}

Status
202 203
WebRequestHandler::GetSegmentVectors(const std::string& collection_name, const std::string& segment_name,
                                     int64_t page_size, int64_t offset, nlohmann::json& json_out) {
204
    std::vector<int64_t> vector_ids;
205
    auto status = request_handler_.GetVectorIDs(context_ptr_, collection_name, segment_name, vector_ids);
206 207 208 209 210 211 212 213 214
    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;
215
    status = GetVectorsByIDs(collection_name, ids, vectors_json);
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230

    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
231
WebRequestHandler::GetSegmentIds(const std::string& collection_name, const std::string& segment_name, int64_t page_size,
232 233
                                 int64_t offset, nlohmann::json& json_out) {
    std::vector<int64_t> vector_ids;
234
    auto status = request_handler_.GetVectorIDs(context_ptr_, collection_name, segment_name, vector_ids);
235 236 237 238 239 240 241 242 243 244 245 246 247 248 249
    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;
250
}
B
BossZou 已提交
251

252 253 254
Status
WebRequestHandler::CommandLine(const std::string& cmd, std::string& reply) {
    return request_handler_.Cmd(context_ptr_, cmd, reply);
B
BossZou 已提交
255 256
}

257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272
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 已提交
273
WebRequestHandler::PreLoadCollection(const nlohmann::json& json, std::string& result_str) {
274 275
    if (!json.contains("collection_name")) {
        return Status(BODY_FIELD_LOSS, "Field \"load\" must contains collection_name");
276 277
    }

278
    auto collection_name = json["collection_name"];
279
    auto status = request_handler_.PreloadCollection(context_ptr_, collection_name.get<std::string>());
280 281 282 283 284
    if (status.ok()) {
        nlohmann::json result;
        AddStatusToJson(result, status.code(), status.message());
        result_str = result.dump();
    }
B
BossZou 已提交
285

286 287 288 289 290
    return status;
}

Status
WebRequestHandler::Flush(const nlohmann::json& json, std::string& result_str) {
291 292
    if (!json.contains("collection_names")) {
        return Status(BODY_FIELD_LOSS, "Field \"flush\" must contains collection_names");
293 294
    }

295 296 297
    auto collection_names = json["collection_names"];
    if (!collection_names.is_array()) {
        return Status(BODY_FIELD_LOSS, "Field \"collection_names\" must be and array");
298 299 300
    }

    std::vector<std::string> names;
301
    for (auto& name : collection_names) {
302 303 304 305 306 307 308 309 310 311 312 313 314 315 316
        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) {
317 318
    if (!json.contains("collection_name")) {
        return Status(BODY_FIELD_LOSS, "Field \"compact\" must contains collection_names");
319 320
    }

321 322 323
    auto collection_name = json["collection_name"];
    if (!collection_name.is_string()) {
        return Status(BODY_FIELD_LOSS, "Field \"collection_names\" must be a string");
324 325
    }

326
    auto name = collection_name.get<std::string>();
327

G
groot 已提交
328 329
    double compact_threshold = 0.1;  // compact trigger threshold: delete_counts/segment_counts
    auto status = request_handler_.Compact(context_ptr_, name, compact_threshold);
330 331 332

    if (status.ok()) {
        nlohmann::json result;
333
        AddStatusToJson(result, status.code(), status.message());
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
        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
        bool required = false;
W
Wang XiangYu 已提交
365 366
        // TODO: Use new cofnig mgr
        // Config::GetInstance().GetServerRestartRequired(required);
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 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413
        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;";
    }

414 415 416
    nlohmann::json result;
    AddStatusToJson(result, StatusCode::SUCCESS, msg);

417
    bool required = false;
W
Wang XiangYu 已提交
418
    // Config::GetInstance().GetServerRestartRequired(required);
419 420 421 422 423 424 425 426
    result["restart_required"] = required;

    result_str = result.dump();

    return Status::OK();
}

Status
427
WebRequestHandler::Search(const std::string& collection_name, const nlohmann::json& json, std::string& result_str) {
428 429 430 431 432
    if (!json.contains("topk")) {
        return Status(BODY_FIELD_LOSS, "Field \'topk\' is required");
    }
    int64_t topk = json["topk"];

B
BossZou 已提交
433 434 435 436
    if (!json.contains("params")) {
        return Status(BODY_FIELD_LOSS, "Field \'params\' is required");
    }

437 438 439 440 441 442 443 444 445 446 447 448
    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 已提交
449 450 451 452 453 454
    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");
455
        }
B
BossZou 已提交
456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473

        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>());
            }
474 475
        }

B
BossZou 已提交
476 477 478 479 480
        bool bin_flag = false;
        status = IsBinaryCollection(collection_name, bin_flag);
        if (!status.ok()) {
            return status;
        }
481

B
BossZou 已提交
482 483 484
        if (!json.contains("vectors")) {
            return Status(BODY_FIELD_LOSS, "Field \"vectors\" is required");
        }
485

B
BossZou 已提交
486 487 488 489 490
        engine::VectorsData vectors_data;
        status = CopyRecordsFromJson(json["vectors"], vectors_data, bin_flag);
        if (!status.ok()) {
            return status;
        }
491

B
BossZou 已提交
492 493
        status = request_handler_.Search(context_ptr_, collection_name, vectors_data, topk, json["params"],
                                         partition_tags, file_id_vec, result);
494 495 496
    }
    if (!status.ok()) {
        return status;
497 498 499 500 501 502 503 504 505 506 507 508
    }

    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 已提交
509
    for (int64_t i = 0; i < result.row_num_; i++) {
510 511 512 513 514 515 516 517 518 519 520 521 522 523 524
        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();
}

525 526 527 528 529 530 531 532 533 534 535 536
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};
        }

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 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639
        //        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);
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 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705
    }
    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 已提交
706
void
707
ConvertRowToColumnJson(const std::vector<engine::AttrsData>& row_attrs, const std::vector<std::string>& field_names,
Y
yukun 已提交
708
                       const int64_t row_num, nlohmann::json& column_attrs_json) {
709 710 711 712 713 714 715 716
    //    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 已提交
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 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808

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

809 810 811 812 813
Status
WebRequestHandler::HybridSearch(const std::string& collection_name, const nlohmann::json& json,
                                std::string& result_str) {
    Status status;

814 815
    milvus::server::HybridCollectionSchema collection_schema;
    status = request_handler_.DescribeHybridCollection(context_ptr_, collection_name, collection_schema);
816 817 818
    if (!status.ok()) {
        return Status{UNEXPECTED_ERROR, "DescribeHybridCollection failed"};
    }
819
    field_type_ = collection_schema.field_types_;
820

Y
yukun 已提交
821 822 823 824 825 826 827 828
    milvus::json extra_params;
    if (json.contains("fields")) {
        if (json["fields"].is_array()) {
            extra_params["fields"] = json["fields"];
        }
    }
    auto query_json = json["query"];

829
    std::vector<std::string> partition_tags;
Y
yukun 已提交
830 831
    if (query_json.contains("partition_tags")) {
        auto tags = query_json["partition_tags"];
832 833 834 835 836 837 838 839 840
        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 已提交
841 842
    if (query_json.contains("bool")) {
        auto boolean_query_json = query_json["bool"];
Y
yukun 已提交
843 844
        auto boolean_query = std::make_shared<query::BooleanQuery>();
        query_ptr_ = std::make_shared<query::Query>();
845 846 847 848 849

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

Y
yukun 已提交
853 854
        query_ptr_->root = general_query->bin;

855 856
        engine::QueryResultPtr result = std::make_shared<engine::QueryResult>();
        status = request_handler_.HybridSearch(context_ptr_, query_ptr_, extra_params, result);
857 858 859 860 861 862

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

        nlohmann::json result_json;
863 864
        result_json["num"] = result->row_num_;
        if (result->row_num_ == 0) {
865 866 867 868 869
            result_json["result"] = std::vector<int64_t>();
            result_str = result_json.dump();
            return Status::OK();
        }

870
        auto step = result->result_ids_.size() / result->row_num_;
871
        nlohmann::json search_result_json;
872
        for (int64_t i = 0; i < result->row_num_; i++) {
873 874 875
            nlohmann::json raw_result_json;
            for (size_t j = 0; j < step; j++) {
                nlohmann::json one_result_json;
876 877
                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));
878 879 880 881
                raw_result_json.emplace_back(one_result_json);
            }
            search_result_json.emplace_back(raw_result_json);
        }
Y
yukun 已提交
882
        nlohmann::json attr_json;
883
        ConvertRowToColumnJson(result->attrs_, query_ptr_->field_names, result->row_num_, attr_json);
Y
yukun 已提交
884
        result_json["Entity"] = attr_json;
885 886 887 888 889 890 891
        result_json["result"] = search_result_json;
        result_str = result_json.dump();
    }

    return Status::OK();
}

892
Status
893 894
WebRequestHandler::DeleteByIDs(const std::string& collection_name, const nlohmann::json& json,
                               std::string& result_str) {
895 896 897 898 899 900 901 902 903 904
    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) {
905
        auto id_str = id.get<std::string>();
C
Cai Yudong 已提交
906
        if (!ValidateStringIsNumber(id_str).ok()) {
907 908 909
            return Status(ILLEGAL_BODY, "Members in \"ids\" must be integer string");
        }
        vector_ids.emplace_back(std::stol(id_str));
910 911
    }

912
    auto status = request_handler_.DeleteByID(context_ptr_, collection_name, vector_ids);
913 914 915 916

    nlohmann::json result_json;
    AddStatusToJson(result_json, status.code(), status.message());
    result_str = result_json.dump();
917 918 919 920

    return status;
}

Y
yukun 已提交
921 922
Status
WebRequestHandler::GetEntityByIDs(const std::string& collection_name, const std::vector<int64_t>& ids,
923
                                  std::vector<std::string>& field_names, nlohmann::json& json_out) {
Y
yukun 已提交
924 925
    std::vector<engine::VectorsData> vector_batch;
    std::vector<engine::AttrsData> attr_batch;
926 927
    auto status =
        request_handler_.GetEntityByID(context_ptr_, collection_name, field_names, ids, attr_batch, vector_batch);
Y
yukun 已提交
928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953
    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;
}

954
Status
955
WebRequestHandler::GetVectorsByIDs(const std::string& collection_name, const std::vector<int64_t>& ids,
956 957
                                   nlohmann::json& json_out) {
    std::vector<engine::VectorsData> vector_batch;
958 959 960
    auto status = request_handler_.GetVectorsByID(context_ptr_, collection_name, ids, vector_batch);
    if (!status.ok()) {
        return status;
961 962 963
    }

    bool bin;
B
BossZou 已提交
964
    status = IsBinaryCollection(collection_name, bin);
965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984
    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 已提交
985 986 987 988 989
StatusDto::ObjectWrapper
WebRequestHandler::GetDevices(DevicesDto::ObjectWrapper& devices_dto) {
    auto system_info = SystemInfo::GetInstance();

    devices_dto->cpu = devices_dto->cpu->createShared();
990
    devices_dto->cpu->memory = system_info.GetPhysicalMemory() >> 30;
B
BossZou 已提交
991 992 993 994 995

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

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

    if (count != device_mems.size()) {
999
        RETURN_STATUS_DTO(UNEXPECTED_ERROR, "Can't obtain GPU info");
B
BossZou 已提交
1000 1001 1002 1003
    }

    for (size_t i = 0; i < count; i++) {
        auto device_dto = DeviceInfoDto::createShared();
1004
        device_dto->memory = device_mems.at(i) >> 30;
B
BossZou 已提交
1005 1006 1007 1008 1009 1010 1011 1012 1013
        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) {
W
Wang XiangYu 已提交
1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049
    //    std::string reply;
    //    std::string cache_cmd_prefix = "get_config " + std::string(CONFIG_CACHE) + ".";
    //
    //    std::string cache_cmd_string = cache_cmd_prefix + std::string(CONFIG_CACHE_CPU_CACHE_CAPACITY);
    //    auto status = CommandLine(cache_cmd_string, reply);
    //    if (!status.ok()) {
    //        ASSIGN_RETURN_STATUS_DTO(status)
    //    }
    //    advanced_config->cpu_cache_capacity = std::stol(reply);
    //
    //    cache_cmd_string = cache_cmd_prefix + std::string(CONFIG_CACHE_CACHE_INSERT_DATA);
    //    CommandLine(cache_cmd_string, reply);
    //    if (!status.ok()) {
    //        ASSIGN_RETURN_STATUS_DTO(status)
    //    }
    //    advanced_config->cache_insert_data = ("1" == reply || "true" == reply);
    //
    //    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);
    //    if (!status.ok()) {
    //        ASSIGN_RETURN_STATUS_DTO(status)
    //    }
    //    advanced_config->use_blas_threshold = std::stol(reply);
    //
    //#ifdef MILVUS_GPU_VERSION
    //    engine_cmd_string = engine_cmd_prefix + std::string(CONFIG_GPU_RESOURCE_GPU_SEARCH_THRESHOLD);
    //    CommandLine(engine_cmd_string, reply);
    //    if (!status.ok()) {
    //        ASSIGN_RETURN_STATUS_DTO(status)
    //    }
    //    advanced_config->gpu_search_threshold = std::stol(reply);
    //#endif
    //
    //    ASSIGN_RETURN_STATUS_DTO(status)
    ASSIGN_RETURN_STATUS_DTO(Status::OK());
B
BossZou 已提交
1050 1051 1052 1053
}

StatusDto::ObjectWrapper
WebRequestHandler::SetAdvancedConfig(const AdvancedConfigDto::ObjectWrapper& advanced_config) {
W
Wang XiangYu 已提交
1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109
    //    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.");
    //    }
    //#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);
    //    if (!status.ok()) {
    //        ASSIGN_RETURN_STATUS_DTO(status)
    //    }
    //
    //#ifdef MILVUS_GPU_VERSION
    //    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);
    //    if (!status.ok()) {
    //        ASSIGN_RETURN_STATUS_DTO(status)
    //    }
    //#endif
    //
    //    ASSIGN_RETURN_STATUS_DTO(status)
    ASSIGN_RETURN_STATUS_DTO(Status::OK());
B
BossZou 已提交
1110 1111 1112 1113 1114
}

#ifdef MILVUS_GPU_VERSION
StatusDto::ObjectWrapper
WebRequestHandler::GetGpuConfig(GPUConfigDto::ObjectWrapper& gpu_config_dto) {
W
Wang XiangYu 已提交
1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163
    //    std::string reply;
    //    std::string gpu_cmd_prefix = "get_config " + std::string(CONFIG_GPU_RESOURCE) + ".";
    //
    //    std::string gpu_cmd_request = gpu_cmd_prefix + std::string(CONFIG_GPU_RESOURCE_ENABLE);
    //    auto status = CommandLine(gpu_cmd_request, reply);
    //    if (!status.ok()) {
    //        ASSIGN_RETURN_STATUS_DTO(status);
    //    }
    //    gpu_config_dto->enable = reply == "1" || reply == "true";
    //
    //    if (!gpu_config_dto->enable->getValue()) {
    //        ASSIGN_RETURN_STATUS_DTO(Status::OK());
    //    }
    //
    //    gpu_cmd_request = gpu_cmd_prefix + std::string(CONFIG_GPU_RESOURCE_CACHE_CAPACITY);
    //    status = CommandLine(gpu_cmd_request, reply);
    //    if (!status.ok()) {
    //        ASSIGN_RETURN_STATUS_DTO(status);
    //    }
    //    gpu_config_dto->cache_capacity = std::stol(reply);
    //
    //    gpu_cmd_request = gpu_cmd_prefix + std::string(CONFIG_GPU_RESOURCE_SEARCH_RESOURCES);
    //    status = CommandLine(gpu_cmd_request, reply);
    //    if (!status.ok()) {
    //        ASSIGN_RETURN_STATUS_DTO(status);
    //    }
    //
    //    std::vector<std::string> gpu_entry;
    //    StringHelpFunctions::SplitStringByDelimeter(reply, ",", gpu_entry);
    //
    //    gpu_config_dto->search_resources = gpu_config_dto->search_resources->createShared();
    //    for (auto& device_id : gpu_entry) {
    //        gpu_config_dto->search_resources->pushBack(OString(device_id.c_str())->toUpperCase());
    //    }
    //    gpu_entry.clear();
    //
    //    gpu_cmd_request = gpu_cmd_prefix + std::string(CONFIG_GPU_RESOURCE_BUILD_INDEX_RESOURCES);
    //    status = CommandLine(gpu_cmd_request, reply);
    //    if (!status.ok()) {
    //        ASSIGN_RETURN_STATUS_DTO(status);
    //    }
    //
    //    StringHelpFunctions::SplitStringByDelimeter(reply, ",", gpu_entry);
    //    gpu_config_dto->build_index_resources = gpu_config_dto->build_index_resources->createShared();
    //    for (auto& device_id : gpu_entry) {
    //        gpu_config_dto->build_index_resources->pushBack(OString(device_id.c_str())->toUpperCase());
    //    }
    //
    //    ASSIGN_RETURN_STATUS_DTO(Status::OK());
B
BossZou 已提交
1164 1165 1166 1167 1168
    ASSIGN_RETURN_STATUS_DTO(Status::OK());
}

StatusDto::ObjectWrapper
WebRequestHandler::SetGpuConfig(const GPUConfigDto::ObjectWrapper& gpu_config_dto) {
W
Wang XiangYu 已提交
1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248
    //    // Step 1: Check config param
    //    if (nullptr == gpu_config_dto->enable.get()) {
    //        RETURN_STATUS_DTO(BODY_FIELD_LOSS, "Field \'enable\' miss")
    //    }
    //
    //    if (nullptr == gpu_config_dto->cache_capacity.get()) {
    //        RETURN_STATUS_DTO(BODY_FIELD_LOSS, "Field \'cache_capacity\' miss")
    //    }
    //
    //    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");
    //    }
    //
    //    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");
    //    }
    //
    //    // 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);
    //    if (!status.ok()) {
    //        ASSIGN_RETURN_STATUS_DTO(status);
    //    }
    //
    //    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);
    //    }
    //
    //    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);
    //    }
    //
    //    gpu_cmd_request = gpu_cmd_prefix + std::string(CONFIG_GPU_RESOURCE_SEARCH_RESOURCES) + " " +
    //    search_resources_value; status = CommandLine(gpu_cmd_request, reply); 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);
    //    }
    //
    //    gpu_cmd_request =
    //        gpu_cmd_prefix + std::string(CONFIG_GPU_RESOURCE_BUILD_INDEX_RESOURCES) + " " + build_resources_value;
    //    status = CommandLine(gpu_cmd_request, reply);
    //    if (!status.ok()) {
    //        ASSIGN_RETURN_STATUS_DTO(status);
    //    }
    //
    //    ASSIGN_RETURN_STATUS_DTO(Status::OK());
B
BossZou 已提交
1249 1250 1251 1252
    ASSIGN_RETURN_STATUS_DTO(Status::OK());
}
#endif

1253 1254
/*************
 *
J
Jin Hai 已提交
1255
 * Collection {
1256
 */
B
BossZou 已提交
1257
StatusDto::ObjectWrapper
B
BossZou 已提交
1258
WebRequestHandler::CreateCollection(const CollectionRequestDto::ObjectWrapper& collection_schema) {
1259 1260
    if (nullptr == collection_schema->collection_name.get()) {
        RETURN_STATUS_DTO(BODY_FIELD_LOSS, "Field \'collection_name\' is missing")
B
BossZou 已提交
1261 1262
    }

1263
    if (nullptr == collection_schema->dimension.get()) {
B
BossZou 已提交
1264 1265 1266
        RETURN_STATUS_DTO(BODY_FIELD_LOSS, "Field \'dimension\' is missing")
    }

1267
    if (nullptr == collection_schema->index_file_size.get()) {
B
BossZou 已提交
1268 1269 1270
        RETURN_STATUS_DTO(BODY_FIELD_LOSS, "Field \'index_file_size\' is missing")
    }

1271
    if (nullptr == collection_schema->metric_type.get()) {
B
BossZou 已提交
1272 1273 1274
        RETURN_STATUS_DTO(BODY_FIELD_LOSS, "Field \'metric_type\' is missing")
    }

1275
    if (MetricNameMap.find(collection_schema->metric_type->std_str()) == MetricNameMap.end()) {
B
BossZou 已提交
1276 1277 1278
        RETURN_STATUS_DTO(ILLEGAL_METRIC_TYPE, "metric_type is illegal")
    }

1279 1280 1281 1282 1283
    auto status = Status::OK();
    //    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 已提交
1284 1285 1286 1287

    ASSIGN_RETURN_STATUS_DTO(status)
}

1288 1289 1290 1291 1292 1293
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
1294 1295 1296
    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;
1297 1298 1299 1300 1301
    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") {
1302
            field_types.insert(std::make_pair(field_name, engine::meta::hybrid::DataType::INT8));
1303
        } else if (field_type == "int16") {
1304
            field_types.insert(std::make_pair(field_name, engine::meta::hybrid::DataType::INT16));
1305
        } else if (field_type == "int32") {
1306
            field_types.insert(std::make_pair(field_name, engine::meta::hybrid::DataType::INT32));
1307
        } else if (field_type == "int64") {
1308
            field_types.insert(std::make_pair(field_name, engine::meta::hybrid::DataType::INT64));
1309
        } else if (field_type == "float") {
1310
            field_types.insert(std::make_pair(field_name, engine::meta::hybrid::DataType::FLOAT));
1311
        } else if (field_type == "double") {
1312
            field_types.insert(std::make_pair(field_name, engine::meta::hybrid::DataType::DOUBLE));
1313 1314 1315 1316 1317 1318
        } else if (field_type == "vector") {
        } else {
            std::string msg = field_name + " has wrong field_type";
            RETURN_STATUS_DTO(BODY_PARSE_FAIL, msg.c_str());
        }

1319
        field_extra_params.insert(std::make_pair(field_name, extra_params.dump()));
1320 1321
    }

1322 1323 1324 1325
    milvus::json json_params;

    auto status = request_handler_.CreateHybridCollection(context_ptr_, collection_name, field_types,
                                                          field_index_params, field_extra_params, json_params);
1326 1327 1328 1329

    ASSIGN_RETURN_STATUS_DTO(status)
}

B
BossZou 已提交
1330
StatusDto::ObjectWrapper
B
BossZou 已提交
1331
WebRequestHandler::ShowCollections(const OQueryParams& query_params, OString& result) {
1332 1333 1334 1335
    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 已提交
1336 1337
    }

1338 1339 1340 1341
    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());
1342 1343
    }

1344
    if (offset < 0 || page_size < 0) {
1345
        RETURN_STATUS_DTO(ILLEGAL_QUERY_PARAM, "Query param 'offset' or 'page_size' should equal or bigger than 0");
B
BossZou 已提交
1346
    }
1347

1348
    bool all_required = false;
1349 1350 1351
    ParseQueryBool(query_params, "all_required", all_required);
    if (!status.ok()) {
        RETURN_STATUS_DTO(status.code(), status.message().c_str());
1352 1353
    }

1354
    std::vector<std::string> collections;
1355
    status = request_handler_.ShowCollections(context_ptr_, collections);
1356 1357 1358
    if (!status.ok()) {
        ASSIGN_RETURN_STATUS_DTO(status)
    }
B
BossZou 已提交
1359

1360
    if (all_required) {
1361
        offset = 0;
1362
        page_size = collections.size();
1363
    } else {
1364 1365
        offset = std::min((size_t)offset, collections.size());
        page_size = std::min(collections.size() - offset, (size_t)page_size);
1366 1367
    }

1368
    nlohmann::json collections_json;
1369
    for (int64_t i = offset; i < page_size + offset; i++) {
1370
        nlohmann::json collection_json;
B
BossZou 已提交
1371
        status = GetCollectionMetaInfo(collections.at(i), collection_json);
B
BossZou 已提交
1372
        if (!status.ok()) {
1373
            ASSIGN_RETURN_STATUS_DTO(status)
B
BossZou 已提交
1374
        }
1375
        collections_json.push_back(collection_json);
1376
    }
1377

1378
    nlohmann::json result_json;
1379 1380 1381
    result_json["count"] = collections.size();
    if (collections_json.empty()) {
        result_json["collections"] = std::vector<int64_t>();
1382
    } else {
1383
        result_json["collections"] = collections_json;
B
BossZou 已提交
1384 1385
    }

1386 1387
    result = result_json.dump().c_str();

B
BossZou 已提交
1388 1389 1390
    ASSIGN_RETURN_STATUS_DTO(status)
}

1391
StatusDto::ObjectWrapper
B
BossZou 已提交
1392
WebRequestHandler::GetCollection(const OString& collection_name, const OQueryParams& query_params, OString& result) {
1393 1394
    if (nullptr == collection_name.get()) {
        RETURN_STATUS_DTO(PATH_PARAM_LOSS, "Path param \'collection_name\' is required!");
1395 1396
    }

1397 1398 1399 1400 1401
    std::string stat;
    auto status = ParseQueryStr(query_params, "info", stat);
    if (!status.ok()) {
        RETURN_STATUS_DTO(status.code(), status.message().c_str());
    }
1402

1403
    if (!stat.empty() && stat == "stat") {
1404
        nlohmann::json json;
B
BossZou 已提交
1405
        status = GetCollectionStat(collection_name->std_str(), json);
1406
        result = status.ok() ? json.dump().c_str() : "NULL";
1407 1408
    } else {
        nlohmann::json json;
B
BossZou 已提交
1409
        status = GetCollectionMetaInfo(collection_name->std_str(), json);
1410
        result = status.ok() ? json.dump().c_str() : "NULL";
1411 1412 1413 1414 1415
    }

    ASSIGN_RETURN_STATUS_DTO(status);
}

B
BossZou 已提交
1416
StatusDto::ObjectWrapper
B
BossZou 已提交
1417
WebRequestHandler::DropCollection(const OString& collection_name) {
1418
    auto status = request_handler_.DropCollection(context_ptr_, collection_name->std_str());
B
BossZou 已提交
1419 1420 1421 1422

    ASSIGN_RETURN_STATUS_DTO(status)
}

1423 1424 1425 1426 1427
/***********
 *
 * Index {
 */

B
BossZou 已提交
1428
StatusDto::ObjectWrapper
J
Jin Hai 已提交
1429
WebRequestHandler::CreateIndex(const OString& collection_name, const OString& body) {
1430 1431
    try {
        auto request_json = nlohmann::json::parse(body->std_str());
1432
        std::string field_name, index_name;
1433 1434 1435
        if (!request_json.contains("index_type")) {
            RETURN_STATUS_DTO(BODY_FIELD_LOSS, "Field \'index_type\' is required");
        }
B
BossZou 已提交
1436

1437 1438 1439 1440 1441 1442 1443 1444
        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")
        }
1445 1446 1447 1448 1449

        auto status = Status::OK();
        //        auto status =
        //            request_handler_.CreateIndex(context_ptr_, collection_name->std_str(), index,
        //            request_json["params"]);
1450 1451
        ASSIGN_RETURN_STATUS_DTO(status);
    } catch (nlohmann::detail::parse_error& e) {
Y
Yhz 已提交
1452
        RETURN_STATUS_DTO(BODY_PARSE_FAIL, e.what())
1453
    } catch (nlohmann::detail::type_error& e) {
Y
Yhz 已提交
1454
        RETURN_STATUS_DTO(BODY_PARSE_FAIL, e.what())
B
BossZou 已提交
1455 1456
    }

1457
    ASSIGN_RETURN_STATUS_DTO(Status::OK())
B
BossZou 已提交
1458 1459 1460
}

StatusDto::ObjectWrapper
1461
WebRequestHandler::GetIndex(const OString& collection_name, OString& result) {
B
BossZou 已提交
1462
    IndexParam param;
1463
    auto status = request_handler_.DescribeIndex(context_ptr_, collection_name->std_str(), param);
B
BossZou 已提交
1464 1465

    if (status.ok()) {
1466 1467 1468 1469 1470
        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 已提交
1471 1472 1473 1474 1475 1476
    }

    ASSIGN_RETURN_STATUS_DTO(status)
}

StatusDto::ObjectWrapper
1477
WebRequestHandler::DropIndex(const OString& collection_name) {
1478 1479
    auto status = Status::OK();
    //    auto status = request_handler_.DropIndex(context_ptr_, collection_name->std_str());
B
BossZou 已提交
1480 1481 1482 1483 1484

    ASSIGN_RETURN_STATUS_DTO(status)
}

StatusDto::ObjectWrapper
1485
WebRequestHandler::CreatePartition(const OString& collection_name, const PartitionRequestDto::ObjectWrapper& param) {
B
BossZou 已提交
1486 1487 1488 1489
    if (nullptr == param->partition_tag.get()) {
        RETURN_STATUS_DTO(BODY_FIELD_LOSS, "Field \'partition_tag\' is required")
    }

1490
    auto status =
1491
        request_handler_.CreatePartition(context_ptr_, collection_name->std_str(), param->partition_tag->std_str());
B
BossZou 已提交
1492 1493 1494 1495 1496

    ASSIGN_RETURN_STATUS_DTO(status)
}

StatusDto::ObjectWrapper
B
BossZou 已提交
1497
WebRequestHandler::ShowPartitions(const OString& collection_name, const OQueryParams& query_params,
B
BossZou 已提交
1498
                                  PartitionListDto::ObjectWrapper& partition_list_dto) {
1499 1500 1501 1502
    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 已提交
1503 1504
    }

1505 1506 1507 1508
    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());
1509 1510
    }

1511
    if (offset < 0 || page_size < 0) {
1512 1513
        ASSIGN_RETURN_STATUS_DTO(
            Status(SERVER_UNEXPECTED_ERROR, "Query param 'offset' or 'page_size' should equal or bigger than 0"));
B
BossZou 已提交
1514 1515
    }

1516 1517 1518 1519
    bool all_required = false;
    auto required = query_params.get("all_required");
    if (nullptr != required.get()) {
        auto required_str = required->std_str();
C
Cai Yudong 已提交
1520
        if (!ValidateStringIsBool(required_str).ok()) {
1521 1522 1523 1524 1525
            RETURN_STATUS_DTO(ILLEGAL_QUERY_PARAM, "Query param \'all_required\' must be a bool")
        }
        all_required = required_str == "True" || required_str == "true";
    }

1526 1527
    std::vector<std::string> partition_names;
    status = request_handler_.ShowPartitions(context_ptr_, collection_name->std_str(), partition_names);
1528 1529 1530
    if (!status.ok()) {
        ASSIGN_RETURN_STATUS_DTO(status)
    }
B
BossZou 已提交
1531

1532
    if (all_required) {
1533
        offset = 0;
1534
        page_size = partition_names.size();
1535
    } else {
1536 1537
        offset = std::min((size_t)offset, partition_names.size());
        page_size = std::min(partition_names.size() - offset, (size_t)page_size);
1538 1539
    }

1540
    partition_list_dto->count = partition_names.size();
1541 1542
    partition_list_dto->partitions = partition_list_dto->partitions->createShared();

1543
    if (offset < (int64_t)(partition_names.size())) {
1544
        for (int64_t i = offset; i < page_size + offset; i++) {
1545
            auto partition_dto = PartitionFieldsDto::createShared();
1546
            partition_dto->partition_tag = partition_names.at(i).c_str();
1547
            partition_list_dto->partitions->pushBack(partition_dto);
B
BossZou 已提交
1548 1549 1550 1551 1552 1553 1554
        }
    }

    ASSIGN_RETURN_STATUS_DTO(status)
}

StatusDto::ObjectWrapper
1555
WebRequestHandler::DropPartition(const OString& collection_name, const OString& body) {
1556 1557 1558 1559 1560 1561 1562 1563 1564
    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())
    }
1565
    auto status = request_handler_.DropPartition(context_ptr_, collection_name->std_str(), tag);
B
BossZou 已提交
1566 1567 1568 1569

    ASSIGN_RETURN_STATUS_DTO(status)
}

1570 1571 1572 1573
/***********
 *
 * Segment {
 */
B
BossZou 已提交
1574
StatusDto::ObjectWrapper
1575
WebRequestHandler::ShowSegments(const OString& collection_name, const OQueryParams& query_params, OString& response) {
1576 1577 1578 1579
    int64_t offset = 0;
    auto status = ParseQueryInteger(query_params, "offset", offset);
    if (!status.ok()) {
        RETURN_STATUS_DTO(status.code(), status.message().c_str());
1580 1581
    }

1582 1583 1584 1585
    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());
1586 1587
    }

1588
    if (offset < 0 || page_size < 0) {
1589 1590 1591
        RETURN_STATUS_DTO(ILLEGAL_QUERY_PARAM, "Query param 'offset' or 'page_size' should equal or bigger than 0");
    }

1592 1593 1594 1595
    bool all_required = false;
    auto required = query_params.get("all_required");
    if (nullptr != required.get()) {
        auto required_str = required->std_str();
C
Cai Yudong 已提交
1596
        if (!ValidateStringIsBool(required_str).ok()) {
1597 1598 1599 1600 1601
            RETURN_STATUS_DTO(ILLEGAL_QUERY_PARAM, "Query param \'all_required\' must be a bool")
        }
        all_required = required_str == "True" || required_str == "true";
    }

1602 1603 1604 1605 1606
    std::string tag;
    if (nullptr != query_params.get("partition_tag").get()) {
        tag = query_params.get("partition_tag")->std_str();
    }

1607
    std::string info;
1608
    status = request_handler_.ShowCollectionInfo(context_ptr_, collection_name->std_str(), info);
1609 1610 1611 1612
    if (!status.ok()) {
        ASSIGN_RETURN_STATUS_DTO(status)
    }

1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641
    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();
1642 1643 1644
    AddStatusToJson(result_json, status.code(), status.message());
    response = result_json.dump().c_str();

B
BossZou 已提交
1645 1646 1647 1648
    ASSIGN_RETURN_STATUS_DTO(status)
}

StatusDto::ObjectWrapper
1649
WebRequestHandler::GetSegmentInfo(const OString& collection_name, const OString& segment_name, const OString& info,
1650
                                  const OQueryParams& query_params, OString& result) {
1651 1652 1653 1654
    int64_t offset = 0;
    auto status = ParseQueryInteger(query_params, "offset", offset);
    if (!status.ok()) {
        RETURN_STATUS_DTO(status.code(), status.message().c_str());
1655 1656
    }

1657 1658 1659 1660
    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 已提交
1661 1662
    }

1663
    if (offset < 0 || page_size < 0) {
1664 1665 1666 1667 1668
        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();
1669
    status = Status::OK();
1670 1671 1672
    nlohmann::json json;
    // Get vectors
    if (re == "vectors") {
1673
        status = GetSegmentVectors(collection_name->std_str(), segment_name->std_str(), page_size, offset, json);
1674 1675
        // Get vector ids
    } else if (re == "ids") {
1676
        status = GetSegmentIds(collection_name->std_str(), segment_name->std_str(), page_size, offset, json);
B
BossZou 已提交
1677 1678
    }

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

1681 1682 1683 1684 1685 1686 1687 1688
    ASSIGN_RETURN_STATUS_DTO(status)
}

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

1694 1695
    // step 1: copy vectors
    bool bin_flag;
B
BossZou 已提交
1696
    auto status = IsBinaryCollection(collection_name->std_str(), bin_flag);
1697 1698
    if (!status.ok()) {
        ASSIGN_RETURN_STATUS_DTO(status)
B
BossZou 已提交
1699 1700
    }

1701 1702 1703 1704
    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 已提交
1705
    engine::VectorsData vectors;
1706 1707 1708 1709
    CopyRecordsFromJson(body_json["vectors"], vectors, bin_flag);
    if (!status.ok()) {
        ASSIGN_RETURN_STATUS_DTO(status)
    }
1710

1711 1712 1713 1714 1715
    // 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");
1716
        }
1717 1718
        auto& id_array = vectors.id_array_;
        id_array.clear();
1719 1720 1721 1722 1723 1724 1725 1726
        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());
1727
        }
G
groot 已提交
1728
    }
B
BossZou 已提交
1729

1730 1731 1732 1733
    // step 3: copy partition tag
    std::string tag;
    if (body_json.contains("partition_tag")) {
        tag = body_json["partition_tag"];
1734
    }
B
BossZou 已提交
1735

1736
    // step 4: construct result
1737
    status = request_handler_.Insert(context_ptr_, collection_name->std_str(), vectors, tag);
1738 1739 1740 1741 1742 1743 1744 1745 1746 1747
    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)
}

1748 1749 1750 1751 1752 1753 1754 1755
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());
G
groot 已提交
1756
    std::string partition_name = body_json["partition_tag"];
1757 1758 1759
    uint64_t row_num = body_json["row_num"];

    std::unordered_map<std::string, engine::meta::hybrid::DataType> field_types;
1760 1761
    auto status = Status::OK();
    //    auto status = request_handler_.DescribeHybridCollection(context_ptr_, collection_name->c_str(), field_types);
1762 1763 1764 1765 1766 1767

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

G
groot 已提交
1768 1769
    std::unordered_map<std::string, std::vector<uint8_t>> chunk_data;

1770 1771 1772
    for (auto& entity : entities) {
        std::string field_name = entity["field_name"];
        auto field_value = entity["field_value"];
G
groot 已提交
1773 1774 1775 1776 1777 1778
        auto size = field_value.size();
        if (size != row_num) {
            RETURN_STATUS_DTO(ILLEGAL_ROWRECORD, "Field row count inconsist");
        }

        std::vector<uint8_t> temp_data;
1779
        switch (field_types.at(field_name)) {
G
groot 已提交
1780 1781 1782 1783
            case engine::meta::hybrid::DataType::INT32: {
                CopyStructuredData<int32_t>(field_value, temp_data);
                break;
            }
1784
            case engine::meta::hybrid::DataType::INT64: {
G
groot 已提交
1785 1786 1787 1788 1789
                CopyStructuredData<int64_t>(field_value, temp_data);
                break;
            }
            case engine::meta::hybrid::DataType::FLOAT: {
                CopyStructuredData<float>(field_value, temp_data);
1790 1791 1792
                break;
            }
            case engine::meta::hybrid::DataType::DOUBLE: {
G
groot 已提交
1793
                CopyStructuredData<double>(field_value, temp_data);
1794 1795
                break;
            }
1796
            case engine::meta::hybrid::DataType::VECTOR_FLOAT: {
1797
                bool bin_flag;
B
BossZou 已提交
1798
                status = IsBinaryCollection(collection_name->c_str(), bin_flag);
1799 1800 1801 1802
                if (!status.ok()) {
                    ASSIGN_RETURN_STATUS_DTO(status)
                }

G
groot 已提交
1803 1804 1805
                //                engine::VectorsData vectors;
                //                CopyRecordsFromJson(field_value, vectors, bin_flag);
                //                vector_datas.insert(std::make_pair(field_name, vectors));
1806 1807 1808 1809
            }
            default: {}
        }

G
groot 已提交
1810
        chunk_data.insert(std::make_pair(field_name, temp_data));
1811 1812
    }

G
groot 已提交
1813 1814 1815 1816
    status = request_handler_.InsertEntity(context_ptr_, collection_name->c_str(), partition_name, chunk_data);
    if (!status.ok()) {
        RETURN_STATUS_DTO(UNEXPECTED_ERROR, "Failed to insert data");
    }
1817

G
groot 已提交
1818 1819 1820 1821 1822 1823 1824
    // return generated ids
    auto pair = chunk_data.find(engine::DEFAULT_UID_NAME);
    if (pair != chunk_data.end()) {
        int64_t count = pair->second.size() / 8;
        int64_t* pdata = reinterpret_cast<int64_t*>(pair->second.data());
        for (int64_t i = 0; i < count; ++i) {
            ids_dto->ids->pushBack(std::to_string(pdata[i]).c_str());
1825 1826 1827 1828 1829 1830
        }
    }

    ASSIGN_RETURN_STATUS_DTO(status)
}

Y
yukun 已提交
1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847
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));
        }
1848 1849 1850 1851 1852 1853 1854

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

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

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

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

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

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

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

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

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

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

    ASSIGN_RETURN_STATUS_DTO(status)
}

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

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

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

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

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

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

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

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

    ASSIGN_RETURN_STATUS_DTO(status);
}

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