GrpcRequestHandler.cpp 74.4 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"
F
fishpenguin 已提交
24
#include "server/ValidationUtil.h"
F
fishpenguin 已提交
25
#include "server/context/ConnectionContext.h"
Z
Zhiru Zhu 已提交
26 27
#include "tracing/TextMapCarrier.h"
#include "tracing/TracerUtil.h"
B
BossZou 已提交
28
#include "utils/Log.h"
29
#include "utils/LogUtil.h"
K
kun yu 已提交
30 31 32 33
#include "utils/TimeRecorder.h"

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

C
Cai Yudong 已提交
36
const char* EXTRA_PARAM_KEY = "params";
37
const size_t MAXIMUM_FIELD_NUM = 64;
C
Cai Yudong 已提交
38

39 40 41 42 43 44 45 46 47 48 49 50 51
::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 已提交
52 53 54
        {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},
55
        {SERVER_INVALID_VECTOR_DIMENSION, ::milvus::grpc::ErrorCode::ILLEGAL_DIMENSION},
56 57
        {SERVER_INVALID_FIELD_NAME, ::milvus::grpc::ErrorCode::ILLEGAL_ARGUMENT},
        {SERVER_INVALID_FIELD_NUM, ::milvus::grpc::ErrorCode::ILLEGAL_ARGUMENT},
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81

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

82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
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 已提交
101 102
namespace {
void
103
CopyRowRecords(const google::protobuf::RepeatedPtrField<::milvus::grpc::VectorRowRecord>& grpc_records,
G
groot 已提交
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 138 139 140 141
               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 已提交
142 143 144 145 146 147 148 149 150 151 152 153 154
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);
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
                //                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);
                //                }
Y
yukun 已提交
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 217 218 219 220 221 222
                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);
                }
            }
        }
    }
}

223
void
224
ConstructResults(const TopKQueryResult& result, ::milvus::grpc::QueryResult* response) {
225 226 227 228 229 230
    if (!response) {
        return;
    }

    response->set_row_num(result.row_num_);

231 232 233
    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));
234 235 236 237 238 239

    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 已提交
240
void
241 242
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 已提交
243 244 245 246
    if (!response) {
        return;
    }

F
fishpenguin 已提交
247 248 249 250 251 252 253 254
    //    if (field_names.empty()) {
    //        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);
    //            }
    //        }
    //    }
Y
yukun 已提交
255

F
fishpenguin 已提交
256 257
    std::string vector_field_name;
    for (uint64_t i = 0; i < field_names.size(); i++) {
Y
yukun 已提交
258
        auto field_name = field_names[i];
259
        if (!attrs.empty()) {
Y
yukun 已提交
260
            if (attrs[0].attr_type_.find(field_name) != attrs[0].attr_type_.end()) {
F
fishpenguin 已提交
261 262
                auto grpc_field = response->add_fields();
                grpc_field->set_field_name(field_name);
263
                grpc_field->set_type((::milvus::grpc::DataType)attrs[0].attr_type_.at(field_name));
F
fishpenguin 已提交
264 265 266 267 268 269 270
                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;
                std::vector<double> double_data;
                for (auto& attr : attrs) {
F
fishpenguin 已提交
271 272 273
                    if (attr.attr_data_.find(field_name) == attr.attr_data_.end()) {
                        continue;
                    }
F
fishpenguin 已提交
274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344
                    auto attr_data = attr.attr_data_.at(field_name);
                    int32_t grpc_int32_data;
                    int64_t grpc_int64_data;
                    float grpc_float_data;
                    double grpc_double_data;
                    switch (attr.attr_type_.at(field_name)) {
                        case engine::meta::hybrid::DataType::INT8: {
                            if (attr_data.size() == sizeof(int8_t)) {
                                grpc_int32_data = attr_data[0];
                                int32_data.emplace_back(grpc_int32_data);
                            } 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)) {
                                int16_t value;
                                memcpy(&value, attr_data.data(), sizeof(int16_t));
                                grpc_int32_data = value;
                                int32_data.emplace_back(grpc_int32_data);
                            } 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)) {
                                memcpy(&grpc_int32_data, attr_data.data(), sizeof(int32_t));
                                int32_data.emplace_back(grpc_int32_data);
                            } 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)) {
                                memcpy(&grpc_int64_data, attr_data.data(), sizeof(int64_t));
                                int64_data.emplace_back(grpc_int64_data);
                            } 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)) {
                                float value;
                                memcpy(&value, attr_data.data(), sizeof(float));
                                grpc_float_data = value;
                                float_data.emplace_back(grpc_float_data);
                            } 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; }
