GrpcRequestHandler.cpp 71.0 KB
Newer Older
1
// Copyright (C) 2019-2020 Zilliz. All rights reserved.
J
jinhai 已提交
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
J
jinhai 已提交
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.
11 12 13

#include "server/grpc_impl/GrpcRequestHandler.h"

S
shengjh 已提交
14
#include <fiu-local.h>
J
JinHai-CN 已提交
15
#include <algorithm>
Z
Zhiru Zhu 已提交
16
#include <memory>
17
#include <string>
Z
Zhiru Zhu 已提交
18
#include <unordered_map>
19
#include <utility>
Z
Zhiru Zhu 已提交
20 21
#include <vector>

22 23
#include "context/HybridSearchContext.h"
#include "query/BinaryQuery.h"
G
groot 已提交
24
#include "server/context/ConnectionContext.h"
Z
Zhiru Zhu 已提交
25 26
#include "tracing/TextMapCarrier.h"
#include "tracing/TracerUtil.h"
B
BossZou 已提交
27
#include "utils/Log.h"
28
#include "utils/LogUtil.h"
K
kun yu 已提交
29 30 31 32
#include "utils/TimeRecorder.h"

namespace milvus {
namespace server {
Y
Yu Kun 已提交
33
namespace grpc {
K
kun yu 已提交
34

C
Cai Yudong 已提交
35 36
const char* EXTRA_PARAM_KEY = "params";

37 38 39 40 41 42 43 44 45 46 47 48 49
::milvus::grpc::ErrorCode
ErrorMap(ErrorCode code) {
    static const std::map<ErrorCode, ::milvus::grpc::ErrorCode> code_map = {
        {SERVER_UNEXPECTED_ERROR, ::milvus::grpc::ErrorCode::UNEXPECTED_ERROR},
        {SERVER_UNSUPPORTED_ERROR, ::milvus::grpc::ErrorCode::UNEXPECTED_ERROR},
        {SERVER_NULL_POINTER, ::milvus::grpc::ErrorCode::UNEXPECTED_ERROR},
        {SERVER_INVALID_ARGUMENT, ::milvus::grpc::ErrorCode::ILLEGAL_ARGUMENT},
        {SERVER_FILE_NOT_FOUND, ::milvus::grpc::ErrorCode::FILE_NOT_FOUND},
        {SERVER_NOT_IMPLEMENT, ::milvus::grpc::ErrorCode::UNEXPECTED_ERROR},
        {SERVER_CANNOT_CREATE_FOLDER, ::milvus::grpc::ErrorCode::CANNOT_CREATE_FOLDER},
        {SERVER_CANNOT_CREATE_FILE, ::milvus::grpc::ErrorCode::CANNOT_CREATE_FILE},
        {SERVER_CANNOT_DELETE_FOLDER, ::milvus::grpc::ErrorCode::CANNOT_DELETE_FOLDER},
        {SERVER_CANNOT_DELETE_FILE, ::milvus::grpc::ErrorCode::CANNOT_DELETE_FILE},
G
groot 已提交
50 51 52
        {SERVER_COLLECTION_NOT_EXIST, ::milvus::grpc::ErrorCode::COLLECTION_NOT_EXISTS},
        {SERVER_INVALID_COLLECTION_NAME, ::milvus::grpc::ErrorCode::ILLEGAL_COLLECTION_NAME},
        {SERVER_INVALID_COLLECTION_DIMENSION, ::milvus::grpc::ErrorCode::ILLEGAL_DIMENSION},
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
        {SERVER_INVALID_VECTOR_DIMENSION, ::milvus::grpc::ErrorCode::ILLEGAL_DIMENSION},

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

    if (code_map.find(code) != code_map.end()) {
        return code_map.at(code);
    } else {
        return ::milvus::grpc::ErrorCode::UNEXPECTED_ERROR;
    }
}

78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
std::string
RequestMap(BaseRequest::RequestType request_type) {
    static const std::unordered_map<BaseRequest::RequestType, std::string> request_map = {
        {BaseRequest::kInsert, "Insert"},
        {BaseRequest::kCreateIndex, "CreateIndex"},
        {BaseRequest::kSearch, "Search"},
        {BaseRequest::kSearchByID, "SearchByID"},
        {BaseRequest::kHybridSearch, "HybridSearch"},
        {BaseRequest::kFlush, "Flush"},
        {BaseRequest::kCompact, "Compact"},
    };

    if (request_map.find(request_type) != request_map.end()) {
        return request_map.at(request_type);
    } else {
        return "OtherRequest";
    }
}

G
groot 已提交
97 98
namespace {
void
99
CopyRowRecords(const google::protobuf::RepeatedPtrField<::milvus::grpc::VectorRowRecord>& grpc_records,
G
groot 已提交
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 135 136 137
               const google::protobuf::RepeatedField<google::protobuf::int64>& grpc_id_array,
               engine::VectorsData& vectors) {
    // step 1: copy vector data
    int64_t float_data_size = 0, binary_data_size = 0;
    for (auto& record : grpc_records) {
        float_data_size += record.float_data_size();
        binary_data_size += record.binary_data().size();
    }

    std::vector<float> float_array(float_data_size, 0.0f);
    std::vector<uint8_t> binary_array(binary_data_size, 0);
    int64_t float_offset = 0, binary_offset = 0;
    if (float_data_size > 0) {
        for (auto& record : grpc_records) {
            memcpy(&float_array[float_offset], record.float_data().data(), record.float_data_size() * sizeof(float));
            float_offset += record.float_data_size();
        }
    } else if (binary_data_size > 0) {
        for (auto& record : grpc_records) {
            memcpy(&binary_array[binary_offset], record.binary_data().data(), record.binary_data().size());
            binary_offset += record.binary_data().size();
        }
    }

    // step 2: copy id array
    std::vector<int64_t> id_array;
    if (grpc_id_array.size() > 0) {
        id_array.resize(grpc_id_array.size());
        memcpy(id_array.data(), grpc_id_array.data(), grpc_id_array.size() * sizeof(int64_t));
    }

    // step 3: contruct vectors
    vectors.vector_count_ = grpc_records.size();
    vectors.float_data_.swap(float_array);
    vectors.binary_data_.swap(binary_array);
    vectors.id_array_.swap(id_array);
}

Y
yukun 已提交
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216
void
DeSerialization(const ::milvus::grpc::GeneralQuery& general_query, query::BooleanQueryPtr& boolean_clause,
                query::QueryPtr& query_ptr) {
    if (general_query.has_boolean_query()) {
        boolean_clause->SetOccur((query::Occur)general_query.boolean_query().occur());
        for (uint64_t i = 0; i < general_query.boolean_query().general_query_size(); ++i) {
            if (general_query.boolean_query().general_query(i).has_boolean_query()) {
                query::BooleanQueryPtr query = std::make_shared<query::BooleanQuery>();
                DeSerialization(general_query.boolean_query().general_query(i), query, query_ptr);
                boolean_clause->AddBooleanQuery(query);
            } else {
                auto leaf_query = std::make_shared<query::LeafQuery>();
                auto query = general_query.boolean_query().general_query(i);
                if (query.has_term_query()) {
                    query::TermQueryPtr term_query = std::make_shared<query::TermQuery>();
                    term_query->field_name = query.term_query().field_name();
                    term_query->boost = query.term_query().boost();
                    size_t int_size = query.term_query().int_value_size();
                    size_t double_size = query.term_query().double_value_size();
                    if (int_size > 0) {
                        term_query->field_value.resize(int_size * sizeof(int64_t));
                        memcpy(term_query->field_value.data(), query.term_query().int_value().data(),
                               int_size * sizeof(int64_t));
                    } else if (double_size > 0) {
                        term_query->field_value.resize(double_size * sizeof(double));
                        memcpy(term_query->field_value.data(), query.term_query().double_value().data(),
                               double_size * sizeof(double));
                    }
                    leaf_query->term_query = term_query;
                    boolean_clause->AddLeafQuery(leaf_query);
                }
                if (query.has_range_query()) {
                    query::RangeQueryPtr range_query = std::make_shared<query::RangeQuery>();
                    range_query->field_name = query.range_query().field_name();
                    range_query->boost = query.range_query().boost();
                    range_query->compare_expr.resize(query.range_query().operand_size());
                    for (uint64_t j = 0; j < query.range_query().operand_size(); ++j) {
                        range_query->compare_expr[j].compare_operator =
                            query::CompareOperator(query.range_query().operand(j).operator_());
                        range_query->compare_expr[j].operand = query.range_query().operand(j).operand();
                    }
                    leaf_query->range_query = range_query;
                    boolean_clause->AddLeafQuery(leaf_query);
                }
                if (query.has_vector_query()) {
                    query::VectorQueryPtr vector_query = std::make_shared<query::VectorQuery>();

                    engine::VectorsData vectors;
                    CopyRowRecords(query.vector_query().records(),
                                   google::protobuf::RepeatedField<google::protobuf::int64>(), vectors);

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

                    vector_query->boost = query.vector_query().query_boost();
                    vector_query->field_name = query.vector_query().field_name();
                    vector_query->topk = query.vector_query().topk();

                    milvus::json json_params;
                    for (int j = 0; j < query.vector_query().extra_params_size(); j++) {
                        const ::milvus::grpc::KeyValuePair& extra = query.vector_query().extra_params(j);
                        if (extra.key() == EXTRA_PARAM_KEY) {
                            json_params = json::parse(extra.value());
                        }
                    }
                    vector_query->extra_params = json_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;
                    boolean_clause->AddLeafQuery(leaf_query);
                }
            }
        }
    }
}

217
void
218
ConstructResults(const TopKQueryResult& result, ::milvus::grpc::QueryResult* response) {
219 220 221 222 223 224
    if (!response) {
        return;
    }

    response->set_row_num(result.row_num_);

225 226 227
    response->mutable_entities()->mutable_ids()->Resize(static_cast<int>(result.id_list_.size()), 0);
    memcpy(response->mutable_entities()->mutable_ids()->mutable_data(), result.id_list_.data(),
           result.id_list_.size() * sizeof(int64_t));
228 229 230 231 232 233

    response->mutable_distances()->Resize(static_cast<int>(result.distance_list_.size()), 0.0);
    memcpy(response->mutable_distances()->mutable_data(), result.distance_list_.data(),
           result.distance_list_.size() * sizeof(float));
}

Y
yukun 已提交
234
void
235 236
ConstructEntityResults(const std::vector<engine::AttrsData>& attrs, const std::vector<engine::VectorsData>& vectors,
                       std::vector<std::string>& field_names, ::milvus::grpc::Entities* response) {
Y
yukun 已提交
237 238 239 240
    if (!response) {
        return;
    }

241
    if (field_names.empty()) {
Y
yukun 已提交
242 243 244 245 246 247 248 249 250 251
        if (attrs.size() > 0) {
            auto attr_it = attrs[0].attr_type_.begin();
            for (; attr_it != attrs[0].attr_type_.end(); attr_it++) {
                field_names.emplace_back(attr_it->first);
            }
        }
    }

    for (uint64_t i = 0; i < field_names.size() - 1; i++) {
        auto field_name = field_names[i];
252 253 254
        auto grpc_field = response->add_fields();

        if (!attrs.empty()) {
Y
yukun 已提交
255
            if (attrs[0].attr_type_.find(field_name) != attrs[0].attr_type_.end()) {
256
                grpc_field->set_type((::milvus::grpc::DataType)attrs[0].attr_type_.at(field_name));
Y
yukun 已提交
257 258
            }
        }
259 260 261 262 263
        auto grpc_attr_data = grpc_field->mutable_attr_record();

        std::vector<int32_t> int32_data;
        std::vector<int64_t> int64_data;
        std::vector<float> float_data;
Y
yukun 已提交
264 265 266
        std::vector<double> double_data;
        for (auto& attr : attrs) {
            auto attr_data = attr.attr_data_.at(field_name);
267 268 269
            int32_t grpc_int32_data;
            int64_t grpc_int64_data;
            float grpc_float_data;
Y
yukun 已提交
270 271 272 273
            double grpc_double_data;
            switch (attr.attr_type_.at(field_name)) {
                case engine::meta::hybrid::DataType::INT8: {
                    if (attr_data.size() == sizeof(int8_t)) {
274 275
                        grpc_int32_data = attr_data[0];
                        int32_data.emplace_back(grpc_int32_data);
Y
yukun 已提交
276 277 278 279 280 281 282 283
                    } else {
                        response->mutable_status()->set_error_code(::milvus::grpc::ErrorCode::UNEXPECTED_ERROR);
                        return;
                    }
                    break;
                }
                case engine::meta::hybrid::DataType::INT16: {
                    if (attr_data.size() == sizeof(int16_t)) {
284 285 286 287
                        int16_t value;
                        memcpy(&value, attr_data.data(), sizeof(int16_t));
                        grpc_int32_data = value;
                        int32_data.emplace_back(grpc_int32_data);
Y
yukun 已提交
288 289 290 291 292 293 294 295
                    } else {
                        response->mutable_status()->set_error_code(::milvus::grpc::ErrorCode::UNEXPECTED_ERROR);
                        return;
                    }
                    break;
                }
                case engine::meta::hybrid::DataType::INT32: {
                    if (attr_data.size() == sizeof(int32_t)) {
296 297
                        memcpy(&grpc_int32_data, attr_data.data(), sizeof(int32_t));
                        int32_data.emplace_back(grpc_int32_data);
Y
yukun 已提交
298 299 300 301 302 303 304 305
                    } else {
                        response->mutable_status()->set_error_code(::milvus::grpc::ErrorCode::UNEXPECTED_ERROR);
                        return;
                    }
                    break;
                }
                case engine::meta::hybrid::DataType::INT64: {
                    if (attr_data.size() == sizeof(int64_t)) {
306 307
                        memcpy(&grpc_int64_data, attr_data.data(), sizeof(int64_t));
                        int64_data.emplace_back(grpc_int64_data);
Y
yukun 已提交
308 309 310 311 312 313 314 315
                    } else {
                        response->mutable_status()->set_error_code(::milvus::grpc::ErrorCode::UNEXPECTED_ERROR);
                        return;
                    }
                    break;
                }
                case engine::meta::hybrid::DataType::FLOAT: {
                    if (attr_data.size() == sizeof(float)) {
316 317 318 319
                        float value;
                        memcpy(&value, attr_data.data(), sizeof(float));
                        grpc_float_data = value;
                        float_data.emplace_back(grpc_float_data);
Y
yukun 已提交
320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338
                    } else {
                        response->mutable_status()->set_error_code(::milvus::grpc::ErrorCode::UNEXPECTED_ERROR);
                        return;
                    }
                    break;
                }
                case engine::meta::hybrid::DataType::DOUBLE: {
                    if (attr_data.size() == sizeof(double)) {
                        memcpy(&grpc_double_data, attr_data.data(), sizeof(double));
                        double_data.emplace_back(grpc_double_data);
                    } else {
                        response->mutable_status()->set_error_code(::milvus::grpc::ErrorCode::UNEXPECTED_ERROR);
                        return;
                    }
                    break;
                }
                default: { break; }
            }
        }
339 340 341 342 343 344 345 346 347 348 349 350 351
        if (!int32_data.empty()) {
            grpc_attr_data->mutable_int32_value()->Resize(static_cast<int>(int32_data.size()), 0);
            memcpy(grpc_attr_data->mutable_int32_value()->mutable_data(), int32_data.data(),
                   int32_data.size() * sizeof(int32_data));
        } else if (!int64_data.empty()) {
            grpc_attr_data->mutable_int64_value()->Resize(static_cast<int>(int64_data.size()), 0);
            memcpy(grpc_attr_data->mutable_int64_value()->mutable_data(), int64_data.data(),
                   int64_data.size() * sizeof(int64_t));
        } else if (!float_data.empty()) {
            grpc_attr_data->mutable_float_value()->Resize(static_cast<int>(float_data.size()), 0.0);
            memcpy(grpc_attr_data->mutable_float_value()->mutable_data(), float_data.data(),
                   float_data.size() * sizeof(float));
        } else if (!double_data.empty()) {
Y
yukun 已提交
352 353 354 355 356 357
            grpc_attr_data->mutable_double_value()->Resize(static_cast<int>(double_data.size()), 0.0);
            memcpy(grpc_attr_data->mutable_double_value()->mutable_data(), double_data.data(),
                   double_data.size() * sizeof(double));
        }
    }

358 359
    auto grpc_field = response->add_fields();
    ::milvus::grpc::VectorRecord* grpc_vector_data = grpc_field->mutable_vector_record();
Y
yukun 已提交
360
    for (auto& vector : vectors) {
361
        auto grpc_data = grpc_vector_data->add_records();
Y
yukun 已提交
362 363 364 365 366 367 368 369 370 371 372 373
        if (!vector.float_data_.empty()) {
            grpc_data->mutable_float_data()->Resize(vector.float_data_.size(), 0);
            memcpy(grpc_data->mutable_float_data()->mutable_data(), vector.float_data_.data(),
                   vector.float_data_.size() * sizeof(float));
        } else if (!vector.binary_data_.empty()) {
            grpc_data->mutable_binary_data()->resize(vector.binary_data_.size());
            memcpy(grpc_data->mutable_binary_data()->data(), vector.binary_data_.data(),
                   vector.binary_data_.size() * sizeof(uint8_t));
        }
    }
}

G
groot 已提交
374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391
class GrpcConnectionContext : public milvus::server::ConnectionContext {
 public:
    explicit GrpcConnectionContext(::grpc::ServerContext* context) : context_(context) {
    }

    bool
    IsConnectionBroken() const override {
        if (context_ == nullptr) {
            return true;
        }

        return context_->IsCancelled();
    }

 private:
    ::grpc::ServerContext* context_ = nullptr;
};

G
groot 已提交
392 393
}  // namespace

394 395 396 397 398 399 400 401 402 403 404 405 406 407 408
namespace {

#define REQ_ID ("request_id")

std::atomic<int64_t> _sequential_id;

int64_t
get_sequential_id() {
    return _sequential_id++;
}

void
set_request_id(::grpc::ServerContext* context, const std::string& request_id) {
    if (not context) {
        // error
409
        LOG_SERVER_ERROR_ << "set_request_id: grpc::ServerContext is nullptr" << std::endl;
410 411 412 413 414 415 416 417 418 419
        return;
    }

    context->AddInitialMetadata(REQ_ID, request_id);
}

std::string
get_request_id(::grpc::ServerContext* context) {
    if (not context) {
        // error
420
        LOG_SERVER_ERROR_ << "get_request_id: grpc::ServerContext is nullptr" << std::endl;
421 422 423 424 425 426 427 428
        return "INVALID_ID";
    }

    auto server_metadata = context->server_metadata();

    auto request_id_kv = server_metadata.find(REQ_ID);
    if (request_id_kv == server_metadata.end()) {
        // error
429
        LOG_SERVER_ERROR_ << std::string(REQ_ID) << " not found in grpc.server_metadata" << std::endl;
430 431 432 433 434 435 436 437
        return "INVALID_ID";
    }

    return request_id_kv->second.data();
}

}  // namespace

Z
Zhiru Zhu 已提交
438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466
GrpcRequestHandler::GrpcRequestHandler(const std::shared_ptr<opentracing::Tracer>& tracer)
    : tracer_(tracer), random_num_generator_() {
    std::random_device random_device;
    random_num_generator_.seed(random_device());
}

void
GrpcRequestHandler::OnPostRecvInitialMetaData(
    ::grpc::experimental::ServerRpcInfo* server_rpc_info,
    ::grpc::experimental::InterceptorBatchMethods* interceptor_batch_methods) {
    std::unordered_map<std::string, std::string> text_map;
    auto* metadata_map = interceptor_batch_methods->GetRecvInitialMetadata();
    auto context_kv = metadata_map->find(tracing::TracerUtil::GetTraceContextHeaderName());
    if (context_kv != metadata_map->end()) {
        text_map[std::string(context_kv->first.data(), context_kv->first.length())] =
            std::string(context_kv->second.data(), context_kv->second.length());
    }
    // test debug mode
    //    if (std::string(server_rpc_info->method()).find("Search") != std::string::npos) {
    //        text_map["demo-debug-id"] = "debug-id";
    //    }

    tracing::TextMapCarrier carrier{text_map};
    auto span_context_maybe = tracer_->Extract(carrier);
    if (!span_context_maybe) {
        std::cerr << span_context_maybe.error().message() << std::endl;
        return;
    }
    auto span = tracer_->StartSpan(server_rpc_info->method(), {opentracing::ChildOf(span_context_maybe->get())});
467

Z
Zhiru Zhu 已提交
468 469
    auto server_context = server_rpc_info->server_context();
    auto client_metadata = server_context->client_metadata();
470 471 472

    // if client provide request_id in metadata, milvus just use it,
    // else milvus generate a sequential id.
Z
Zhiru Zhu 已提交
473 474 475 476
    std::string request_id;
    auto request_id_kv = client_metadata.find("request_id");
    if (request_id_kv != client_metadata.end()) {
        request_id = request_id_kv->second.data();
477
        LOG_SERVER_DEBUG_ << "client provide request_id: " << request_id;
478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496

        // if request_id is being used by another request,
        // convert it to request_id_n.
        std::lock_guard<std::mutex> lock(context_map_mutex_);
        if (context_map_.find(request_id) == context_map_.end()) {
            // if not found exist, mark
            context_map_[request_id] = nullptr;
        } else {
            // Finding a unused suffix
            int64_t suffix = 1;
            std::string try_request_id;
            bool exist = true;
            do {
                try_request_id = request_id + "_" + std::to_string(suffix);
                exist = context_map_.find(try_request_id) != context_map_.end();
                suffix++;
            } while (exist);
            context_map_[try_request_id] = nullptr;
        }
Z
Zhiru Zhu 已提交
497
    } else {
498 499
        request_id = std::to_string(get_sequential_id());
        set_request_id(server_context, request_id);
500
        LOG_SERVER_DEBUG_ << "milvus generate request_id: " << request_id;
Z
Zhiru Zhu 已提交
501
    }
502

Z
Zhiru Zhu 已提交
503 504 505
    auto trace_context = std::make_shared<tracing::TraceContext>(span);
    auto context = std::make_shared<Context>(request_id);
    context->SetTraceContext(trace_context);
506
    SetContext(server_rpc_info->server_context(), context);
Z
Zhiru Zhu 已提交
507 508 509 510 511
}

void
GrpcRequestHandler::OnPreSendMessage(::grpc::experimental::ServerRpcInfo* server_rpc_info,
                                     ::grpc::experimental::InterceptorBatchMethods* interceptor_batch_methods) {
512
    std::lock_guard<std::mutex> lock(context_map_mutex_);
513 514 515 516
    auto request_id = get_request_id(server_rpc_info->server_context());

    if (context_map_.find(request_id) == context_map_.end()) {
        // error
517
        LOG_SERVER_ERROR_ << "request_id " << request_id << " not found in context_map_";
518
        return;
Z
Zhiru Zhu 已提交
519
    }
520 521
    context_map_[request_id]->GetTraceContext()->GetSpan()->Finish();
    context_map_.erase(request_id);
Z
Zhiru Zhu 已提交
522 523
}

J
Jin Hai 已提交
524
std::shared_ptr<Context>
Z
Zhiru Zhu 已提交
525
GrpcRequestHandler::GetContext(::grpc::ServerContext* server_context) {
526
    std::lock_guard<std::mutex> lock(context_map_mutex_);
527
    auto request_id = get_request_id(server_context);
G
groot 已提交
528 529 530

    auto iter = context_map_.find(request_id);
    if (iter == context_map_.end()) {
531
        LOG_SERVER_ERROR_ << "GetContext: request_id " << request_id << " not found in context_map_";
532 533
        return nullptr;
    }
G
groot 已提交
534 535 536 537 538 539

    if (iter->second != nullptr) {
        ConnectionContextPtr connection_context = std::make_shared<GrpcConnectionContext>(server_context);
        iter->second->SetConnectionContext(connection_context);
    }
    return iter->second;
Z
Zhiru Zhu 已提交
540 541 542 543
}

void
GrpcRequestHandler::SetContext(::grpc::ServerContext* server_context, const std::shared_ptr<Context>& context) {
544
    std::lock_guard<std::mutex> lock(context_map_mutex_);
545 546
    auto request_id = get_request_id(server_context);
    context_map_[request_id] = context;
Z
Zhiru Zhu 已提交
547 548 549 550 551 552 553 554 555 556 557 558 559 560
}

uint64_t
GrpcRequestHandler::random_id() const {
    std::lock_guard<std::mutex> lock(random_mutex_);
    auto value = random_num_generator_();
    while (value == 0) {
        value = random_num_generator_();
    }
    return value;
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

K
kun yu 已提交
561
::grpc::Status
562
GrpcRequestHandler::CreateCollection(::grpc::ServerContext* context, const ::milvus::grpc::Mapping* request,
G
groot 已提交
563
                                     ::milvus::grpc::Status* response) {
564
    CHECK_NULLPTR_RETURN(request);
W
Wang XiangYu 已提交
565
    LOG_SERVER_INFO_ << LogOut("Request [%s] %s begin.", GetContext(context)->RequestID().c_str(), __func__);
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
    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_params;
    for (int i = 0; i < request->fields_size(); ++i) {
        auto field = request->fields(i);
        auto field_name = field.name();
        field_types.insert(std::make_pair(field_name, (engine::meta::hybrid::DataType)field.type()));

        milvus::json index_param;
        for (int j = 0; j < field.index_params_size(); j++) {
            milvus::json json_param;
            json_param[field.index_params(j).key()] = field.index_params(j).value();
            index_param.emplace_back(json_param);
        }
        field_index_params.insert(std::make_pair(field_name, index_param));

        // Currently only one extra_param
        if (request->fields(i).extra_params_size() != 0) {
            auto extra_params = std::make_pair(request->fields(i).name(), request->fields(i).extra_params(0).value());
            field_params.insert(extra_params);
        } else {
            auto extra_params = std::make_pair(request->fields(i).name(), "");
            field_params.insert(extra_params);
        }
    }

    milvus::json json_params;
    for (int i = 0; i < request->extra_params_size(); i++) {
        const ::milvus::grpc::KeyValuePair& extra = request->extra_params(i);
        if (extra.key() == EXTRA_PARAM_KEY) {
            json_params = json::parse(extra.value());
        }
    }

    Status status = request_handler_.CreateHybridCollection(GetContext(context), request->collection_name(),
                                                            field_types, field_index_params, field_params, json_params);
W
Wang XiangYu 已提交
603 604

    LOG_SERVER_INFO_ << LogOut("Request [%s] %s end.", GetContext(context)->RequestID().c_str(), __func__);
605 606
    SET_RESPONSE(response, status, context);

K
kun yu 已提交
607 608 609 610
    return ::grpc::Status::OK;
}

::grpc::Status
G
groot 已提交
611 612
GrpcRequestHandler::HasCollection(::grpc::ServerContext* context, const ::milvus::grpc::CollectionName* request,
                                  ::milvus::grpc::BoolReply* response) {
613
    CHECK_NULLPTR_RETURN(request);
W
Wang XiangYu 已提交
614
    LOG_SERVER_INFO_ << LogOut("Request [%s] %s begin.", GetContext(context)->RequestID().c_str(), __func__);
615

616
    bool has_collection = false;
617

618
    Status status = request_handler_.HasCollection(GetContext(context), request->collection_name(), has_collection);
619
    response->set_bool_reply(has_collection);
W
Wang XiangYu 已提交
620 621

    LOG_SERVER_INFO_ << LogOut("Request [%s] %s end.", GetContext(context)->RequestID().c_str(), __func__);
622 623
    SET_RESPONSE(response->mutable_status(), status, context);

K
kun yu 已提交
624 625 626 627
    return ::grpc::Status::OK;
}

::grpc::Status
G
groot 已提交
628 629
GrpcRequestHandler::DropCollection(::grpc::ServerContext* context, const ::milvus::grpc::CollectionName* request,
                                   ::milvus::grpc::Status* response) {
630
    CHECK_NULLPTR_RETURN(request);
W
Wang XiangYu 已提交
631
    LOG_SERVER_INFO_ << LogOut("Request [%s] %s begin.", GetContext(context)->RequestID().c_str(), __func__);
632

633
    Status status = request_handler_.DropCollection(GetContext(context), request->collection_name());
634

W
Wang XiangYu 已提交
635
    LOG_SERVER_INFO_ << LogOut("Request [%s] %s end.", GetContext(context)->RequestID().c_str(), __func__);
636
    SET_RESPONSE(response, status, context);
K
kun yu 已提交
637 638 639 640
    return ::grpc::Status::OK;
}

::grpc::Status
S
starlord 已提交
641 642
GrpcRequestHandler::CreateIndex(::grpc::ServerContext* context, const ::milvus::grpc::IndexParam* request,
                                ::milvus::grpc::Status* response) {
643
    CHECK_NULLPTR_RETURN(request);
W
Wang XiangYu 已提交
644
    LOG_SERVER_INFO_ << LogOut("Request [%s] %s begin.", GetContext(context)->RequestID().c_str(), __func__);
645

646 647 648 649 650 651 652 653
    milvus::json json_params;
    for (int i = 0; i < request->extra_params_size(); i++) {
        const ::milvus::grpc::KeyValuePair& extra = request->extra_params(i);
        if (extra.key() == EXTRA_PARAM_KEY) {
            json_params = json::parse(extra.value());
        }
    }

654 655
    Status status = request_handler_.CreateIndex(GetContext(context), request->collection_name(), request->field_name(),
                                                 request->index_name(), json_params);
656

W
Wang XiangYu 已提交
657
    LOG_SERVER_INFO_ << LogOut("Request [%s] %s end.", GetContext(context)->RequestID().c_str(), __func__);
658
    SET_RESPONSE(response, status, context);
K
kun yu 已提交
659 660 661 662
    return ::grpc::Status::OK;
}

::grpc::Status
663 664
GrpcRequestHandler::GetEntityByID(::grpc::ServerContext* context, const ::milvus::grpc::EntityIdentity* request,
                                  ::milvus::grpc::Entities* response) {
665
    CHECK_NULLPTR_RETURN(request);
W
Wang XiangYu 已提交
666
    LOG_SERVER_INFO_ << LogOut("Request [%s] %s begin.", GetContext(context)->RequestID().c_str(), __func__);
667

668 669 670 671 672 673
    std::vector<int64_t> vector_ids;
    vector_ids.reserve(request->id_array_size());
    for (int i = 0; i < request->id_array_size(); i++) {
        vector_ids.push_back(request->id_array(i));
    }

674
    std::vector<engine::AttrsData> attrs;
675
    std::vector<engine::VectorsData> vectors;
G
groot 已提交
676
    Status status =
677
        request_handler_.GetEntityByID(GetContext(context), request->collection_name(), vector_ids, attrs, vectors);
678

679 680
    std::vector<std::string> field_names;
    ConstructEntityResults(attrs, vectors, field_names, response);
681

W
Wang XiangYu 已提交
682
    LOG_SERVER_INFO_ << LogOut("Request [%s] %s end.", GetContext(context)->RequestID().c_str(), __func__);
683 684 685 686 687 688
    SET_RESPONSE(response->mutable_status(), status, context);

    return ::grpc::Status::OK;
}

::grpc::Status
689 690
GrpcRequestHandler::GetEntityIDs(::grpc::ServerContext* context, const ::milvus::grpc::GetEntityIDsParam* request,
                                 ::milvus::grpc::EntityIds* response) {
691
    CHECK_NULLPTR_RETURN(request);
W
Wang XiangYu 已提交
692
    LOG_SERVER_INFO_ << LogOut("Request [%s] %s begin.", GetContext(context)->RequestID().c_str(), __func__);
693 694

    std::vector<int64_t> vector_ids;
695
    Status status = request_handler_.GetVectorIDs(GetContext(context), request->collection_name(),
G
groot 已提交
696
                                                  request->segment_name(), vector_ids);
697 698

    if (!vector_ids.empty()) {
699 700
        response->mutable_entity_id_array()->Resize(vector_ids.size(), -1);
        memcpy(response->mutable_entity_id_array()->mutable_data(), vector_ids.data(),
701 702
               vector_ids.size() * sizeof(int64_t));
    }
W
Wang XiangYu 已提交
703 704

    LOG_SERVER_INFO_ << LogOut("Request [%s] %s end.", GetContext(context)->RequestID().c_str(), __func__);
705 706 707 708 709
    SET_RESPONSE(response->mutable_status(), status, context);

    return ::grpc::Status::OK;
}

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
//::grpc::Status
// GrpcRequestHandler::Search(::grpc::ServerContext* context, const ::milvus::grpc::SearchParam* request,
//                           ::milvus::grpc::QueryResult* response) {
//    CHECK_NULLPTR_RETURN(request);
//    LOG_SERVER_INFO_ << LogOut("Request [%s] %s begin.", GetContext(context)->RequestID().c_str(), __func__);
//
//    // step 1: copy vector data
//    engine::VectorsData vectors;
//    CopyRowRecords(request->query_record_array(), google::protobuf::RepeatedField<google::protobuf::int64>(),
//    vectors);
//
//    // step 2: partition tags
//    std::vector<std::string> partitions;
//    std::copy(request->partition_tag_array().begin(), request->partition_tag_array().end(),
//              std::back_inserter(partitions));
//
//    // step 3: parse extra parameters
//    milvus::json json_params;
//    for (int i = 0; i < request->extra_params_size(); i++) {
//        const ::milvus::grpc::KeyValuePair& extra = request->extra_params(i);
//        if (extra.key() == EXTRA_PARAM_KEY) {
//            json_params = json::parse(extra.value());
//        }
//    }
//
//    // step 4: search vectors
//    std::vector<std::string> file_ids;
//    TopKQueryResult result;
//    fiu_do_on("GrpcRequestHandler.Search.not_empty_file_ids", file_ids.emplace_back("test_file_id"));
//
//    Status status = request_handler_.Search(GetContext(context), request->collection_name(), vectors, request->topk(),
//                                            json_params, partitions, file_ids, result);
//
//    // step 5: construct and return result
//    ConstructResults(result, response);
//
//    LOG_SERVER_INFO_ << LogOut("Request [%s] %s end.", GetContext(context)->RequestID().c_str(), __func__);
//    SET_RESPONSE(response->mutable_status(), status, context);
//
//    return ::grpc::Status::OK;
//}
751 752 753

::grpc::Status
GrpcRequestHandler::SearchByID(::grpc::ServerContext* context, const ::milvus::grpc::SearchByIDParam* request,
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
                               ::milvus::grpc::QueryResult* response) {
    //    CHECK_NULLPTR_RETURN(request);
    //    LOG_SERVER_INFO_ << LogOut("Request [%s] %s begin.", GetContext(context)->RequestID().c_str(), __func__);
    //
    //    // step 1: partition tags
    //    std::vector<std::string> partitions;
    //    std::copy(request->partition_tag_array().begin(), request->partition_tag_array().end(),
    //              std::back_inserter(partitions));
    //
    //    // step 2: partition tags
    //    std::vector<int64_t> id_array;
    //    for (int i = 0; i < request->id_array_size(); i++) {
    //        id_array.push_back(request->id_array(i));
    //    }
    //
    //    // step 3: parse extra parameters
    //    milvus::json json_params;
    //    for (int i = 0; i < request->extra_params_size(); i++) {
    //        const ::milvus::grpc::KeyValuePair& extra = request->extra_params(i);
    //        if (extra.key() == EXTRA_PARAM_KEY) {
    //            json_params = json::parse(extra.value());
    //        }
    //    }
    //
    //    // step 4: search vectors
    //    TopKQueryResult result;
    //    Status status = request_handler_.SearchByID(GetContext(context), request->collection_name(), id_array,
    //                                                request->topk(), json_params, partitions, result);
    //
    //    // step 5: construct and return result
    //    ConstructResults(result, response);
    //
    //    LOG_SERVER_INFO_ << LogOut("Request [%s] %s end.", GetContext(context)->RequestID().c_str(), __func__);
    //    SET_RESPONSE(response->mutable_status(), status, context);
    //
    //    return ::grpc::Status::OK;
K
kun yu 已提交
790 791 792
}

::grpc::Status
S
starlord 已提交
793
GrpcRequestHandler::SearchInFiles(::grpc::ServerContext* context, const ::milvus::grpc::SearchInFilesParam* request,
794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833
                                  ::milvus::grpc::QueryResult* response) {
    //    CHECK_NULLPTR_RETURN(request);
    //    LOG_SERVER_INFO_ << LogOut("Request [%s] %s begin.", GetContext(context)->RequestID().c_str(), __func__);
    //
    //    auto* search_request = &request->search_param();
    //
    //    // step 1: copy vector data
    //    engine::VectorsData vectors;
    //    CopyRowRecords(search_request->query_record_array(),
    //    google::protobuf::RepeatedField<google::protobuf::int64>(),
    //                   vectors);
    //
    //    // step 2: copy file id array
    //    std::vector<std::string> file_ids;
    //    std::copy(request->file_id_array().begin(), request->file_id_array().end(), std::back_inserter(file_ids));
    //
    //    // step 3: partition tags
    //    std::vector<std::string> partitions;
    //    std::copy(search_request->partition_tag_array().begin(), search_request->partition_tag_array().end(),
    //              std::back_inserter(partitions));
    //
    //    // step 4: parse extra parameters
    //    milvus::json json_params;
    //    for (int i = 0; i < search_request->extra_params_size(); i++) {
    //        const ::milvus::grpc::KeyValuePair& extra = search_request->extra_params(i);
    //        if (extra.key() == EXTRA_PARAM_KEY) {
    //            json_params = json::parse(extra.value());
    //        }
    //    }
    //
    //    // step 5: search vectors
    //    TopKQueryResult result;
    //    Status status = request_handler_.Search(GetContext(context), search_request->collection_name(), vectors,
    //                                            search_request->topk(), json_params, partitions, file_ids, result);
    //
    //    // step 6: construct and return result
    //    ConstructResults(result, response);
    //
    //    LOG_SERVER_INFO_ << LogOut("Request [%s] %s end.", GetContext(context)->RequestID().c_str(), __func__);
    //    SET_RESPONSE(response->mutable_status(), status, context);
834

Y
Yu Kun 已提交
835
    return ::grpc::Status::OK;
K
kun yu 已提交
836 837 838
}

::grpc::Status
G
groot 已提交
839
GrpcRequestHandler::DescribeCollection(::grpc::ServerContext* context, const ::milvus::grpc::CollectionName* request,
840
                                       ::milvus::grpc::Mapping* response) {
W
Wang XiangYu 已提交
841
    LOG_SERVER_INFO_ << LogOut("Request [%s] %s begin.", GetContext(context)->RequestID().c_str(), __func__);
842 843 844 845
    std::unordered_map<std::string, engine::meta::hybrid::DataType> field_types;
    std::unordered_map<std::string, milvus::json> index_param;
    Status status = request_handler_.DescribeHybridCollection(GetContext(context), request->collection_name(),
                                                              field_types, index_param);
846

847 848 849 850 851 852 853 854 855 856 857 858
    response->set_collection_name(request->collection_name());
    auto field_it = field_types.begin();
    for (; field_it != field_types.end(); field_it++) {
        auto field = response->add_fields();
        field->set_name(field_it->first);
        field->set_type((milvus::grpc::DataType)field_it->second);
        for (auto& json_param : index_param.at(field_it->first).items()) {
            auto grpc_index_param = field->add_index_params();
            grpc_index_param->set_key(json_param.key());
            grpc_index_param->set_value(json_param.value());
        }
    }
859

860
    CHECK_NULLPTR_RETURN(request);
W
Wang XiangYu 已提交
861
    LOG_SERVER_INFO_ << LogOut("Request [%s] %s end.", GetContext(context)->RequestID().c_str(), __func__);
862
    SET_RESPONSE(response->mutable_status(), status, context);
K
kun yu 已提交
863 864 865 866
    return ::grpc::Status::OK;
}

::grpc::Status
G
groot 已提交
867 868
GrpcRequestHandler::CountCollection(::grpc::ServerContext* context, const ::milvus::grpc::CollectionName* request,
                                    ::milvus::grpc::CollectionRowCount* response) {
869
    CHECK_NULLPTR_RETURN(request);
W
Wang XiangYu 已提交
870
    LOG_SERVER_INFO_ << LogOut("Request [%s] %s begin.", GetContext(context)->RequestID().c_str(), __func__);
871

K
kun yu 已提交
872
    int64_t row_count = 0;
873
    Status status = request_handler_.CountCollection(GetContext(context), request->collection_name(), row_count);
G
groot 已提交
874
    response->set_collection_row_count(row_count);
W
Wang XiangYu 已提交
875 876

    LOG_SERVER_INFO_ << LogOut("Request [%s] %s end.", GetContext(context)->RequestID().c_str(), __func__);
877
    SET_RESPONSE(response->mutable_status(), status, context);
W
Wang XiangYu 已提交
878

K
kun yu 已提交
879 880 881 882
    return ::grpc::Status::OK;
}

::grpc::Status
G
groot 已提交
883 884
GrpcRequestHandler::ShowCollections(::grpc::ServerContext* context, const ::milvus::grpc::Command* request,
                                    ::milvus::grpc::CollectionNameList* response) {
885
    CHECK_NULLPTR_RETURN(request);
W
Wang XiangYu 已提交
886
    LOG_SERVER_INFO_ << LogOut("Request [%s] %s begin.", GetContext(context)->RequestID().c_str(), __func__);
887

G
groot 已提交
888
    std::vector<std::string> collections;
889
    Status status = request_handler_.ShowCollections(GetContext(context), collections);
G
groot 已提交
890 891
    for (auto& collection : collections) {
        response->add_collection_names(collection);
892
    }
W
Wang XiangYu 已提交
893 894

    LOG_SERVER_INFO_ << LogOut("Request [%s] %s end.", GetContext(context)->RequestID().c_str(), __func__);
895 896
    SET_RESPONSE(response->mutable_status(), status, context);

897
    return ::grpc::Status::OK;
K
kun yu 已提交
898 899
}

900
::grpc::Status
G
groot 已提交
901 902
GrpcRequestHandler::ShowCollectionInfo(::grpc::ServerContext* context, const ::milvus::grpc::CollectionName* request,
                                       ::milvus::grpc::CollectionInfo* response) {
903
    CHECK_NULLPTR_RETURN(request);
W
Wang XiangYu 已提交
904
    LOG_SERVER_INFO_ << LogOut("Request [%s] %s begin.", GetContext(context)->RequestID().c_str(), __func__);
905

906
    std::string collection_info;
G
groot 已提交
907
    Status status =
908
        request_handler_.ShowCollectionInfo(GetContext(context), request->collection_name(), collection_info);
909
    response->set_json_info(collection_info);
W
Wang XiangYu 已提交
910 911

    LOG_SERVER_INFO_ << LogOut("Request [%s] %s end.", GetContext(context)->RequestID().c_str(), __func__);
912 913 914 915 916
    SET_RESPONSE(response->mutable_status(), status, context);

    return ::grpc::Status::OK;
}

K
kun yu 已提交
917
::grpc::Status
S
starlord 已提交
918 919
GrpcRequestHandler::Cmd(::grpc::ServerContext* context, const ::milvus::grpc::Command* request,
                        ::milvus::grpc::StringReply* response) {
920
    CHECK_NULLPTR_RETURN(request);
W
Wang XiangYu 已提交
921
    LOG_SERVER_INFO_ << LogOut("Request [%s] %s begin.", GetContext(context)->RequestID().c_str(), __func__);
922 923

    std::string reply;
924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947
    Status status;

    std::string cmd = request->cmd();
    std::vector<std::string> requests;
    if (cmd == "requests") {
        std::lock_guard<std::mutex> lock(context_map_mutex_);
        for (auto& iter : context_map_) {
            if (nullptr == iter.second) {
                continue;
            }
            if (iter.second->RequestID() == get_request_id(context)) {
                continue;
            }
            auto request_str = RequestMap(iter.second->GetRequestType()) + "-" + iter.second->RequestID();
            requests.emplace_back(request_str);
        }
        nlohmann::json reply_json;
        reply_json["requests"] = requests;
        reply = reply_json.dump();
        response->set_string_reply(reply);
    } else {
        status = request_handler_.Cmd(GetContext(context), cmd, reply);
        response->set_string_reply(reply);
    }
W
Wang XiangYu 已提交
948 949

    LOG_SERVER_INFO_ << LogOut("Request [%s] %s end.", GetContext(context)->RequestID().c_str(), __func__);
950 951
    SET_RESPONSE(response->mutable_status(), status, context);

K
kun yu 已提交
952 953 954
    return ::grpc::Status::OK;
}

Y
Yu Kun 已提交
955
::grpc::Status
956 957
GrpcRequestHandler::DeleteByID(::grpc::ServerContext* context, const ::milvus::grpc::DeleteByIDParam* request,
                               ::milvus::grpc::Status* response) {
958
    CHECK_NULLPTR_RETURN(request);
W
Wang XiangYu 已提交
959
    LOG_SERVER_INFO_ << LogOut("Request [%s] %s begin.", GetContext(context)->RequestID().c_str(), __func__);
960

961 962 963 964 965 966 967
    // step 1: prepare id array
    std::vector<int64_t> vector_ids;
    for (int i = 0; i < request->id_array_size(); i++) {
        vector_ids.push_back(request->id_array(i));
    }

    // step 2: delete vector
968
    Status status = request_handler_.DeleteByID(GetContext(context), request->collection_name(), vector_ids);
W
Wang XiangYu 已提交
969 970

    LOG_SERVER_INFO_ << LogOut("Request [%s] %s end.", GetContext(context)->RequestID().c_str(), __func__);
971 972
    SET_RESPONSE(response, status, context);

973
    return ::grpc::Status::OK;
Y
Yu Kun 已提交
974 975 976
}

::grpc::Status
G
groot 已提交
977 978
GrpcRequestHandler::PreloadCollection(::grpc::ServerContext* context, const ::milvus::grpc::CollectionName* request,
                                      ::milvus::grpc::Status* response) {
979
    CHECK_NULLPTR_RETURN(request);
W
Wang XiangYu 已提交
980
    LOG_SERVER_INFO_ << LogOut("Request [%s] %s begin.", GetContext(context)->RequestID().c_str(), __func__);
981

982
    Status status = request_handler_.PreloadCollection(GetContext(context), request->collection_name());
W
Wang XiangYu 已提交
983 984

    LOG_SERVER_INFO_ << LogOut("Request [%s] %s end.", GetContext(context)->RequestID().c_str(), __func__);
985
    SET_RESPONSE(response, status, context);
986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004

    return ::grpc::Status::OK;
}

::grpc::Status
GrpcRequestHandler::ReloadSegments(::grpc::ServerContext* context, const ::milvus::grpc::ReLoadSegmentsParam* request,
                                   ::milvus::grpc::Status* response) {
    CHECK_NULLPTR_RETURN(request);
    LOG_SERVER_INFO_ << LogOut("Request [%s] %s begin.", GetContext(context)->RequestID().c_str(), __func__);

    std::vector<std::string> file_ids;
    for (size_t i = 0; i < request->segment_id_array_size(); i++) {
        file_ids.push_back(request->segment_id_array(i));
    }

    Status status = request_handler_.ReLoadSegments(GetContext(context), request->collection_name(), file_ids);

    LOG_SERVER_INFO_ << LogOut("Request [%s] %s end.", GetContext(context)->RequestID().c_str(), __func__);
    SET_RESPONSE(response, status, context);
1005

Y
Yu Kun 已提交
1006
    return ::grpc::Status::OK;
Y
Yu Kun 已提交
1007 1008 1009
}

::grpc::Status
G
groot 已提交
1010
GrpcRequestHandler::DescribeIndex(::grpc::ServerContext* context, const ::milvus::grpc::CollectionName* request,
S
starlord 已提交
1011
                                  ::milvus::grpc::IndexParam* response) {
1012
    CHECK_NULLPTR_RETURN(request);
W
Wang XiangYu 已提交
1013
    LOG_SERVER_INFO_ << LogOut("Request [%s] %s begin.", GetContext(context)->RequestID().c_str(), __func__);
1014 1015

    IndexParam param;
1016
    Status status = request_handler_.DescribeIndex(GetContext(context), request->collection_name(), param);
G
groot 已提交
1017
    response->set_collection_name(param.collection_name_);
1018
    response->set_index_name(param.index_name_);
1019 1020 1021
    ::milvus::grpc::KeyValuePair* kv = response->add_extra_params();
    kv->set_key(EXTRA_PARAM_KEY);
    kv->set_value(param.extra_params_);
W
Wang XiangYu 已提交
1022 1023

    LOG_SERVER_INFO_ << LogOut("Request [%s] %s end.", GetContext(context)->RequestID().c_str(), __func__);
1024 1025
    SET_RESPONSE(response->mutable_status(), status, context);

1026
    return ::grpc::Status::OK;
Y
Yu Kun 已提交
1027 1028 1029
}

::grpc::Status
1030
GrpcRequestHandler::DropIndex(::grpc::ServerContext* context, const ::milvus::grpc::IndexParam* request,
S
starlord 已提交
1031
                              ::milvus::grpc::Status* response) {
1032
    CHECK_NULLPTR_RETURN(request);
W
Wang XiangYu 已提交
1033
    LOG_SERVER_INFO_ << LogOut("Request [%s] %s begin.", GetContext(context)->RequestID().c_str(), __func__);
1034

1035
    Status status = request_handler_.DropIndex(GetContext(context), request->collection_name());
W
Wang XiangYu 已提交
1036 1037

    LOG_SERVER_INFO_ << LogOut("Request [%s] %s end.", GetContext(context)->RequestID().c_str(), __func__);
1038 1039
    SET_RESPONSE(response, status, context);

1040
    return ::grpc::Status::OK;
Y
Yu Kun 已提交
1041 1042
}

G
groot 已提交
1043 1044 1045
::grpc::Status
GrpcRequestHandler::CreatePartition(::grpc::ServerContext* context, const ::milvus::grpc::PartitionParam* request,
                                    ::milvus::grpc::Status* response) {
1046
    CHECK_NULLPTR_RETURN(request);
W
Wang XiangYu 已提交
1047
    LOG_SERVER_INFO_ << LogOut("Request [%s] %s begin.", GetContext(context)->RequestID().c_str(), __func__);
1048

1049
    Status status = request_handler_.CreatePartition(GetContext(context), request->collection_name(), request->tag());
W
Wang XiangYu 已提交
1050 1051

    LOG_SERVER_INFO_ << LogOut("Request [%s] %s end.", GetContext(context)->RequestID().c_str(), __func__);
1052 1053
    SET_RESPONSE(response, status, context);

G
groot 已提交
1054 1055 1056
    return ::grpc::Status::OK;
}

1057 1058 1059 1060
::grpc::Status
GrpcRequestHandler::HasPartition(::grpc::ServerContext* context, const ::milvus::grpc::PartitionParam* request,
                                 ::milvus::grpc::BoolReply* response) {
    CHECK_NULLPTR_RETURN(request);
W
Wang XiangYu 已提交
1061
    LOG_SERVER_INFO_ << LogOut("Request [%s] %s begin.", GetContext(context)->RequestID().c_str(), __func__);
1062 1063 1064 1065 1066 1067

    bool has_collection = false;

    Status status =
        request_handler_.HasPartition(GetContext(context), request->collection_name(), request->tag(), has_collection);
    response->set_bool_reply(has_collection);
W
Wang XiangYu 已提交
1068 1069

    LOG_SERVER_INFO_ << LogOut("Request [%s] %s end.", GetContext(context)->RequestID().c_str(), __func__);
1070 1071 1072 1073 1074
    SET_RESPONSE(response->mutable_status(), status, context);

    return ::grpc::Status::OK;
}

G
groot 已提交
1075
::grpc::Status
G
groot 已提交
1076
GrpcRequestHandler::ShowPartitions(::grpc::ServerContext* context, const ::milvus::grpc::CollectionName* request,
G
groot 已提交
1077
                                   ::milvus::grpc::PartitionList* response) {
1078
    CHECK_NULLPTR_RETURN(request);
W
Wang XiangYu 已提交
1079
    LOG_SERVER_INFO_ << LogOut("Request [%s] %s begin.", GetContext(context)->RequestID().c_str(), __func__);
1080 1081

    std::vector<PartitionParam> partitions;
1082
    Status status = request_handler_.ShowPartitions(GetContext(context), request->collection_name(), partitions);
1083
    for (auto& partition : partitions) {
1084
        response->add_partition_tag_array(partition.tag_);
1085 1086
    }

W
Wang XiangYu 已提交
1087
    LOG_SERVER_INFO_ << LogOut("Request [%s] %s end.", GetContext(context)->RequestID().c_str(), __func__);
1088 1089
    SET_RESPONSE(response->mutable_status(), status, context);

G
groot 已提交
1090 1091 1092 1093 1094 1095
    return ::grpc::Status::OK;
}

::grpc::Status
GrpcRequestHandler::DropPartition(::grpc::ServerContext* context, const ::milvus::grpc::PartitionParam* request,
                                  ::milvus::grpc::Status* response) {
1096
    CHECK_NULLPTR_RETURN(request);
W
Wang XiangYu 已提交
1097
    LOG_SERVER_INFO_ << LogOut("Request [%s] %s begin.", GetContext(context)->RequestID().c_str(), __func__);
1098

1099
    Status status = request_handler_.DropPartition(GetContext(context), request->collection_name(), request->tag());
W
Wang XiangYu 已提交
1100 1101

    LOG_SERVER_INFO_ << LogOut("Request [%s] %s end.", GetContext(context)->RequestID().c_str(), __func__);
1102 1103 1104 1105 1106 1107 1108 1109 1110
    SET_RESPONSE(response, status, context);

    return ::grpc::Status::OK;
}

::grpc::Status
GrpcRequestHandler::Flush(::grpc::ServerContext* context, const ::milvus::grpc::FlushParam* request,
                          ::milvus::grpc::Status* response) {
    CHECK_NULLPTR_RETURN(request);
W
Wang XiangYu 已提交
1111
    LOG_SERVER_INFO_ << LogOut("Request [%s] %s begin.", GetContext(context)->RequestID().c_str(), __func__);
1112

J
Jin Hai 已提交
1113
    std::vector<std::string> collection_names;
G
groot 已提交
1114 1115
    for (int32_t i = 0; i < request->collection_name_array().size(); i++) {
        collection_names.push_back(request->collection_name_array(i));
1116
    }
1117
    Status status = request_handler_.Flush(GetContext(context), collection_names);
W
Wang XiangYu 已提交
1118 1119

    LOG_SERVER_INFO_ << LogOut("Request [%s] %s end.", GetContext(context)->RequestID().c_str(), __func__);
1120 1121 1122 1123 1124 1125
    SET_RESPONSE(response, status, context);

    return ::grpc::Status::OK;
}

::grpc::Status
G
groot 已提交
1126
GrpcRequestHandler::Compact(::grpc::ServerContext* context, const ::milvus::grpc::CollectionName* request,
1127 1128
                            ::milvus::grpc::Status* response) {
    CHECK_NULLPTR_RETURN(request);
W
Wang XiangYu 已提交
1129
    LOG_SERVER_INFO_ << LogOut("Request [%s] %s begin.", GetContext(context)->RequestID().c_str(), __func__);
1130

G
groot 已提交
1131 1132
    double compact_threshold = 0.1;  // compact trigger threshold: delete_counts/segment_counts
    Status status = request_handler_.Compact(GetContext(context), request->collection_name(), compact_threshold);
W
Wang XiangYu 已提交
1133 1134

    LOG_SERVER_INFO_ << LogOut("Request [%s] %s end.", GetContext(context)->RequestID().c_str(), __func__);
1135 1136
    SET_RESPONSE(response, status, context);

G
groot 已提交
1137 1138 1139
    return ::grpc::Status::OK;
}

1140 1141 1142
/*******************************************New Interface*********************************************/

::grpc::Status
1143 1144
GrpcRequestHandler::Insert(::grpc::ServerContext* context, const ::milvus::grpc::InsertParam* request,
                           ::milvus::grpc::EntityIds* response) {
Y
yukun 已提交
1145 1146 1147
    //    engine::VectorsData vectors;
    //    CopyRowRecords(request->entity().vector_data(0).value(), request->entity_id_array(), vectors);

1148
    CHECK_NULLPTR_RETURN(request);
W
Wang XiangYu 已提交
1149
    LOG_SERVER_INFO_ << LogOut("Request [%s] %s begin.", GetContext(context)->RequestID().c_str(), __func__);
1150

1151
    auto field_size = request->fields_size();
1152

1153
    std::unordered_map<std::string, engine::VectorsData> vectors;
1154
    std::vector<std::string> field_names;
1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 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

    std::vector<int64_t> offsets;
    std::vector<std::vector<uint8_t>> attr_datas(field_size);
    uint64_t row_num;
    for (int i = 0; i < field_size; i++) {
        auto grpc_int32_size = request->fields(i).attr_record().int32_value_size();
        auto grpc_int64_size = request->fields(i).attr_record().int64_value_size();
        auto grpc_float_size = request->fields(i).attr_record().float_value_size();
        auto grpc_double_size = request->fields(i).attr_record().double_value_size();
        const auto& field = request->fields(i);
        auto field_name = field.field_name();

        field_names.emplace_back(field_name);
        std::vector<uint8_t> temp_data;
        if (grpc_int32_size > 0) {
            temp_data.resize(grpc_int32_size * sizeof(int32_t));
            memcpy(temp_data.data(), field.attr_record().int32_value().data(), grpc_int32_size * sizeof(int32_t));
            offsets.emplace_back(grpc_int32_size * sizeof(int32_t));
        } else if (grpc_int64_size > 0) {
            temp_data.resize(grpc_int64_size * sizeof(int64_t));
            memcpy(temp_data.data(), field.attr_record().int64_value().data(), grpc_int64_size * sizeof(int64_t));
            offsets.emplace_back(grpc_int64_size * sizeof(int64_t));
        } else if (grpc_float_size > 0) {
            temp_data.resize(grpc_float_size * sizeof(float));
            memcpy(temp_data.data(), field.attr_record().float_value().data(), grpc_float_size * sizeof(float));
            offsets.emplace_back(grpc_float_size * sizeof(float));
        } else if (grpc_double_size > 0) {
            temp_data.resize(grpc_double_size * sizeof(double));
            memcpy(temp_data.data(), field.attr_record().double_value().data(), grpc_double_size * sizeof(double));
            offsets.emplace_back(grpc_double_size * sizeof(double));
        } else {
            // vector field
            engine::VectorsData vector_data;
            CopyRowRecords(field.vector_record().records(), request->entity_id_array(), vector_data);
            vectors.insert(std::make_pair(field_name, vector_data));
            row_num = field.vector_record().records_size();
            break;
        }
        attr_datas.emplace_back(temp_data);
1194 1195
    }

1196 1197 1198 1199 1200 1201
    auto attr_size = std::accumulate(offsets.begin(), offsets.end(), decltype(offsets)::value_type(0));
    std::vector<uint8_t> attr_data(attr_size);
    int64_t offset = 0;
    for (auto& attr : attr_datas) {
        memcpy(attr_data.data() + offset, attr.data(), attr.size());
        offset += attr.size();
1202 1203 1204 1205
    }

    std::string collection_name = request->collection_name();
    std::string partition_tag = request->partition_tag();
1206
    Status status = request_handler_.InsertEntity(GetContext(context), collection_name, partition_tag, row_num,
1207
                                                  field_names, attr_data, vectors);
1208

1209 1210 1211
    response->mutable_entity_id_array()->Resize(static_cast<int>(vectors.begin()->second.id_array_.size()), 0);
    memcpy(response->mutable_entity_id_array()->mutable_data(), vectors.begin()->second.id_array_.data(),
           vectors.begin()->second.id_array_.size() * sizeof(int64_t));
1212

W
Wang XiangYu 已提交
1213
    LOG_SERVER_INFO_ << LogOut("Request [%s] %s end.", GetContext(context)->RequestID().c_str(), __func__);
1214
    SET_RESPONSE(response->mutable_status(), status, context);
W
Wang XiangYu 已提交
1215

1216 1217 1218
    return ::grpc::Status::OK;
}

Y
yukun 已提交
1219
::grpc::Status
1220 1221
GrpcRequestHandler::SearchPB(::grpc::ServerContext* context, const ::milvus::grpc::SearchParamPB* request,
                             ::milvus::grpc::QueryResult* response) {
Y
yukun 已提交
1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235
    CHECK_NULLPTR_RETURN(request);
    LOG_SERVER_INFO_ << LogOut("Request [%s] %s begin.", GetContext(context)->RequestID().c_str(), __func__);

    auto boolean_query = std::make_shared<query::BooleanQuery>();
    auto query_ptr = std::make_shared<query::Query>();
    DeSerialization(request->general_query(), boolean_query, query_ptr);

    auto general_query = std::make_shared<query::GeneralQuery>();
    query::GenBinaryQuery(boolean_query, general_query->bin);

    Status status;

    if (!query::ValidateBinaryQuery(general_query->bin)) {
        status = Status{SERVER_INVALID_BINARY_QUERY, "Generate wrong binary query tree"};
1236
        SET_RESPONSE(response->mutable_entities()->mutable_status(), status, context)
Y
yukun 已提交
1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260
        return ::grpc::Status::OK;
    }

    std::vector<std::string> partition_list;
    partition_list.resize(request->partition_tag_array_size());
    for (uint64_t i = 0; i < request->partition_tag_array_size(); ++i) {
        partition_list[i] = request->partition_tag_array(i);
    }

    milvus::json json_params;
    for (int i = 0; i < request->extra_params_size(); i++) {
        const ::milvus::grpc::KeyValuePair& extra = request->extra_params(i);
        if (extra.key() == EXTRA_PARAM_KEY) {
            json_params = json::parse(extra.value());
        }
    }

    engine::QueryResult result;
    std::vector<std::string> field_names;
    status = request_handler_.HybridSearch(GetContext(context), request->collection_name(), partition_list,
                                           general_query, query_ptr, json_params, field_names, result);

    // step 6: construct and return result
    response->set_row_num(result.row_num_);
1261 1262 1263 1264
    auto grpc_entity = response->mutable_entities();
    ConstructEntityResults(result.attrs_, result.vectors_, field_names, grpc_entity);
    grpc_entity->mutable_ids()->Resize(static_cast<int>(result.result_ids_.size()), 0);
    memcpy(grpc_entity->mutable_ids()->mutable_data(), result.result_ids_.data(),
Y
yukun 已提交
1265 1266
           result.result_ids_.size() * sizeof(int64_t));

1267 1268
    response->mutable_distances()->Resize(static_cast<int>(result.result_distances_.size()), 0.0);
    memcpy(response->mutable_distances()->mutable_data(), result.result_distances_.data(),
Y
yukun 已提交
1269 1270 1271
           result.result_distances_.size() * sizeof(float));

    LOG_SERVER_INFO_ << LogOut("Request [%s] %s end.", GetContext(context)->RequestID().c_str(), __func__);
1272
    SET_RESPONSE(grpc_entity->mutable_status(), status, context);
Y
yukun 已提交
1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421

    return ::grpc::Status::OK;
}

Status
ParseTermQuery(const nlohmann::json& term_json,
               std::unordered_map<std::string, engine::meta::hybrid::DataType> field_type,
               query::TermQueryPtr& term_query) {
    std::string field_name = term_json["field_name"].get<std::string>();
    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{SERVER_INVALID_DSL_PARAMETER, msg};
    }

    auto term_size = term_value_json.size();
    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: {
            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<int8_t>();
            }
            memcpy(term_query->field_value.data(), term_value.data(), term_size * sizeof(int64_t));
            break;
        }
        case engine::meta::hybrid::DataType::INT16: {
            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<int16_t>();
            }
            memcpy(term_query->field_value.data(), term_value.data(), term_size * sizeof(int64_t));
            break;
        }
        case engine::meta::hybrid::DataType::INT32: {
            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<int32_t>();
            }
            memcpy(term_query->field_value.data(), term_value.data(), term_size * sizeof(int64_t));
            break;
        }
        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: {
            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<float>();
            }
            memcpy(term_query->field_value.data(), term_value.data(), term_size * sizeof(double));
            break;
        }
        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;
        }
    }
    return Status::OK();
}

