RequestTask.cpp 27.9 KB
Newer Older
G
groot 已提交
1 2 3 4 5
/*******************************************************************************
 * Copyright 上海赜睿信息科技有限公司(Zilliz) - All Rights Reserved
 * Unauthorized copying of this file, via any medium is strictly prohibited.
 * Proprietary and confidential.
 ******************************************************************************/
G
groot 已提交
6
#include "RequestTask.h"
G
groot 已提交
7 8 9 10
#include "ServerConfig.h"
#include "utils/CommonUtil.h"
#include "utils/Log.h"
#include "utils/TimeRecorder.h"
J
jinhai 已提交
11
#include "utils/ValidationUtil.h"
G
groot 已提交
12
#include "DBWrapper.h"
G
groot 已提交
13
#include "version.h"
G
groot 已提交
14

Y
yudong.cai 已提交
15 16 17 18
#ifdef MILVUS_ENABLE_PROFILING
#include "gperftools/profiler.h"
#endif

G
groot 已提交
19
namespace zilliz {
J
jinhai 已提交
20
namespace milvus {
G
groot 已提交
21 22
namespace server {

G
groot 已提交
23 24
using namespace ::milvus;

G
groot 已提交
25 26
static const std::string DQL_TASK_GROUP = "dql";
static const std::string DDL_DML_TASK_GROUP = "ddl_dml";
G
groot 已提交
27
static const std::string PING_TASK_GROUP = "ping";
G
groot 已提交
28

J
jinhai 已提交
29 30
using DB_META = zilliz::milvus::engine::meta::Meta;
using DB_DATE = zilliz::milvus::engine::meta::DateT;
G
groot 已提交
31 32

namespace {
G
groot 已提交
33 34 35 36 37
    engine::EngineType EngineType(int type) {
        static std::map<int, engine::EngineType> map_type = {
                {0, engine::EngineType::INVALID},
                {1, engine::EngineType::FAISS_IDMAP},
                {2, engine::EngineType::FAISS_IVFFLAT},
G
groot 已提交
38
                {3, engine::EngineType::FAISS_IVFSQ8},
G
groot 已提交
39 40 41 42 43 44 45
        };

        if(map_type.find(type) == map_type.end()) {
            return engine::EngineType::INVALID;
        }

        return map_type[type];
G
groot 已提交
46
    }
G
groot 已提交
47

G
groot 已提交
48 49 50 51 52
    int IndexType(engine::EngineType type) {
        static std::map<engine::EngineType, int> map_type = {
                {engine::EngineType::INVALID, 0},
                {engine::EngineType::FAISS_IDMAP, 1},
                {engine::EngineType::FAISS_IVFFLAT, 2},
G
groot 已提交
53
                {engine::EngineType::FAISS_IVFSQ8, 3},
G
groot 已提交
54 55 56 57 58 59 60 61 62
        };

        if(map_type.find(type) == map_type.end()) {
            return 0;
        }

        return map_type[type];
    }

G
groot 已提交
63
    void
G
groot 已提交
64 65
    ConvertRowRecordToFloatArray(const std::vector<thrift::RowRecord>& record_array,
                                 uint64_t dimension,
G
groot 已提交
66 67 68
                                 std::vector<float>& float_array,
                                 ServerError& error_code,
                                 std::string& error_msg) {
G
groot 已提交
69 70 71 72 73
        uint64_t vec_count = record_array.size();
        float_array.resize(vec_count*dimension);//allocate enough memory
        for(uint64_t i = 0; i < vec_count; i++) {
            const auto& record = record_array[i];
            if(record.vector_data.empty()) {
G
groot 已提交
74 75 76
                error_code = SERVER_INVALID_ROWRECORD;
                error_msg = "Rowrecord float array is empty";
                return;
G
groot 已提交
77 78 79 80
            }
            uint64_t vec_dim = record.vector_data.size()/sizeof(double);//how many double value?
            if(vec_dim != dimension) {
                error_code = SERVER_INVALID_VECTOR_DIMENSION;
G
groot 已提交
81 82 83
                error_msg = "Invalid rowrecord dimension: " + std::to_string(vec_dim)
                                 + " vs. table dimension:" + std::to_string(dimension);
                return;
G
groot 已提交
84 85 86 87 88 89 90 91 92 93 94 95
            }

            //convert double array to float array(thrift has no float type)
            const double* d_p = reinterpret_cast<const double*>(record.vector_data.data());
            for(uint64_t d = 0; d < vec_dim; d++) {
                float_array[i*vec_dim + d] = (float)(d_p[d]);
            }
        }
    }