Y
yukun 已提交
345 346
                    }
                }
F
fishpenguin 已提交
347 348 349
                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(),
350
                           int32_data.size() * sizeof(int32_t));
F
fishpenguin 已提交
351 352 353 354 355 356 357 358 359 360 361 362
                } 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()) {
                    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));
Y
yukun 已提交
363
                }
F
fishpenguin 已提交
364
            } else {
F
fishpenguin 已提交
365 366 367 368 369 370
                vector_field_name = field_name;
            }
        }
    }

    if (!vector_field_name.empty()) {
371 372 373 374 375 376 377 378
        auto size = vectors.size();
        response->mutable_ids()->Resize(static_cast<int>(vectors.size()), 0);
        std::vector<int64_t> id_array(size);
        for (int64_t i = 0; i < size; i++) {
            id_array[i] = vectors[i].id_array_[0];
        }
        memcpy(response->mutable_ids()->mutable_data(), id_array.data(), size * sizeof(int64_t));

F
fishpenguin 已提交
379
        auto grpc_field = response->add_fields();
F
fishpenguin 已提交
380
        grpc_field->set_field_name(vector_field_name);
F
fishpenguin 已提交
381 382 383 384 385 386 387 388 389 390 391 392 393
        ::milvus::grpc::VectorRecord* grpc_vector_data = grpc_field->mutable_vector_record();
        for (auto& vector : vectors) {
            auto grpc_data = grpc_vector_data->add_records();
            if (!vector.float_data_.empty()) {
                grpc_field->set_type(::milvus::grpc::DataType::FLOAT_VECTOR);
                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_field->set_type(::milvus::grpc::DataType::BINARY_VECTOR);
                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));
Y
yukun 已提交
394 395 396 397 398
            }
        }
    }
}

G
groot 已提交
399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416
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 已提交
417 418
}  // namespace

419 420 421 422 423 424 425 426 427 428 429 430 431 432 433
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
434
        LOG_SERVER_ERROR_ << "set_request_id: grpc::ServerContext is nullptr" << std::endl;
435 436 437 438 439 440 441 442 443 444
        return;
    }

    context->AddInitialMetadata(REQ_ID, request_id);
}

std::string
get_request_id(::grpc::ServerContext* context) {
    if (not context) {
        // error
445
        LOG_SERVER_ERROR_ << "get_request_id: grpc::ServerContext is nullptr" << std::endl;
446 447 448 449 450 451 452 453
        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
454
        LOG_SERVER_ERROR_ << std::string(REQ_ID) << " not found in grpc.server_metadata" << std::endl;
455 456 457 458 459 460 461 462
        return "INVALID_ID";
    }

    return request_id_kv->second.data();
}

}  // namespace

Z
Zhiru Zhu 已提交
463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491
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())});
492

Z
Zhiru Zhu 已提交
493 494
    auto server_context = server_rpc_info->server_context();
    auto client_metadata = server_context->client_metadata();
495 496 497

    // if client provide request_id in metadata, milvus just use it,
    // else milvus generate a sequential id.
Z
Zhiru Zhu 已提交
498 499 500 501
    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();
502
        LOG_SERVER_DEBUG_ << "client provide request_id: " << request_id;
503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521

        // 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 已提交
522
    } else {
523 524
        request_id = std::to_string(get_sequential_id());
        set_request_id(server_context, request_id);
525
        LOG_SERVER_DEBUG_ << "milvus generate request_id: " << request_id;
Z
Zhiru Zhu 已提交
526
    }
527

Z
Zhiru Zhu 已提交
528 529 530
    auto trace_context = std::make_shared<tracing::TraceContext>(span);
    auto context = std::make_shared<Context>(request_id);
    context->SetTraceContext(trace_context);
531
    SetContext(server_rpc_info->server_context(), context);