Status
ParseRangeQuery(const nlohmann::json& range_json, query::RangeQueryPtr& range_query) {
    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);
    }
    return Status::OK();
}

Status
GrpcRequestHandler::ProcessLeafQueryJson(const nlohmann::json& json, query::BooleanQueryPtr& query) {
    auto status = Status::OK();
    if (json.contains("term")) {
        auto leaf_query = std::make_shared<query::LeafQuery>();
        auto term_json = json["term"];
        auto term_query = std::make_shared<query::TermQuery>();
        status = ParseTermQuery(term_json, field_type_, term_query);

        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"];
        status = ParseRangeQuery(range_json, range_query);

        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_json = json["vector"];

        leaf_query->vector_placeholder = vector_json.get<std::string>();
        query->AddLeafQuery(leaf_query);
    }
    return status;
}

Status
GrpcRequestHandler::ProcessBooleanQueryJson(const nlohmann::json& query_json, query::BooleanQueryPtr& boolean_query) {
    auto status = Status::OK();
Y
yukun 已提交
1422 1423 1424 1425 1426 1427 1428 1429
    for (auto& el : query_json.items()) {
        if (el.key() == "must") {
            boolean_query->SetOccur(query::Occur::MUST);
            auto must_json = el.value();
            if (!must_json.is_array()) {
                std::string msg = "Must json string is not an array";
                return Status{SERVER_INVALID_DSL_PARAMETER, msg};
            }
Y
yukun 已提交
1430

Y
yukun 已提交
1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443
            for (auto& json : must_json) {
                auto must_query = std::make_shared<query::BooleanQuery>();
                if (json.contains("must") || json.contains("should") || json.contains("must_not")) {
                    status = ProcessBooleanQueryJson(json, must_query);
                    if (!status.ok()) {
                        return status;
                    }
                    boolean_query->AddBooleanQuery(must_query);
                } else {
                    status = ProcessLeafQueryJson(json, boolean_query);
                    if (!status.ok()) {
                        return status;
                    }
1444
                }
Y
yukun 已提交
1445
            }
Y
yukun 已提交
1446 1447 1448 1449 1450 1451 1452
        } else if (el.key() == "should") {
            boolean_query->SetOccur(query::Occur::SHOULD);
            auto should_json = el.value();
            if (!should_json.is_array()) {
                std::string msg = "Should json string is not an array";
                return Status{SERVER_INVALID_DSL_PARAMETER, msg};
            }
Y
yukun 已提交
1453

Y
yukun 已提交
1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466
            for (auto& json : should_json) {
                auto should_query = std::make_shared<query::BooleanQuery>();
                if (json.contains("must") || json.contains("should") || json.contains("must_not")) {
                    status = ProcessBooleanQueryJson(json, should_query);
                    if (!status.ok()) {
                        return status;
                    }
                    boolean_query->AddBooleanQuery(should_query);
                } else {
                    status = ProcessLeafQueryJson(json, boolean_query);
                    if (!status.ok()) {
                        return status;
                    }
Y
yukun 已提交
1467 1468
                }
            }
Y
yukun 已提交
1469 1470 1471 1472 1473 1474 1475
        } else if (el.key() == "must_not") {
            boolean_query->SetOccur(query::Occur::MUST_NOT);
            auto should_json = el.value();
            if (!should_json.is_array()) {
                std::string msg = "Must_not json string is not an array";
                return Status{SERVER_INVALID_DSL_PARAMETER, msg};
            }
1476

Y
yukun 已提交
1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489
            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>();
                    status = ProcessBooleanQueryJson(json, must_not_query);
                    if (!status.ok()) {
                        return status;
                    }
                    boolean_query->AddBooleanQuery(must_not_query);
                } else {
                    status = ProcessLeafQueryJson(json, boolean_query);
                    if (!status.ok()) {
                        return status;
                    }
Y
yukun 已提交
1490 1491
                }
            }
Y
yukun 已提交
1492 1493 1494
        } else {
            std::string msg = "Must json string doesnot include right query";
            return Status{SERVER_INVALID_DSL_PARAMETER, msg};
Y
yukun 已提交
1495 1496
        }
    }