    static constexpr long DAY_SECONDS = 86400;

G
groot 已提交
96
    void
G
groot 已提交
97
    ConvertTimeRangeToDBDates(const std::vector<thrift::Range> &range_array,
G
groot 已提交
98 99 100
                              std::vector<DB_DATE>& dates,
                              ServerError& error_code,
                              std::string& error_msg) {
G
groot 已提交
101 102 103 104 105 106
        dates.clear();
        for(auto& range : range_array) {
            time_t tt_start, tt_end;
            tm tm_start, tm_end;
            if(!CommonUtil::TimeStrToTime(range.start_value, tt_start, tm_start)){
                error_code = SERVER_INVALID_TIME_RANGE;
G
groot 已提交
107 108
                error_msg = "Invalid time range: " + range.start_value;
                return;
G
groot 已提交
109 110 111 112
            }

            if(!CommonUtil::TimeStrToTime(range.end_value, tt_end, tm_end)){
                error_code = SERVER_INVALID_TIME_RANGE;
G
groot 已提交
113 114
                error_msg = "Invalid time range: " + range.start_value;
                return;
G
groot 已提交
115 116 117
            }

            long days = (tt_end > tt_start) ? (tt_end - tt_start)/DAY_SECONDS : (tt_start - tt_end)/DAY_SECONDS;
G
groot 已提交
118 119 120 121 122 123 124
            if(days == 0) {
                error_code = SERVER_INVALID_TIME_RANGE;
                error_msg = "Invalid time range: " + range.start_value + " to " + range.end_value;
                return ;
            }

            for(long i = 0; i < days; i++) {
G
groot 已提交
125 126 127 128 129 130 131 132 133
                time_t tt_day = tt_start + DAY_SECONDS*i;
                tm tm_day;
                CommonUtil::ConvertTime(tt_day, tm_day);

                long date = tm_day.tm_year*10000 + tm_day.tm_mon*100 + tm_day.tm_mday;//according to db logic
                dates.push_back(date);
            }
        }
    }
Y
yudong.cai 已提交
134 135 136 137 138 139 140 141 142 143 144 145