Z
Zhiru Zhu 已提交
532 533 534 535 536
}

void
GrpcRequestHandler::OnPreSendMessage(::grpc::experimental::ServerRpcInfo* server_rpc_info,
                                     ::grpc::experimental::InterceptorBatchMethods* interceptor_batch_methods) {
537
    std::lock_guard<std::mutex> lock(context_map_mutex_);
538 539 540 541
    auto request_id = get_request_id(server_rpc_info->server_context());

    if (context_map_.find(request_id) == context_map_.end()) {
        // error
542
        LOG_SERVER_ERROR_ << "request_id " << request_id << " not found in context_map_";
543
        return;
Z
Zhiru Zhu 已提交
544
    }
545 546
    context_map_[request_id]->GetTraceContext()->GetSpan()->Finish();
    context_map_.erase(request_id);
Z
Zhiru Zhu 已提交
547 548
}

J
Jin Hai 已提交
549
std::shared_ptr<Context>
Z
Zhiru Zhu 已提交
550
GrpcRequestHandler::GetContext(::grpc::ServerContext* server_context) {
551
    std::lock_guard<std::mutex> lock(context_map_mutex_);
552
    auto request_id = get_request_id(server_context);
G
groot 已提交
553 554 555

    auto iter = context_map_.find(request_id);
    if (iter == context_map_.end()) {
556
        LOG_SERVER_ERROR_ << "GetContext: request_id " << request_id << " not found in context_map_";
557 558
        return nullptr;
    }
G
groot 已提交
559 560 561 562 563 564

    if (iter->second != nullptr) {
        ConnectionContextPtr connection_context = std::make_shared<GrpcConnectionContext>(server_context);
        iter->second->SetConnectionContext(connection_context);
    }
    return iter->second;
Z
Zhiru Zhu 已提交
565 566 567 568
}

void
GrpcRequestHandler::SetContext(::grpc::ServerContext* server_context, const std::shared_ptr<Context>& context) {
569
    std::lock_guard<std::mutex> lock(context_map_mutex_);
570 571
    auto request_id = get_request_id(server_context);
    context_map_[request_id] = context;
Z
Zhiru Zhu 已提交
572 573 574 575 576 577 578 579 580 581 582 583 584 585
}

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 已提交
586
::grpc::Status
587
GrpcRequestHandler::CreateCollection(::grpc::ServerContext* context, const ::milvus::grpc::Mapping* request,
G
groot 已提交
588
                                     ::milvus::grpc::Status* response) {
589
    CHECK_NULLPTR_RETURN(request);
W
Wang XiangYu 已提交
590
    LOG_SERVER_INFO_ << LogOut("Request [%s] %s begin.", GetContext(context)->RequestID().c_str(), __func__);
591

592 593 594
    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;
595 596 597 598 599 600
    if (request->fields_size() > MAXIMUM_FIELD_NUM) {
        Status status = Status{SERVER_INVALID_FIELD_NUM, "Maximum field's number should be limited to 64"};
        LOG_SERVER_INFO_ << LogOut("Request [%s] %s end.", GetContext(context)->RequestID().c_str(), __func__);
        SET_RESPONSE(response, status, context);
        return ::grpc::Status::OK;
    }
601 602 603 604 605 606 607
    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++) {
608
            index_param[field.index_params(j).key()] = field.index_params(j).value();
609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631
        }
        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 已提交
632 633

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

K
kun yu 已提交
636 637 638 639
    return ::grpc::Status::OK;
}

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

645
    bool has_collection = false;
646

647
    Status status = request_handler_.HasCollection(GetContext(context), request->collection_name(), has_collection);
648
    response->set_bool_reply(has_collection);
W
Wang XiangYu 已提交
649 650

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

K
kun yu 已提交
653 654 655 656
    return ::grpc::Status::OK;
}

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

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

W
Wang XiangYu 已提交
664
    LOG_SERVER_INFO_ << LogOut("Request [%s] %s end.", GetContext(context)->RequestID().c_str(), __func__);
665
    SET_RESPONSE(response, status, context);
K
kun yu 已提交
666 667 668 669
    return ::grpc::Status::OK;
}