1497

Y
yukun 已提交
1498 1499
    return status;
}
1500

Y
yukun 已提交
1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520
Status
GrpcRequestHandler::DeserializeJsonToBoolQuery(
    const google::protobuf::RepeatedPtrField<::milvus::grpc::VectorParam>& vector_params, const std::string& dsl_string,
    query::BooleanQueryPtr& boolean_query, std::unordered_map<std::string, query::VectorQueryPtr>& vectors) {
    nlohmann::json dsl_json = json::parse(dsl_string);

    try {
        auto status = Status::OK();
        for (size_t i = 0; i < vector_params.size(); i++) {
            std::string vector_string = vector_params.at(i).json();
            nlohmann::json vector_json = json::parse(vector_string);
            json::iterator it = vector_json.begin();
            std::string placeholder = it.key();

            auto vector_query = std::make_shared<query::VectorQuery>();
            vector_query->topk = it.value()["topk"].get<int64_t>();
            vector_query->field_name = it.value()["field_name"].get<std::string>();
            vector_query->extra_params = it.value()["params"];

            engine::VectorsData vector_data;
1521 1522
            CopyRowRecords(vector_params.at(i).row_record().records(),
                           google::protobuf::RepeatedField<google::protobuf::int64>(), vector_data);
Y
yukun 已提交
1523 1524 1525 1526 1527
            vector_query->query_vector.binary_data = vector_data.binary_data_;
            vector_query->query_vector.float_data = vector_data.float_data_;

            vectors.insert(std::make_pair(placeholder, vector_query));
        }
1528

Y
yukun 已提交
1529 1530 1531 1532 1533
        if (dsl_json.contains("bool")) {
            auto boolean_query_json = dsl_json["bool"];
            status = ProcessBooleanQueryJson(boolean_query_json, boolean_query);
            if (!status.ok()) {
                return status;
1534 1535
            }
        }
Y
yukun 已提交
1536 1537 1538
        return status;
    } catch (std::exception& e) {
        return Status{SERVER_INVALID_DSL_PARAMETER, e.what()};
1539 1540 1541 1542
    }
}