    std::string
    GetCurrTimeStr() {
        char tm_buf[20] = {0};
        time_t tt;
        time(&tt);
        tt = tt + 8 * 60 * 60;
        tm* t = gmtime(&tt);
        sprintf(tm_buf, "%4d%02d%02d_%02d%02d%02d", (t->tm_year+1900), (t->tm_mon+1), (t->tm_mday),
                                                    (t->tm_hour), (t->tm_min), (t->tm_sec));
        return tm_buf;
    }
G
groot 已提交
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
CreateTableTask::CreateTableTask(const thrift::TableSchema& schema)
: BaseTask(DDL_DML_TASK_GROUP),
  schema_(schema) {

}

BaseTaskPtr CreateTableTask::Create(const thrift::TableSchema& schema) {
    return std::shared_ptr<BaseTask>(new CreateTableTask(schema));
}

ServerError CreateTableTask::OnExecute() {
    TimeRecorder rc("CreateTableTask");
P
peng.xu 已提交
161

G
groot 已提交
162
    try {
G
groot 已提交
163
        //step 1: check arguments
J
jinhai 已提交
164 165 166
        ServerError res = SERVER_SUCCESS;
        res = ValidateTableName(schema_.table_name);
        if(res != SERVER_SUCCESS) {
167
            return SetError(res, "Invalid table name: " + schema_.table_name);
G
groot 已提交
168
        }
J
jinhai 已提交
169 170 171

        res = ValidateTableDimension(schema_.dimension);
        if(res != SERVER_SUCCESS) {
172
            return SetError(res, "Invalid table dimension: " + std::to_string(schema_.dimension));
G
groot 已提交
173 174
        }

J
jinhai 已提交
175 176
        res = ValidateTableIndexType(schema_.index_type);
        if(res != SERVER_SUCCESS) {
177
            return SetError(res, "Invalid index type: " + std::to_string(schema_.index_type));
G
groot 已提交
178 179 180
        }

        //step 2: construct table schema
G
groot 已提交
181
        engine::meta::TableSchema table_info;
G
groot 已提交
182 183 184 185 186
        table_info.dimension_ = (uint16_t)schema_.dimension;
        table_info.table_id_ = schema_.table_name;
        table_info.engine_type_ = (int)EngineType(schema_.index_type);
        table_info.store_raw_data_ = schema_.store_raw_vector;

G
groot 已提交
187
        //step 3: create table
G
groot 已提交
188
        engine::Status stat = DBWrapper::DB()->CreateTable(table_info);
G
groot 已提交
189
        if(!stat.ok()) {//table could exist
G
groot 已提交
190
            return SetError(DB_META_TRANSACTION_FAILED, "Engine failed: " + stat.ToString());
G
groot 已提交
191 192 193
        }

    } catch (std::exception& ex) {
G
groot 已提交
194
        return SetError(SERVER_UNEXPECTED_ERROR, ex.what());
G
groot 已提交
195 196
    }

G
groot 已提交
197
    rc.ElapseFromBegin("totally cost");
G
groot 已提交
198 199 200 201 202 203

    return SERVER_SUCCESS;
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
DescribeTableTask::DescribeTableTask(const std::string &table_name, thrift::TableSchema &schema)
G
groot 已提交
204
    : BaseTask(DDL_DML_TASK_GROUP),
G
groot 已提交
205 206 207 208 209 210 211 212 213 214 215 216 217
      table_name_(table_name),
      schema_(schema) {
    schema_.table_name = table_name_;
}

BaseTaskPtr DescribeTableTask::Create(const std::string& table_name, thrift::TableSchema& schema) {
    return std::shared_ptr<BaseTask>(new DescribeTableTask(table_name, schema));
}

ServerError DescribeTableTask::OnExecute() {
    TimeRecorder rc("DescribeTableTask");

    try {
G
groot 已提交
218
        //step 1: check arguments
J
jinhai 已提交
219 220 221
        ServerError res = SERVER_SUCCESS;
        res = ValidateTableName(table_name_);
        if(res != SERVER_SUCCESS) {
222
            return SetError(res, "Invalid table name: " + table_name_);
G
groot 已提交
223 224 225
        }

        //step 2: get table info
G
groot 已提交
226
        engine::meta::TableSchema table_info;
G
groot 已提交
227
        table_info.table_id_ = table_name_;
G
groot 已提交
228
        engine::Status stat = DBWrapper::DB()->DescribeTable(table_info);
G
groot 已提交
229
        if(!stat.ok()) {
G
groot 已提交
230
            return SetError(DB_META_TRANSACTION_FAILED, "Engine failed: " + stat.ToString());
G
groot 已提交
231 232
        }

G
groot 已提交
233 234 235 236 237
        schema_.table_name = table_info.table_id_;
        schema_.index_type = IndexType((engine::EngineType)table_info.engine_type_);
        schema_.dimension = table_info.dimension_;
        schema_.store_raw_vector = table_info.store_raw_data_;

G
groot 已提交
238
    } catch (std::exception& ex) {
G
groot 已提交
239
        return SetError(SERVER_UNEXPECTED_ERROR, ex.what());
G
groot 已提交
240 241
    }

G
groot 已提交
242
    rc.ElapseFromBegin("totally cost");
G
groot 已提交
243 244 245 246

    return SERVER_SUCCESS;
}

P
peng.xu 已提交
247 248 249 250 251 252 253 254 255 256 257 258 259 260 261
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
BuildIndexTask::BuildIndexTask(const std::string& table_name)
    : BaseTask(DDL_DML_TASK_GROUP),
      table_name_(table_name) {
}

BaseTaskPtr BuildIndexTask::Create(const std::string& table_name) {
    return std::shared_ptr<BaseTask>(new BuildIndexTask(table_name));
}

ServerError BuildIndexTask::OnExecute() {
    try {
        TimeRecorder rc("BuildIndexTask");

        //step 1: check arguments
262 263 264 265 266 267 268 269 270 271
        ServerError res = SERVER_SUCCESS;
        res = ValidateTableName(table_name_);
        if(res != SERVER_SUCCESS) {
            return SetError(res, "Invalid table name: " + table_name_);
        }

        bool has_table = false;
        engine::Status stat = DBWrapper::DB()->HasTable(table_name_, has_table);
        if(!has_table) {
            return SetError(SERVER_TABLE_NOT_EXIST, "Table " + table_name_ + " not exists");
P
peng.xu 已提交
272 273 274
        }

        //step 2: check table existence
275
        stat = DBWrapper::DB()->BuildIndex(table_name_);
P
peng.xu 已提交
276 277 278 279
        if(!stat.ok()) {
            return SetError(SERVER_BUILD_INDEX_ERROR, "Engine failed: " + stat.ToString());
        }

G
groot 已提交
280
        rc.ElapseFromBegin("totally cost");
P
peng.xu 已提交
281 282 283 284 285 286 287
    } catch (std::exception& ex) {
        return SetError(SERVER_UNEXPECTED_ERROR, ex.what());
    }

    return SERVER_SUCCESS;
}

G
groot 已提交
288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
HasTableTask::HasTableTask(const std::string& table_name, bool& has_table)
    : BaseTask(DDL_DML_TASK_GROUP),
      table_name_(table_name),
      has_table_(has_table) {

}

BaseTaskPtr HasTableTask::Create(const std::string& table_name, bool& has_table) {
    return std::shared_ptr<BaseTask>(new HasTableTask(table_name, has_table));
}

ServerError HasTableTask::OnExecute() {
    try {
        TimeRecorder rc("HasTableTask");

        //step 1: check arguments
J
jinhai 已提交
305 306 307
        ServerError res = SERVER_SUCCESS;
        res = ValidateTableName(table_name_);
        if(res != SERVER_SUCCESS) {
308
            return SetError(res, "Invalid table name: " + table_name_);
G
groot 已提交
309 310 311 312
        }

        //step 2: check table existence
        engine::Status stat = DBWrapper::DB()->HasTable(table_name_, has_table_);
G
groot 已提交
313 314 315
        if(!stat.ok()) {
            return SetError(DB_META_TRANSACTION_FAILED, "Engine failed: " + stat.ToString());
        }
G
groot 已提交
316

G
groot 已提交
317
        rc.ElapseFromBegin("totally cost");
G
groot 已提交
318
    } catch (std::exception& ex) {
G
groot 已提交
319
        return SetError(SERVER_UNEXPECTED_ERROR, ex.what());
G
groot 已提交
320 321 322 323 324
    }

    return SERVER_SUCCESS;
}

G
groot 已提交
325 326 327 328 329 330 331
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
DeleteTableTask::DeleteTableTask(const std::string& table_name)
    : BaseTask(DDL_DML_TASK_GROUP),
      table_name_(table_name) {

}

G
groot 已提交
332 333
BaseTaskPtr DeleteTableTask::Create(const std::string& table_name) {
    return std::shared_ptr<BaseTask>(new DeleteTableTask(table_name));
G
groot 已提交
334 335 336
}

ServerError DeleteTableTask::OnExecute() {
G
groot 已提交
337 338 339
    try {
        TimeRecorder rc("DeleteTableTask");

G
groot 已提交
340
        //step 1: check arguments
J
jinhai 已提交
341 342 343
        ServerError res = SERVER_SUCCESS;
        res = ValidateTableName(table_name_);
        if(res != SERVER_SUCCESS) {
344
            return SetError(res, "Invalid table name: " + table_name_);
G
groot 已提交
345 346 347 348 349
        }

        //step 2: check table existence
        engine::meta::TableSchema table_info;
        table_info.table_id_ = table_name_;
G
groot 已提交
350
        engine::Status stat = DBWrapper::DB()->DescribeTable(table_info);
G
groot 已提交
351
        if(!stat.ok()) {
G
groot 已提交
352 353 354 355 356
            if(stat.IsNotFound()) {
                return SetError(SERVER_TABLE_NOT_EXIST, "Table " + table_name_ + " not exists");
            } else {
                return SetError(DB_META_TRANSACTION_FAILED, "Engine failed: " + stat.ToString());
            }
G
groot 已提交
357 358 359 360
        }

        //step 3: delete table
        std::vector<DB_DATE> dates;
G
groot 已提交
361
        stat = DBWrapper::DB()->DeleteTable(table_name_, dates);
G
groot 已提交
362
        if(!stat.ok()) {
G
groot 已提交
363
            return SetError(DB_META_TRANSACTION_FAILED, "Engine failed: " + stat.ToString());
G
groot 已提交
364 365
        }

G
groot 已提交
366
        rc.ElapseFromBegin("totally cost");
G
groot 已提交
367
    } catch (std::exception& ex) {
G
groot 已提交
368
        return SetError(SERVER_UNEXPECTED_ERROR, ex.what());
G
groot 已提交
369 370 371
    }

    return SERVER_SUCCESS;
G
groot 已提交
372 373
}

G
groot 已提交
374 375
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
ShowTablesTask::ShowTablesTask(std::vector<std::string>& tables)
G
groot 已提交
376
    : BaseTask(DDL_DML_TASK_GROUP),
G
groot 已提交
377 378 379 380 381 382 383 384 385
      tables_(tables) {

}

BaseTaskPtr ShowTablesTask::Create(std::vector<std::string>& tables) {
    return std::shared_ptr<BaseTask>(new ShowTablesTask(tables));
}

ServerError ShowTablesTask::OnExecute() {
G
groot 已提交
386
    std::vector<engine::meta::TableSchema> schema_array;
G
groot 已提交
387
    engine::Status stat = DBWrapper::DB()->AllTables(schema_array);
G
groot 已提交
388
    if(!stat.ok()) {
G
groot 已提交
389
        return SetError(DB_META_TRANSACTION_FAILED, "Engine failed: " + stat.ToString());
G
groot 已提交
390 391 392 393 394 395
    }

    tables_.clear();
    for(auto& schema : schema_array) {
        tables_.push_back(schema.table_id_);
    }
G
groot 已提交
396 397 398

    return SERVER_SUCCESS;
}
G
groot 已提交
399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
AddVectorTask::AddVectorTask(const std::string& table_name,
                                       const std::vector<thrift::RowRecord>& record_array,
                                       std::vector<int64_t>& record_ids)
    : BaseTask(DDL_DML_TASK_GROUP),
      table_name_(table_name),
      record_array_(record_array),
      record_ids_(record_ids) {
    record_ids_.clear();
}

BaseTaskPtr AddVectorTask::Create(const std::string& table_name,
                                       const std::vector<thrift::RowRecord>& record_array,
                                       std::vector<int64_t>& record_ids) {
    return std::shared_ptr<BaseTask>(new AddVectorTask(table_name, record_array, record_ids));
}

ServerError AddVectorTask::OnExecute() {
    try {
        TimeRecorder rc("AddVectorTask");

G
groot 已提交
421
        //step 1: check arguments
J
jinhai 已提交
422 423 424
        ServerError res = SERVER_SUCCESS;
        res = ValidateTableName(table_name_);
        if(res != SERVER_SUCCESS) {
425
            return SetError(res, "Invalid table name: " + table_name_);
G
groot 已提交
426 427
        }

G
groot 已提交
428
        if(record_array_.empty()) {
G
groot 已提交
429
            return SetError(SERVER_INVALID_ROWRECORD_ARRAY, "Row record array is empty");
G
groot 已提交
430 431
        }

G
groot 已提交
432
        //step 2: check table existence
G
groot 已提交
433
        engine::meta::TableSchema table_info;
G
groot 已提交
434
        table_info.table_id_ = table_name_;
G
groot 已提交
435
        engine::Status stat = DBWrapper::DB()->DescribeTable(table_info);
G
groot 已提交
436
        if(!stat.ok()) {
G
groot 已提交
437 438 439 440 441
            if(stat.IsNotFound()) {
                return SetError(SERVER_TABLE_NOT_EXIST, "Table " + table_name_ + " not exists");
            } else {
                return SetError(DB_META_TRANSACTION_FAILED, "Engine failed: " + stat.ToString());
            }
G
groot 已提交
442 443
        }

G
groot 已提交
444
        rc.RecordSection("check validation");
G
groot 已提交
445

Y
yudong.cai 已提交
446
#ifdef MILVUS_ENABLE_PROFILING
447 448
        std::string fname = "/tmp/insert_" + std::to_string(this->record_array_.size()) +
                            "_" + GetCurrTimeStr() + ".profiling";
Y
yudong.cai 已提交
449 450 451
        ProfilerStart(fname.c_str());
#endif

G
groot 已提交
452
        //step 3: prepare float data
G
groot 已提交
453
        std::vector<float> vec_f;
G
groot 已提交
454 455 456 457 458
        ServerError error_code = SERVER_SUCCESS;
        std::string error_msg;
        ConvertRowRecordToFloatArray(record_array_, table_info.dimension_, vec_f, error_code, error_msg);
        if(error_code != SERVER_SUCCESS) {
            return SetError(error_code, error_msg);
G
groot 已提交
459 460
        }

G
groot 已提交
461
        rc.RecordSection("prepare vectors data");
G
groot 已提交
462

G
groot 已提交
463
        //step 4: insert vectors
G
groot 已提交
464
        uint64_t vec_count = (uint64_t)record_array_.size();
G
groot 已提交
465
        stat = DBWrapper::DB()->InsertVectors(table_name_, vec_count, vec_f.data(), record_ids_);
G
groot 已提交
466
        if(!stat.ok()) {
G
groot 已提交
467
            return SetError(SERVER_CACHE_ERROR, "Cache error: " + stat.ToString());
G
groot 已提交
468 469
        }

G
groot 已提交
470
        if(record_ids_.size() != vec_count) {
G
groot 已提交
471 472 473
            std::string msg = "Add " + std::to_string(vec_count) + " vectors but only return "
                    + std::to_string(record_ids_.size()) + " id";
            return SetError(SERVER_ILLEGAL_VECTOR_ID, msg);
G
groot 已提交
474 475
        }

Y
yudong.cai 已提交
476 477 478 479
#ifdef MILVUS_ENABLE_PROFILING
        ProfilerStop();
#endif

G
groot 已提交
480 481
        rc.RecordSection("add vectors to engine");
        rc.ElapseFromBegin("totally cost");
G
groot 已提交
482 483

    } catch (std::exception& ex) {
G
groot 已提交
484
        return SetError(SERVER_UNEXPECTED_ERROR, ex.what());
G
groot 已提交
485 486 487 488 489 490
    }

    return SERVER_SUCCESS;
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
491 492 493 494 495
SearchVectorTaskBase::SearchVectorTaskBase(const std::string &table_name,
        const std::vector<std::string>& file_id_array,
        const std::vector<thrift::RowRecord> &query_record_array,
        const std::vector<thrift::Range> &query_range_array,
        const int64_t top_k)
G
groot 已提交
496 497 498 499 500
    : BaseTask(DQL_TASK_GROUP),
      table_name_(table_name),
      file_id_array_(file_id_array),
      record_array_(query_record_array),
      range_array_(query_range_array),
501
      top_k_(top_k) {
G
groot 已提交
502 503 504

}

505
ServerError SearchVectorTaskBase::OnExecute() {
G
groot 已提交
506 507 508
    try {
        TimeRecorder rc("SearchVectorTask");

G
groot 已提交
509
        //step 1: check arguments
J
jinhai 已提交
510 511 512
        ServerError res = SERVER_SUCCESS;
        res = ValidateTableName(table_name_);
        if(res != SERVER_SUCCESS) {
513
            return SetError(res, "Invalid table name: " + table_name_);
G
groot 已提交
514 515
        }

G
groot 已提交
516
        if(top_k_ <= 0 || top_k_ > 1024) {
G
groot 已提交
517 518 519 520
            return SetError(SERVER_INVALID_TOPK, "Invalid topk: " + std::to_string(top_k_));
        }
        if(record_array_.empty()) {
            return SetError(SERVER_INVALID_ROWRECORD_ARRAY, "Row record array is empty");
G
groot 已提交
521 522
        }

G
groot 已提交
523
        //step 2: check table existence
G
groot 已提交
524
        engine::meta::TableSchema table_info;
G
groot 已提交
525
        table_info.table_id_ = table_name_;
G
groot 已提交
526
        engine::Status stat = DBWrapper::DB()->DescribeTable(table_info);
G
groot 已提交
527
        if(!stat.ok()) {
G
groot 已提交
528 529 530 531 532
            if(stat.IsNotFound()) {
                return SetError(SERVER_TABLE_NOT_EXIST, "Table " + table_name_ + " not exists");
            } else {
                return SetError(DB_META_TRANSACTION_FAILED, "Engine failed: " + stat.ToString());
            }
G
groot 已提交
533 534
        }

G
groot 已提交
535 536
        //step 3: check date range, and convert to db dates
        std::vector<DB_DATE> dates;
G
groot 已提交
537 538 539 540 541
        ServerError error_code = SERVER_SUCCESS;
        std::string error_msg;
        ConvertTimeRangeToDBDates(range_array_, dates, error_code, error_msg);
        if(error_code != SERVER_SUCCESS) {
            return SetError(error_code, error_msg);
G
groot 已提交
542 543
        }

G
groot 已提交
544
        double span_check = rc.RecordSection("check validation");
G
groot 已提交
545

Y
yudong.cai 已提交
546
#ifdef MILVUS_ENABLE_PROFILING
547 548
        std::string fname = "/tmp/search_nq_" + std::to_string(this->record_array_.size()) +
                            "_top_" + std::to_string(this->top_k_) + "_" +
Y
yudong.cai 已提交
549 550 551 552
                            GetCurrTimeStr() + ".profiling";
        ProfilerStart(fname.c_str());
#endif

G
groot 已提交
553
        //step 3: prepare float data
G
groot 已提交
554
        std::vector<float> vec_f;
G
groot 已提交
555 556 557
        ConvertRowRecordToFloatArray(record_array_, table_info.dimension_, vec_f, error_code, error_msg);
        if(error_code != SERVER_SUCCESS) {
            return SetError(error_code, error_msg);
G
groot 已提交
558 559
        }

G
groot 已提交
560
        double span_prepare = rc.RecordSection("prepare vector data");
G
groot 已提交
561

G
groot 已提交
562
        //step 4: search vectors
G
groot 已提交
563
        engine::QueryResults results;
G
groot 已提交
564
        uint64_t record_count = (uint64_t)record_array_.size();
565 566

        if(file_id_array_.empty()) {
G
groot 已提交
567
            stat = DBWrapper::DB()->Query(table_name_, (size_t) top_k_, record_count, vec_f.data(), dates, results);
568
        } else {
G
groot 已提交
569
            stat = DBWrapper::DB()->Query(table_name_, file_id_array_, (size_t) top_k_, record_count, vec_f.data(), dates, results);
570 571
        }

G
groot 已提交
572
        double span_search = rc.RecordSection("search vectors from engine");
G
groot 已提交
573
        if(!stat.ok()) {
G
groot 已提交
574 575 576 577 578
            return SetError(DB_META_TRANSACTION_FAILED, "Engine failed: " + stat.ToString());
        }

        if(results.empty()) {
            return SERVER_SUCCESS; //empty table
G
groot 已提交
579 580 581
        }

        if(results.size() != record_count) {
G
groot 已提交
582 583 584
            std::string msg = "Search " + std::to_string(record_count) + " vectors but only return "
                              + std::to_string(results.size()) + " results";
            return SetError(SERVER_ILLEGAL_SEARCH_RESULT, msg);
G
groot 已提交
585 586
        }

G
groot 已提交
587
        //step 5: construct result array
588
        ConstructResult(results);
Y
yudong.cai 已提交
589 590 591 592 593

#ifdef MILVUS_ENABLE_PROFILING
        ProfilerStop();
#endif

G
groot 已提交
594 595 596 597 598 599 600 601 602
        double span_result = rc.RecordSection("construct result");
        rc.ElapseFromBegin("totally cost");

        //step 6: print time cost percent
        double total_cost = span_check + span_prepare + span_search + span_result;
        SERVER_LOG_DEBUG << "SearchVectorTask: " << "check validation(" << (span_check/total_cost)*100.0 << "%)"
            << " prepare data(" << (span_prepare/total_cost)*100.0 << "%)"
            << " search(" << (span_search/total_cost)*100.0 << "%)"
            << " construct result(" << (span_result/total_cost)*100.0 << "%)";
603

G
groot 已提交
604
    } catch (std::exception& ex) {
G
groot 已提交
605
        return SetError(SERVER_UNEXPECTED_ERROR, ex.what());
G
groot 已提交
606 607 608 609 610
    }

    return SERVER_SUCCESS;
}

611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
SearchVectorTask1::SearchVectorTask1(const std::string &table_name,
                                     const std::vector<std::string>& file_id_array,
                                     const std::vector<thrift::RowRecord> &query_record_array,
                                     const std::vector<thrift::Range> &query_range_array,
                                     const int64_t top_k,
                                     std::vector<thrift::TopKQueryResult> &result_array)
        : SearchVectorTaskBase(table_name, file_id_array, query_record_array, query_range_array, top_k),
          result_array_(result_array) {

}

BaseTaskPtr SearchVectorTask1::Create(const std::string& table_name,
                                      const std::vector<std::string>& file_id_array,
                                      const std::vector<thrift::RowRecord> & query_record_array,
                                      const std::vector<thrift::Range> & query_range_array,
                                      const int64_t top_k,
                                      std::vector<thrift::TopKQueryResult>& result_array) {
    return std::shared_ptr<BaseTask>(new SearchVectorTask1(table_name, file_id_array,
                                                           query_record_array, query_range_array, top_k, result_array));
}

ServerError SearchVectorTask1::ConstructResult(engine::QueryResults& results) {
    for(uint64_t i = 0; i < results.size(); i++) {
        auto& result = results[i];
        const auto& record = record_array_[i];

        thrift::TopKQueryResult thrift_topk_result;
        for(auto& pair : result) {
            thrift::QueryResult thrift_result;
            thrift_result.__set_id(pair.first);
            thrift_result.__set_distance(pair.second);

            thrift_topk_result.query_result_arrays.emplace_back(thrift_result);
        }
G
groot 已提交
646

647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680
        result_array_.emplace_back(thrift_topk_result);
    }

    return SERVER_SUCCESS;
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
SearchVectorTask2::SearchVectorTask2(const std::string &table_name,
                                     const std::vector<std::string>& file_id_array,
                                     const std::vector<thrift::RowRecord> &query_record_array,
                                     const std::vector<thrift::Range> &query_range_array,
                                     const int64_t top_k,
                                     std::vector<thrift::TopKQueryBinResult> &result_array)
    : SearchVectorTaskBase(table_name, file_id_array, query_record_array, query_range_array, top_k),
      result_array_(result_array) {

}

BaseTaskPtr SearchVectorTask2::Create(const std::string& table_name,
                                     const std::vector<std::string>& file_id_array,
                                     const std::vector<thrift::RowRecord> & query_record_array,
                                     const std::vector<thrift::Range> & query_range_array,
                                     const int64_t top_k,
                                     std::vector<thrift::TopKQueryBinResult>& result_array) {
    return std::shared_ptr<BaseTask>(new SearchVectorTask2(table_name, file_id_array,
            query_record_array, query_range_array, top_k, result_array));
}

ServerError SearchVectorTask2::ConstructResult(engine::QueryResults& results) {
    for(size_t i = 0; i < results.size(); i++) {
        auto& result = results[i];

        thrift::TopKQueryBinResult thrift_topk_result;
        if(result.empty()) {
G
groot 已提交
681
            result_array_.emplace_back(thrift_topk_result);
682
            continue;
G
groot 已提交
683
        }
684

685 686 687 688 689 690
        std::string str_ids, str_distances;
        str_ids.resize(sizeof(engine::IDNumber)*result.size());
        str_distances.resize(sizeof(double)*result.size());

        engine::IDNumber* ids_ptr = (engine::IDNumber*)str_ids.data();
        double* distance_ptr = (double*)str_distances.data();
G
groot 已提交
691
        for(size_t k = 0; k < result.size(); k++) {
692 693 694 695 696 697 698 699
            auto& pair = result[k];
            ids_ptr[k] = pair.first;
            distance_ptr[k] = pair.second;
        }

        thrift_topk_result.__set_id_array(str_ids);
        thrift_topk_result.__set_distance_array(str_distances);
        result_array_.emplace_back(thrift_topk_result);
G
groot 已提交
700 701 702 703 704
    }

    return SERVER_SUCCESS;
}

G
groot 已提交
705 706
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
GetTableRowCountTask::GetTableRowCountTask(const std::string& table_name, int64_t& row_count)
G
groot 已提交
707
: BaseTask(DDL_DML_TASK_GROUP),
G
groot 已提交
708 709 710 711 712 713 714 715 716 717
  table_name_(table_name),
  row_count_(row_count) {

}

BaseTaskPtr GetTableRowCountTask::Create(const std::string& table_name, int64_t& row_count) {
    return std::shared_ptr<BaseTask>(new GetTableRowCountTask(table_name, row_count));
}

ServerError GetTableRowCountTask::OnExecute() {
G
groot 已提交
718 719 720
    try {
        TimeRecorder rc("GetTableRowCountTask");

G
groot 已提交
721
        //step 1: check arguments
J
jinhai 已提交
722 723 724
        ServerError res = SERVER_SUCCESS;
        res = ValidateTableName(table_name_);
        if(res != SERVER_SUCCESS) {
725
            return SetError(res, "Invalid table name: " + table_name_);
G
groot 已提交
726 727 728 729
        }

        //step 2: get row count
        uint64_t row_count = 0;
G
groot 已提交
730
        engine::Status stat = DBWrapper::DB()->GetTableRowCount(table_name_, row_count);
G
groot 已提交
731
        if (!stat.ok()) {
G
groot 已提交
732
            return SetError(DB_META_TRANSACTION_FAILED, "Engine failed: " + stat.ToString());
G
groot 已提交
733 734 735 736
        }

        row_count_ = (int64_t) row_count;

G
groot 已提交
737
        rc.ElapseFromBegin("totally cost");
G
groot 已提交
738 739

    } catch (std::exception& ex) {
G
groot 已提交
740
        return SetError(SERVER_UNEXPECTED_ERROR, ex.what());
G
groot 已提交
741 742
    }

G
groot 已提交
743
    return SERVER_SUCCESS;
G
groot 已提交
744 745
}

G
groot 已提交
746 747 748 749 750 751 752 753 754 755 756 757 758 759
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
PingTask::PingTask(const std::string& cmd, std::string& result)
    : BaseTask(PING_TASK_GROUP),
      cmd_(cmd),
      result_(result) {

}

BaseTaskPtr PingTask::Create(const std::string& cmd, std::string& result) {
    return std::shared_ptr<BaseTask>(new PingTask(cmd, result));
}

ServerError PingTask::OnExecute() {
    if(cmd_ == "version") {
G
groot 已提交
760
        result_ = MILVUS_VERSION;
G
groot 已提交
761 762 763 764 765
    }

    return SERVER_SUCCESS;
}

G
groot 已提交
766 767 768
}
}
}