::grpc::Status
S
starlord 已提交
670 671
GrpcRequestHandler::CreateIndex(::grpc::ServerContext* context, const ::milvus::grpc::IndexParam* request,
                                ::milvus::grpc::Status* response) {
F
fishpenguin 已提交
672
    CHECK_NULLPTR_RETURN(request)
W
Wang XiangYu 已提交
673
    LOG_SERVER_INFO_ << LogOut("Request [%s] %s begin.", GetContext(context)->RequestID().c_str(), __func__);
674

675 676 677 678 679 680 681 682
    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());
        }
    }

683 684
    Status status = request_handler_.CreateIndex(GetContext(context), request->collection_name(), request->field_name(),
                                                 request->index_name(), json_params);
685

W
Wang XiangYu 已提交
686
    LOG_SERVER_INFO_ << LogOut("Request [%s] %s end.", GetContext(context)->RequestID().c_str(), __func__);
687
    SET_RESPONSE(response, status, context);
K
kun yu 已提交
688 689 690 691
    return ::grpc::Status::OK;
}

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

697 698 699 700 701 702
    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));
    }

F
fishpenguin 已提交
703 704 705 706 707
    std::vector<std::string> field_names(request->field_names_size());
    for (int i = 0; i < request->field_names_size(); i++) {
        field_names[i] = request->field_names(i);
    }

708
    std::vector<engine::AttrsData> attrs;
709
    std::vector<engine::VectorsData> vectors;
F
fishpenguin 已提交
710 711
    Status status = request_handler_.GetEntityByID(GetContext(context), request->collection_name(), field_names,
                                                   vector_ids, attrs, vectors);
712

713
    ConstructEntityResults(attrs, vectors, field_names, response);
714

W
Wang XiangYu 已提交
715
    LOG_SERVER_INFO_ << LogOut("Request [%s] %s end.", GetContext(context)->RequestID().c_str(), __func__);
716 717 718 719 720 721
    SET_RESPONSE(response->mutable_status(), status, context);

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

::grpc::Status
722 723
GrpcRequestHandler::GetEntityIDs(::grpc::ServerContext* context, const ::milvus::grpc::GetEntityIDsParam* request,
                                 ::milvus::grpc::EntityIds* response) {
724
    CHECK_NULLPTR_RETURN(request);
W
Wang XiangYu 已提交
725
    LOG_SERVER_INFO_ << LogOut("Request [%s] %s begin.", GetContext(context)->RequestID().c_str(), __func__);
726 727

    std::vector<int64_t> vector_ids;
728
    Status status = request_handler_.GetVectorIDs(GetContext(context), request->collection_name(),
G
groot 已提交
729
                                                  request->segment_name(), vector_ids);
730 731

    if (!vector_ids.empty()) {
732 733
        response->mutable_entity_id_array()->Resize(vector_ids.size(), -1);
        memcpy(response->mutable_entity_id_array()->mutable_data(), vector_ids.data(),
734 735
               vector_ids.size() * sizeof(int64_t));
    }
W
Wang XiangYu 已提交
736 737

    LOG_SERVER_INFO_ << LogOut("Request [%s] %s end.", GetContext(context)->RequestID().c_str(), __func__);
738 739 740 741 742
    SET_RESPONSE(response->mutable_status(), status, context);

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

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
//::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;
//}
784 785 786

::grpc::Status
GrpcRequestHandler::SearchByID(::grpc::ServerContext* context, const ::milvus::grpc::SearchByIDParam* request,
787 788 789 790 791 792 793 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
                               ::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 已提交
823 824 825
}

::grpc::Status
S
starlord 已提交
826
GrpcRequestHandler::SearchInFiles(::grpc::ServerContext* context, const ::milvus::grpc::SearchInFilesParam* request,
827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866
                                  ::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);
867

Y
Yu Kun 已提交
868
    return ::grpc::Status::OK;
K
kun yu 已提交
869 870 871
}

::grpc::Status
G
groot 已提交
872
GrpcRequestHandler::DescribeCollection(::grpc::ServerContext* context, const ::milvus::grpc::CollectionName* request,
873
                                       ::milvus::grpc::Mapping* response) {
W
Wang XiangYu 已提交
874
    LOG_SERVER_INFO_ << LogOut("Request [%s] %s begin.", GetContext(context)->RequestID().c_str(), __func__);
875 876 877 878
    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);