::grpc::Status
1543 1544
GrpcRequestHandler::Search(::grpc::ServerContext* context, const ::milvus::grpc::SearchParam* request,
                           ::milvus::grpc::QueryResult* response) {
1545
    CHECK_NULLPTR_RETURN(request);
W
Wang XiangYu 已提交
1546
    LOG_SERVER_INFO_ << LogOut("Request [%s] %s begin.", GetContext(context)->RequestID().c_str(), __func__);
1547

Y
yukun 已提交
1548 1549
    Status status;

1550 1551 1552 1553 1554
    std::unordered_map<std::string, milvus::json> index_params;
    status = request_handler_.DescribeHybridCollection(GetContext(context), request->collection_name(), field_type_,
                                                       index_params);

    auto grpc_entity = response->mutable_entities();
Y
yukun 已提交
1555
    if (!status.ok()) {
1556
        SET_RESPONSE(grpc_entity->mutable_status(), status, context);
Y
yukun 已提交
1557 1558
        return ::grpc::Status::OK;
    }
1559 1560

    query::BooleanQueryPtr boolean_query = std::make_shared<query::BooleanQuery>();
Y
yukun 已提交
1561 1562 1563 1564 1565
    query::QueryPtr query_ptr = std::make_shared<query::Query>();
    std::unordered_map<std::string, query::VectorQueryPtr> vectors;

    DeserializeJsonToBoolQuery(request->vector_param(), request->dsl(), boolean_query, vectors);

Y
yukun 已提交
1566 1567
    status = query::ValidateBooleanQuery(boolean_query);
    if (!status.ok()) {
1568
        SET_RESPONSE(grpc_entity->mutable_status(), status, context);
Y
yukun 已提交
1569 1570 1571
        return ::grpc::Status::OK;
    }

Y
yukun 已提交
1572
    query_ptr->vectors = vectors;
1573 1574 1575

    query::GeneralQueryPtr general_query = std::make_shared<query::GeneralQuery>();
    query::GenBinaryQuery(boolean_query, general_query->bin);
Y
yukun 已提交
1576
    query_ptr->root = general_query->bin;
1577 1578 1579

    if (!query::ValidateBinaryQuery(general_query->bin)) {
        status = Status{SERVER_INVALID_BINARY_QUERY, "Generate wrong binary query tree"};
1580
        SET_RESPONSE(grpc_entity->mutable_status(), status, context);
1581 1582 1583 1584 1585
        return ::grpc::Status::OK;
    }

    std::vector<std::string> partition_list;
    partition_list.resize(request->partition_tag_array_size());
C
Cai Yudong 已提交
1586
    for (int i = 0; i < request->partition_tag_array_size(); ++i) {
1587 1588 1589
        partition_list[i] = request->partition_tag_array(i);
    }

Y
yukun 已提交
1590 1591 1592 1593 1594 1595 1596
    milvus::json json_params;
    for (int i = 0; i < request->extra_params_size(); i++) {
        const ::milvus::grpc::KeyValuePair& extra = request->extra_params(i);
        if (extra.key() == EXTRA_PARAM_KEY) {
            json_params = json::parse(extra.value());
        }
    }
1597

Y
yukun 已提交
1598 1599
    engine::QueryResult result;
    std::vector<std::string> field_names;
Y
yukun 已提交
1600 1601
    status = request_handler_.HybridSearch(GetContext(context), request->collection_name(), partition_list,
                                           general_query, query_ptr, json_params, field_names, result);
1602 1603

    // step 6: construct and return result
Y
yukun 已提交
1604
    response->set_row_num(result.row_num_);
1605 1606 1607 1608
    ConstructEntityResults(result.attrs_, result.vectors_, field_names, grpc_entity);

    grpc_entity->mutable_ids()->Resize(static_cast<int>(result.result_ids_.size()), 0);
    memcpy(grpc_entity->mutable_ids()->mutable_data(), result.result_ids_.data(),
Y
yukun 已提交
1609 1610
           result.result_ids_.size() * sizeof(int64_t));

1611 1612
    response->mutable_distances()->Resize(static_cast<int>(result.result_distances_.size()), 0.0);
    memcpy(response->mutable_distances()->mutable_data(), result.result_distances_.data(),
Y
yukun 已提交
1613 1614 1615
           result.result_distances_.size() * sizeof(float));

    LOG_SERVER_INFO_ << LogOut("Request [%s] %s end.", GetContext(context)->RequestID().c_str(), __func__);
1616
    SET_RESPONSE(grpc_entity->mutable_status(), status, context);
Y
yukun 已提交
1617 1618 1619 1620

    return ::grpc::Status::OK;
}

S
starlord 已提交
1621 1622 1623
}  // namespace grpc
}  // namespace server
}  // namespace milvus