879

880 881 882 883 884 885 886 887 888 889 890 891
    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());
        }
    }
892

893
    CHECK_NULLPTR_RETURN(request);
W
Wang XiangYu 已提交
894
    LOG_SERVER_INFO_ << LogOut("Request [%s] %s end.", GetContext(context)->RequestID().c_str(), __func__);
895
    SET_RESPONSE(response->mutable_status(), status, context);
K
kun yu 已提交
896 897 898 899
    return ::grpc::Status::OK;
}

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

K
kun yu 已提交
905
    int64_t row_count = 0;
906
    Status status = request_handler_.CountCollection(GetContext(context), request->collection_name(), row_count);
G
groot 已提交
907
    response->set_collection_row_count(row_count);
W
Wang XiangYu 已提交
908 909

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

K
kun yu 已提交
912 913 914 915
    return ::grpc::Status::OK;
}

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

G
groot 已提交
921
    std::vector<std::string> collections;
922
    Status status = request_handler_.ShowCollections(GetContext(context), collections);
G
groot 已提交
923 924
    for (auto& collection : collections) {
        response->add_collection_names(collection);
925
    }
W
Wang XiangYu 已提交
926 927

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

930
    return ::grpc::Status::OK;
K
kun yu 已提交
931 932
}

933
::grpc::Status
G
groot 已提交
934 935
GrpcRequestHandler::ShowCollectionInfo(::grpc::ServerContext* context, const ::milvus::grpc::CollectionName* request,
                                       ::milvus::grpc::CollectionInfo* response) {
936
    CHECK_NULLPTR_RETURN(request);
W
Wang XiangYu 已提交
937
    LOG_SERVER_INFO_ << LogOut("Request [%s] %s begin.", GetContext(context)->RequestID().c_str(), __func__);
938

939
    std::string collection_info;
G
groot 已提交
940
    Status status =
941
        request_handler_.ShowCollectionInfo(GetContext(context), request->collection_name(), collection_info);
942
    response->set_json_info(collection_info);
W
Wang XiangYu 已提交
943 944

    LOG_SERVER_INFO_ << LogOut("Request [%s] %s end.", GetContext(context)->RequestID().c_str(), __func__);
945 946 947 948 949
    SET_RESPONSE(response->mutable_status(), status, context);

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

K
kun yu 已提交
950
::grpc::Status
S
starlord 已提交
951 952
GrpcRequestHandler::Cmd(::grpc::ServerContext* context, const ::milvus::grpc::Command* request,
                        ::milvus::grpc::StringReply* response) {
953
    CHECK_NULLPTR_RETURN(request);
W
Wang XiangYu 已提交
954
    LOG_SERVER_INFO_ << LogOut("Request [%s] %s begin.", GetContext(context)->RequestID().c_str(), __func__);
955 956

    std::string reply;
957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980
    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 已提交
981 982

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

K
kun yu 已提交
985 986 987
    return ::grpc::Status::OK;
}

Y
Yu Kun 已提交
988
::grpc::Status
989 990
GrpcRequestHandler::DeleteByID(::grpc::ServerContext* context, const ::milvus::grpc::DeleteByIDParam* request,
                               ::milvus::grpc::Status* response) {
991
    CHECK_NULLPTR_RETURN(request);
W
Wang XiangYu 已提交
992
    LOG_SERVER_INFO_ << LogOut("Request [%s] %s begin.", GetContext(context)->RequestID().c_str(), __func__);
993

994 995 996 997 998 999 1000
    // 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
1001
    Status status = request_handler_.DeleteByID(GetContext(context), request->collection_name(), vector_ids);
W
Wang XiangYu 已提交
1002 1003

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

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

::grpc::Status
G
groot 已提交
1010 1011
GrpcRequestHandler::PreloadCollection(::grpc::ServerContext* context, const ::milvus::grpc::CollectionName* request,
                                      ::milvus::grpc::Status* 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
    Status status = request_handler_.PreloadCollection(GetContext(context), request->collection_name());
W
Wang XiangYu 已提交
1016 1017

    LOG_SERVER_INFO_ << LogOut("Request [%s] %s end.", GetContext(context)->RequestID().c_str(), __func__);
1018
    SET_RESPONSE(response, status, context);
1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037

    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);
1038

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

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

    IndexParam param;
1049
    Status status = request_handler_.DescribeIndex(GetContext(context), request->collection_name(), param);
G
groot 已提交
1050
    response->set_collection_name(param.collection_name_);
1051
    response->set_index_name(param.index_name_);
1052 1053 1054
    ::milvus::grpc::KeyValuePair* kv = response->add_extra_params();
    kv->set_key(EXTRA_PARAM_KEY);
    kv->set_value(param.extra_params_);
W
Wang XiangYu 已提交
1055 1056

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

1059
    return ::grpc::Status::OK;
Y
Yu Kun 已提交
1060 1061 1062
}

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

F
fishpenguin 已提交
1068 1069
    Status status = request_handler_.DropIndex(GetContext(context), request->collection_name(), request->field_name(),
                                               request->index_name());
W
Wang XiangYu 已提交
1070 1071

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

1074
    return ::grpc::Status::OK;
Y
Yu Kun 已提交
1075 1076
}

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

1083
    Status status = request_handler_.CreatePartition(GetContext(context), request->collection_name(), request->tag());
W
Wang XiangYu 已提交
1084 1085

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

G
groot 已提交
1088 1089 1090
    return ::grpc::Status::OK;
}

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

    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 已提交
1102 1103

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

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

G
groot 已提交
1109
::grpc::Status
G
groot 已提交
1110
GrpcRequestHandler::ShowPartitions(::grpc::ServerContext* context, const ::milvus::grpc::CollectionName* request,
G
groot 已提交
1111
                                   ::milvus::grpc::PartitionList* response) {
1112
    CHECK_NULLPTR_RETURN(request);
W
Wang XiangYu 已提交
1113
    LOG_SERVER_INFO_ << LogOut("Request [%s] %s begin.", GetContext(context)->RequestID().c_str(), __func__);
1114 1115

    std::vector<PartitionParam> partitions;
1116
    Status status = request_handler_.ShowPartitions(GetContext(context), request->collection_name(), partitions);
1117
    for (auto& partition : partitions) {
1118
        response->add_partition_tag_array(partition.tag_);
1119 1120
    }

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

G
groot 已提交
1124 1125 1126 1127 1128 1129
    return ::grpc::Status::OK;
}

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

1133
    Status status = request_handler_.DropPartition(GetContext(context), request->collection_name(), request->tag());
W
Wang XiangYu 已提交
1134 1135

    LOG_SERVER_INFO_ << LogOut("Request [%s] %s end.", GetContext(context)->RequestID().c_str(), __func__);
1136 1137 1138 1139 1140 1141 1142 1143 1144
    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 已提交
1145
    LOG_SERVER_INFO_ << LogOut("Request [%s] %s begin.", GetContext(context)->RequestID().c_str(), __func__);
1146

J
Jin Hai 已提交
1147
    std::vector<std::string> collection_names;
G
groot 已提交
1148 1149
    for (int32_t i = 0; i < request->collection_name_array().size(); i++) {
        collection_names.push_back(request->collection_name_array(i));
1150
    }
1151
    Status status = request_handler_.Flush(GetContext(context), collection_names);
W
Wang XiangYu 已提交
1152 1153

    LOG_SERVER_INFO_ << LogOut("Request [%s] %s end.", GetContext(context)->RequestID().c_str(), __func__);
1154 1155 1156 1157 1158 1159
    SET_RESPONSE(response, status, context);

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

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

G
groot 已提交
1165 1166
    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 已提交
1167 1168

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

G
groot 已提交
1171 1172 1173
    return ::grpc::Status::OK;
}

1174 1175 1176
/*******************************************New Interface*********************************************/

::grpc::Status
1177 1178
GrpcRequestHandler::Insert(::grpc::ServerContext* context, const ::milvus::grpc::InsertParam* request,
                           ::milvus::grpc::EntityIds* response) {
Y
yukun 已提交
1179 1180 1181
    //    engine::VectorsData vectors;
    //    CopyRowRecords(request->entity().vector_data(0).value(), request->entity_id_array(), vectors);

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

1185
    auto field_size = request->fields_size();
1186

1187
    std::unordered_map<std::string, engine::VectorsData> vectors;
1188
    std::vector<std::string> field_names;
1189 1190

    std::vector<int64_t> offsets;
1191
    std::vector<std::vector<uint8_t>> attr_datas;
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
    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);
1228 1229
    }

1230 1231 1232 1233 1234 1235
    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();
1236 1237 1238 1239
    }

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

1243 1244 1245
    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));
1246

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

1250 1251 1252
    return ::grpc::Status::OK;
}

Y
yukun 已提交
1253
::grpc::Status
1254 1255
GrpcRequestHandler::SearchPB(::grpc::ServerContext* context, const ::milvus::grpc::SearchParamPB* request,
                             ::milvus::grpc::QueryResult* response) {
Y
yukun 已提交
1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269
    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"};
F
fishpenguin 已提交
1270
        SET_RESPONSE(response->mutable_status(), status, context)
Y
yukun 已提交
1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294
        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_);
1295 1296 1297 1298
    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 已提交
1299 1300
           result.result_ids_.size() * sizeof(int64_t));

1301 1302
    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 已提交
1303 1304 1305
           result.result_distances_.size() * sizeof(float));

    LOG_SERVER_INFO_ << LogOut("Request [%s] %s end.", GetContext(context)->RequestID().c_str(), __func__);
F
fishpenguin 已提交
1306
    SET_RESPONSE(response->mutable_status(), status, context);
Y
yukun 已提交
1307 1308 1309 1310

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

1311
#if 0
Y
yukun 已提交
1312 1313 1314 1315
Status
ParseTermQuery(const nlohmann::json& term_json,
               std::unordered_map<std::string, engine::meta::hybrid::DataType> field_type,
               query::TermQueryPtr& term_query) {
F
fishpenguin 已提交
1316
    std::string field_name = term_json["field"].get<std::string>();
Y
yukun 已提交
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
    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) {
F
fishpenguin 已提交
1382
    std::string field_name = range_json["field"];
Y
yukun 已提交
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 1422 1423
    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();
}
1424
#endif
Y
yukun 已提交
1425 1426 1427 1428 1429 1430 1431

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_query = std::make_shared<query::TermQuery>();
1432
        term_query->json_obj = json["term"];
Y
yukun 已提交
1433 1434 1435 1436 1437
        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>();
1438
        range_query->json_obj = json["range"];
Y
yukun 已提交
1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453
        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 已提交
1454 1455 1456 1457 1458 1459 1460 1461
    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 已提交
1462

Y
yukun 已提交
1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475
            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;
                    }
1476
                }
Y
yukun 已提交
1477
            }
Y
yukun 已提交
1478 1479 1480 1481 1482 1483 1484
        } 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 已提交
1485

Y
yukun 已提交
1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498
            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 已提交
1499 1500
                }
            }
Y
yukun 已提交
1501 1502 1503 1504 1505 1506 1507
        } 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};
            }
1508

Y
yukun 已提交
1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521
            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 已提交
1522 1523
                }
            }
Y
yukun 已提交
1524 1525 1526
        } else {
            std::string msg = "Must json string doesnot include right query";
            return Status{SERVER_INVALID_DSL_PARAMETER, msg};
Y
yukun 已提交
1527 1528
        }
    }
1529

Y
yukun 已提交
1530 1531
    return status;
}
1532

Y
yukun 已提交
1533 1534 1535 1536 1537
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) {
    try {
F
fishpenguin 已提交
1538 1539
        nlohmann::json dsl_json = json::parse(dsl_string);

Y
yukun 已提交
1540
        auto status = Status::OK();
F
fishpenguin 已提交
1541 1542
        for (const auto& vector_param : vector_params) {
            std::string vector_string = vector_param.json();
Y
yukun 已提交
1543 1544 1545 1546 1547
            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>();
1548 1549 1550
            json::iterator vector_param_it = it.value().begin();
            if (vector_param_it != it.value().end()) {
                vector_query->field_name = vector_param_it.key();
F
fishpenguin 已提交
1551 1552 1553 1554 1555 1556
                int64_t topk = vector_param_it.value()["topk"];
                status = server::ValidateSearchTopk(topk);
                if (!status.ok()) {
                    return status;
                }
                vector_query->topk = topk;
1557 1558
                vector_query->extra_params = vector_param_it.value()["params"];
            }
Y
yukun 已提交
1559 1560

            engine::VectorsData vector_data;
F
fishpenguin 已提交
1561
            CopyRowRecords(vector_param.row_record().records(),
1562
                           google::protobuf::RepeatedField<google::protobuf::int64>(), vector_data);
Y
yukun 已提交
1563 1564 1565 1566 1567 1568 1569 1570 1571 1572
            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));
        }
        if (dsl_json.contains("bool")) {
            auto boolean_query_json = dsl_json["bool"];
            status = ProcessBooleanQueryJson(boolean_query_json, boolean_query);
            if (!status.ok()) {
                return status;
1573 1574
            }
        }
Y
yukun 已提交
1575 1576 1577
        return status;
    } catch (std::exception& e) {
        return Status{SERVER_INVALID_DSL_PARAMETER, e.what()};
1578 1579 1580 1581
    }
}

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

Y
yukun 已提交
1587 1588
    Status status;

1589 1590 1591 1592 1593
    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 已提交
1594
    if (!status.ok()) {
F
fishpenguin 已提交
1595
        SET_RESPONSE(response->mutable_status(), status, context);
Y
yukun 已提交
1596 1597
        return ::grpc::Status::OK;
    }
1598 1599

    query::BooleanQueryPtr boolean_query = std::make_shared<query::BooleanQuery>();
Y
yukun 已提交
1600 1601 1602
    query::QueryPtr query_ptr = std::make_shared<query::Query>();
    std::unordered_map<std::string, query::VectorQueryPtr> vectors;

F
fishpenguin 已提交
1603 1604 1605 1606 1607
    status = DeserializeJsonToBoolQuery(request->vector_param(), request->dsl(), boolean_query, vectors);
    if (!status.ok()) {
        SET_RESPONSE(response->mutable_status(), status, context);
        return ::grpc::Status::OK;
    }
Y
yukun 已提交
1608

Y
yukun 已提交
1609 1610
    status = query::ValidateBooleanQuery(boolean_query);
    if (!status.ok()) {
F
fishpenguin 已提交
1611
        SET_RESPONSE(response->mutable_status(), status, context);
Y
yukun 已提交
1612 1613 1614
        return ::grpc::Status::OK;
    }

Y
yukun 已提交
1615
    query_ptr->vectors = vectors;
1616 1617 1618

    query::GeneralQueryPtr general_query = std::make_shared<query::GeneralQuery>();
    query::GenBinaryQuery(boolean_query, general_query->bin);
Y
yukun 已提交
1619
    query_ptr->root = general_query->bin;
1620 1621 1622

    if (!query::ValidateBinaryQuery(general_query->bin)) {
        status = Status{SERVER_INVALID_BINARY_QUERY, "Generate wrong binary query tree"};
1623
        SET_RESPONSE(grpc_entity->mutable_status(), status, context);
1624 1625 1626 1627 1628
        return ::grpc::Status::OK;
    }

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

Y
yukun 已提交
1633 1634 1635 1636 1637 1638 1639
    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());
        }
    }
1640

Y
yukun 已提交
1641 1642
    engine::QueryResult result;
    std::vector<std::string> field_names;
Y
yukun 已提交
1643 1644
    status = request_handler_.HybridSearch(GetContext(context), request->collection_name(), partition_list,
                                           general_query, query_ptr, json_params, field_names, result);
1645 1646

    // step 6: construct and return result
Y
yukun 已提交
1647
    response->set_row_num(result.row_num_);
1648 1649 1650 1651
    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 已提交
1652 1653
           result.result_ids_.size() * sizeof(int64_t));

1654 1655
    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 已提交
1656 1657 1658
           result.result_distances_.size() * sizeof(float));

    LOG_SERVER_INFO_ << LogOut("Request [%s] %s end.", GetContext(context)->RequestID().c_str(), __func__);
F
fishpenguin 已提交
1659
    SET_RESPONSE(response->mutable_status(), status, context);
Y
yukun 已提交
1660 1661 1662 1663

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

S
starlord 已提交
1664 1665 1666
}  // namespace grpc
}  // namespace server
}  // namespace milvus