ExecExprVisitor.cpp 75.4 KB
Newer Older
F
FluorineDog 已提交
1 2 3 4 5 6 7 8 9 10 11
// Copyright (C) 2019-2020 Zilliz. All rights reserved.
//
// 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
//
// 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

Y
yah01 已提交
12 13 14
#include "query/generated/ExecExprVisitor.h"

#include <boost/variant.hpp>
15
#include <boost/utility/binary.hpp>
16
#include <deque>
N
neza2017 已提交
17
#include <optional>
18 19 20
#include <string>
#include <string_view>
#include <type_traits>
21
#include <unordered_set>
22 23
#include <utility>

24
#include "arrow/type_fwd.h"
25 26 27 28
#include "common/Json.h"
#include "common/Types.h"
#include "exceptions/EasyAssert.h"
#include "pb/plan.pb.h"
G
GuoRentong 已提交
29
#include "query/ExprImpl.h"
30
#include "query/Relational.h"
Y
yah01 已提交
31 32
#include "query/Utils.h"
#include "segcore/SegmentGrowingImpl.h"
33
#include "simdjson/error.h"
N
neza2017 已提交
34 35 36 37 38 39 40

namespace milvus::query {
// THIS CONTAINS EXTRA BODY FOR VISITOR
// WILL BE USED BY GENERATOR
namespace impl {
class ExecExprVisitor : ExprVisitor {
 public:
Y
yah01 已提交
41 42 43
    ExecExprVisitor(const segcore::SegmentInternalInterface& segment,
                    int64_t row_count,
                    Timestamp timestamp)
44
        : segment_(segment), row_count_(row_count), timestamp_(timestamp) {
N
neza2017 已提交
45
    }
46 47

    BitsetType
N
neza2017 已提交
48
    call_child(Expr& expr) {
Y
yah01 已提交
49 50
        AssertInfo(!bitset_opt_.has_value(),
                   "[ExecExprVisitor]Bitset already has value before accept");
N
neza2017 已提交
51
        expr.accept(*this);
Y
yah01 已提交
52 53
        AssertInfo(bitset_opt_.has_value(),
                   "[ExecExprVisitor]Bitset doesn't have value after accept");
54 55
        auto res = std::move(bitset_opt_);
        bitset_opt_ = std::nullopt;
56
        return std::move(res.value());
N
neza2017 已提交
57 58
    }

G
GuoRentong 已提交
59
 public:
F
FluorineDog 已提交
60
    template <typename T, typename IndexFunc, typename ElementFunc>
G
GuoRentong 已提交
61
    auto
Y
yah01 已提交
62 63 64
    ExecRangeVisitorImpl(FieldId field_id,
                         IndexFunc func,
                         ElementFunc element_func) -> BitsetType;
G
GuoRentong 已提交
65 66 67

    template <typename T>
    auto
68
    ExecUnaryRangeVisitorDispatcher(UnaryRangeExpr& expr_raw) -> BitsetType;
69

70 71
    template <typename T>
    auto
Y
yah01 已提交
72 73
    ExecBinaryArithOpEvalRangeVisitorDispatcher(
        BinaryArithOpEvalRangeExpr& expr_raw) -> BitsetType;
74

75 76
    template <typename T>
    auto
77
    ExecBinaryRangeVisitorDispatcher(BinaryRangeExpr& expr_raw) -> BitsetType;
G
GuoRentong 已提交
78

S
sunby 已提交
79 80
    template <typename T>
    auto
81
    ExecTermVisitorImpl(TermExpr& expr_raw) -> BitsetType;
S
sunby 已提交
82

83 84 85 86
    template <typename T>
    auto
    ExecTermVisitorImplTemplate(TermExpr& expr_raw) -> BitsetType;

87 88
    template <typename CmpFunc>
    auto
Y
yah01 已提交
89 90
    ExecCompareExprDispatcher(CompareExpr& expr, CmpFunc cmp_func)
        -> BitsetType;
91

N
neza2017 已提交
92
 private:
93 94
    const segcore::SegmentInternalInterface& segment_;
    int64_t row_count_;
95
    Timestamp timestamp_;
96
    BitsetTypeOpt bitset_opt_;
N
neza2017 已提交
97 98 99 100
};
}  // namespace impl

void
F
FluorineDog 已提交
101 102
ExecExprVisitor::visit(LogicalUnaryExpr& expr) {
    using OpType = LogicalUnaryExpr::OpType;
103
    auto child_res = call_child(*expr.child_);
104
    BitsetType res = std::move(child_res);
105 106 107 108 109 110 111
    switch (expr.op_type_) {
        case OpType::LogicalNot: {
            res.flip();
            break;
        }
        default: {
            PanicInfo("Invalid Unary Op");
F
FluorineDog 已提交
112 113
        }
    }
Y
yah01 已提交
114 115
    AssertInfo(res.size() == row_count_,
               "[ExecExprVisitor]Size of results not equal row count");
116
    bitset_opt_ = std::move(res);
N
neza2017 已提交
117 118 119
}

void
F
FluorineDog 已提交
120 121
ExecExprVisitor::visit(LogicalBinaryExpr& expr) {
    using OpType = LogicalBinaryExpr::OpType;
F
FluorineDog 已提交
122 123
    auto left = call_child(*expr.left_);
    auto right = call_child(*expr.right_);
Y
yah01 已提交
124 125
    AssertInfo(left.size() == right.size(),
               "[ExecExprVisitor]Left size not equal to right size");
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
    auto res = std::move(left);
    switch (expr.op_type_) {
        case OpType::LogicalAnd: {
            res &= right;
            break;
        }
        case OpType::LogicalOr: {
            res |= right;
            break;
        }
        case OpType::LogicalXor: {
            res ^= right;
            break;
        }
        case OpType::LogicalMinus: {
            res -= right;
            break;
        }
        default: {
            PanicInfo("Invalid Binary Op");
        }
    }
Y
yah01 已提交
148 149
    AssertInfo(res.size() == row_count_,
               "[ExecExprVisitor]Size of results not equal row count");
150
    bitset_opt_ = std::move(res);
151
}
F
FluorineDog 已提交
152

153
static auto
154 155
Assemble(const std::deque<BitsetType>& srcs) -> BitsetType {
    BitsetType res;
156

157 158 159 160
    if (srcs.size() == 1) {
        return srcs[0];
    }

161 162 163 164 165 166 167 168 169 170
    int64_t total_size = 0;
    for (auto& chunk : srcs) {
        total_size += chunk.size();
    }
    res.resize(total_size);

    int64_t counter = 0;
    for (auto& chunk : srcs) {
        for (int64_t i = 0; i < chunk.size(); ++i) {
            res[counter + i] = chunk[i];
F
FluorineDog 已提交
171
        }
172
        counter += chunk.size();
F
FluorineDog 已提交
173
    }
174
    return res;
N
neza2017 已提交
175 176
}

177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239
void
AppendOneChunk(BitsetType& result, const FixedVector<bool>& chunk_res) {
    // Append a value once instead of BITSET_BLOCK_BIT_SIZE times.
    auto AppendBlock = [&result](const bool* ptr, int n) {
        for (int i = 0; i < n; ++i) {
            BitSetBlockType val = 0;
            // This can use CPU SIMD optimzation
            uint8_t vals[BITSET_BLOCK_SIZE] = {0};
            for (size_t j = 0; j < 8; ++j) {
                for (size_t k = 0; k < BITSET_BLOCK_SIZE; ++k) {
                    vals[k] |= uint8_t(*(ptr + k * 8 + j)) << j;
                }
            }
            for (size_t j = 0; j < BITSET_BLOCK_SIZE; ++j) {
                val |= BitSetBlockType(vals[j]) << (8 * j);
            }
            result.append(val);
            ptr += BITSET_BLOCK_SIZE * 8;
        }
    };
    // Append bit for these bits that can not be union as a block
    // Usually n less than BITSET_BLOCK_BIT_SIZE.
    auto AppendBit = [&result](const bool* ptr, int n) {
        for (int i = 0; i < n; ++i) {
            bool bit = *ptr++;
            result.push_back(bit);
        }
    };

    size_t res_len = result.size();
    size_t chunk_len = chunk_res.size();
    const bool* chunk_ptr = chunk_res.data();

    int n_prefix =
        res_len % BITSET_BLOCK_BIT_SIZE == 0
            ? 0
            : std::min(BITSET_BLOCK_BIT_SIZE - res_len % BITSET_BLOCK_BIT_SIZE,
                       chunk_len);

    AppendBit(chunk_ptr, n_prefix);

    if (n_prefix == chunk_len)
        return;

    size_t n_block = (chunk_len - n_prefix) / BITSET_BLOCK_BIT_SIZE;
    size_t n_suffix = (chunk_len - n_prefix) % BITSET_BLOCK_BIT_SIZE;

    AppendBlock(chunk_ptr + n_prefix, n_block);

    AppendBit(chunk_ptr + n_prefix + n_block * BITSET_BLOCK_BIT_SIZE, n_suffix);

    return;
}

BitsetType
AssembleChunk(const std::vector<FixedVector<bool>>& results) {
    BitsetType assemble_result;
    for (auto& result : results) {
        AppendOneChunk(assemble_result, result);
    }
    return assemble_result;
}

F
FluorineDog 已提交
240
template <typename T, typename IndexFunc, typename ElementFunc>
G
GuoRentong 已提交
241
auto
Y
yah01 已提交
242 243 244
ExecExprVisitor::ExecRangeVisitorImpl(FieldId field_id,
                                      IndexFunc index_func,
                                      ElementFunc element_func) -> BitsetType {
G
GuoRentong 已提交
245
    auto& schema = segment_.get_schema();
246 247
    auto& field_meta = schema[field_id];
    auto indexing_barrier = segment_.num_chunk_index(field_id);
B
BossZou 已提交
248 249
    auto size_per_chunk = segment_.size_per_chunk();
    auto num_chunk = upper_div(row_count_, size_per_chunk);
250
    std::vector<FixedVector<bool>> results;
Y
yah01 已提交
251 252 253
    typedef std::
        conditional_t<std::is_same_v<T, std::string_view>, std::string, T>
            IndexInnerType;
Y
yah01 已提交
254
    using Index = index::ScalarIndex<IndexInnerType>;
F
FluorineDog 已提交
255
    for (auto chunk_id = 0; chunk_id < indexing_barrier; ++chunk_id) {
Y
yah01 已提交
256 257
        const Index& indexing =
            segment_.chunk_scalar_index<IndexInnerType>(field_id, chunk_id);
258 259 260
        // NOTE: knowhere is not const-ready
        // This is a dirty workaround
        auto data = index_func(const_cast<Index*>(&indexing));
261
        AssertInfo(data.size() == size_per_chunk,
Y
yah01 已提交
262
                   "[ExecExprVisitor]Data size not equal to size_per_chunk");
263
        results.emplace_back(std::move(data));
F
FluorineDog 已提交
264
    }
265
    for (auto chunk_id = indexing_barrier; chunk_id < num_chunk; ++chunk_id) {
Y
yah01 已提交
266 267 268
        auto this_size = chunk_id == num_chunk - 1
                             ? row_count_ - chunk_id * size_per_chunk
                             : size_per_chunk;
269
        FixedVector<bool> chunk_res(this_size);
270
        auto chunk = segment_.chunk_data<T>(field_id, chunk_id);
G
GuoRentong 已提交
271
        const T* data = chunk.data();
272
        // Can use CPU SIMD optimazation to speed up
273
        for (int index = 0; index < this_size; ++index) {
274 275
            auto x = data[index];
            chunk_res[index] = element_func(x);
G
GuoRentong 已提交
276
        }
277
        results.emplace_back(std::move(chunk_res));
G
GuoRentong 已提交
278
    }
279
    auto final_result = AssembleChunk(results);
Y
yah01 已提交
280 281
    AssertInfo(final_result.size() == row_count_,
               "[ExecExprVisitor]Final result size not equal to row count");
282
    return final_result;
G
GuoRentong 已提交
283
}
284

285
template <typename T, typename IndexFunc, typename ElementFunc>
286
auto
Y
yah01 已提交
287 288 289
ExecExprVisitor::ExecDataRangeVisitorImpl(FieldId field_id,
                                          IndexFunc index_func,
                                          ElementFunc element_func)
290
    -> BitsetType {
291
    auto& schema = segment_.get_schema();
292
    auto& field_meta = schema[field_id];
293 294
    auto size_per_chunk = segment_.size_per_chunk();
    auto num_chunk = upper_div(row_count_, size_per_chunk);
295 296 297 298
    auto indexing_barrier = segment_.num_chunk_index(field_id);
    auto data_barrier = segment_.num_chunk_data(field_id);
    AssertInfo(std::max(data_barrier, indexing_barrier) == num_chunk,
               "max(data_barrier, index_barrier) not equal to num_chunk");
299
    std::vector<FixedVector<bool>> results;
300

301 302 303 304 305
    // for growing segment, indexing_barrier will always less than data_barrier
    // so growing segment will always execute expr plan using raw data
    // if sealed segment has loaded raw data on this field, then index_barrier = 0 and data_barrier = 1
    // in this case, sealed segment execute expr plan using raw data
    for (auto chunk_id = 0; chunk_id < data_barrier; ++chunk_id) {
Y
yah01 已提交
306 307 308
        auto this_size = chunk_id == num_chunk - 1
                             ? row_count_ - chunk_id * size_per_chunk
                             : size_per_chunk;
309
        FixedVector<bool> result(this_size);
310
        auto chunk = segment_.chunk_data<T>(field_id, chunk_id);
311 312 313 314
        const T* data = chunk.data();
        for (int index = 0; index < this_size; ++index) {
            result[index] = element_func(data[index]);
        }
315 316 317
        AssertInfo(result.size() == this_size,
                   "[ExecExprVisitor]Chunk result size not equal to "
                   "expected size");
318 319
        results.emplace_back(std::move(result));
    }
320 321 322

    // if sealed segment has loaded scalar index for this field, then index_barrier = 1 and data_barrier = 0
    // in this case, sealed segment execute expr plan using scalar index
Y
yah01 已提交
323 324 325
    typedef std::
        conditional_t<std::is_same_v<T, std::string_view>, std::string, T>
            IndexInnerType;
Y
yah01 已提交
326
    using Index = index::ScalarIndex<IndexInnerType>;
Y
yah01 已提交
327 328 329 330
    for (auto chunk_id = data_barrier; chunk_id < indexing_barrier;
         ++chunk_id) {
        auto& indexing =
            segment_.chunk_scalar_index<IndexInnerType>(field_id, chunk_id);
331
        auto this_size = const_cast<Index*>(&indexing)->Count();
332
        FixedVector<bool> result(this_size);
333 334 335 336 337 338
        for (int offset = 0; offset < this_size; ++offset) {
            result[offset] = index_func(const_cast<Index*>(&indexing), offset);
        }
        results.emplace_back(std::move(result));
    }

339
    auto final_result = AssembleChunk(results);
Y
yah01 已提交
340 341
    AssertInfo(final_result.size() == row_count_,
               "[ExecExprVisitor]Final result size not equal to row count");
342 343 344
    return final_result;
}

G
GuoRentong 已提交
345 346 347 348
#pragma clang diagnostic push
#pragma ide diagnostic ignored "Simplify"
template <typename T>
auto
Y
yah01 已提交
349 350 351 352 353
ExecExprVisitor::ExecUnaryRangeVisitorDispatcher(UnaryRangeExpr& expr_raw)
    -> BitsetType {
    typedef std::
        conditional_t<std::is_same_v<T, std::string_view>, std::string, T>
            IndexInnerType;
Y
yah01 已提交
354 355 356
    using Index = index::ScalarIndex<IndexInnerType>;
    auto& expr = static_cast<UnaryRangeExprImpl<IndexInnerType>&>(expr_raw);

357
    auto op = expr.op_type_;
Y
yah01 已提交
358
    auto val = IndexInnerType(expr.value_);
359
    auto field_id = expr.column_.field_id;
360 361
    switch (op) {
        case OpType::Equal: {
362 363
            auto index_func = [&](Index* index) { return index->In(1, &val); };
            auto elem_func = [&](T x) { return (x == val); };
364
            return ExecRangeVisitorImpl<T>(field_id, index_func, elem_func);
365 366
        }
        case OpType::NotEqual: {
367
            auto index_func = [&](Index* index) {
Y
yah01 已提交
368 369
                return index->NotIn(1, &val);
            };
370
            auto elem_func = [&](T x) { return (x != val); };
371
            return ExecRangeVisitorImpl<T>(field_id, index_func, elem_func);
372 373
        }
        case OpType::GreaterEqual: {
374
            auto index_func = [&](Index* index) {
Y
yah01 已提交
375 376
                return index->Range(val, OpType::GreaterEqual);
            };
377
            auto elem_func = [&](T x) { return (x >= val); };
378
            return ExecRangeVisitorImpl<T>(field_id, index_func, elem_func);
G
GuoRentong 已提交
379
        }
380
        case OpType::GreaterThan: {
381
            auto index_func = [&](Index* index) {
Y
yah01 已提交
382 383
                return index->Range(val, OpType::GreaterThan);
            };
384
            auto elem_func = [&](T x) { return (x > val); };
385
            return ExecRangeVisitorImpl<T>(field_id, index_func, elem_func);
386 387
        }
        case OpType::LessEqual: {
388
            auto index_func = [&](Index* index) {
Y
yah01 已提交
389 390
                return index->Range(val, OpType::LessEqual);
            };
391
            auto elem_func = [&](T x) { return (x <= val); };
392
            return ExecRangeVisitorImpl<T>(field_id, index_func, elem_func);
393 394
        }
        case OpType::LessThan: {
395
            auto index_func = [&](Index* index) {
Y
yah01 已提交
396 397
                return index->Range(val, OpType::LessThan);
            };
398
            auto elem_func = [&](T x) { return (x < val); };
399
            return ExecRangeVisitorImpl<T>(field_id, index_func, elem_func);
400 401
        }
        case OpType::PrefixMatch: {
402
            auto index_func = [&](Index* index) {
P
presburger 已提交
403
                auto dataset = std::make_unique<Dataset>();
404 405
                dataset->Set(milvus::index::OPERATOR_TYPE, OpType::PrefixMatch);
                dataset->Set(milvus::index::PREFIX_VALUE, val);
406 407
                return index->Query(std::move(dataset));
            };
408
            auto elem_func = [&](T x) { return Match(x, val, op); };
409
            return ExecRangeVisitorImpl<T>(field_id, index_func, elem_func);
410 411
        }
        // TODO: PostfixMatch
412
        default: {
G
GuoRentong 已提交
413 414
            PanicInfo("unsupported range node");
        }
415 416 417 418
    }
}
#pragma clang diagnostic pop

419 420 421 422 423 424 425 426 427
template <typename ExprValueType>
auto
ExecExprVisitor::ExecUnaryRangeVisitorDispatcherJson(UnaryRangeExpr& expr_raw)
    -> BitsetType {
    using Index = index::ScalarIndex<milvus::Json>;
    auto& expr = static_cast<UnaryRangeExprImpl<ExprValueType>&>(expr_raw);

    auto op = expr.op_type_;
    auto val = expr.value_;
428
    auto pointer = milvus::Json::pointer(std::move(expr.column_.nested_path));
429
    auto field_id = expr.column_.field_id;
430
    auto index_func = [=](Index* index) { return TargetBitmap{}; };
431 432 433 434 435
    using GetType =
        std::conditional_t<std::is_same_v<ExprValueType, std::string>,
                           std::string_view,
                           ExprValueType>;

436 437 438 439 440 441 442 443 444 445 446
#define UnaryRangeJSONCompare(cmp)                            \
    do {                                                      \
        auto x = json.template at<GetType>(pointer);          \
        if (x.error()) {                                      \
            if constexpr (std::is_same_v<GetType, int64_t>) { \
                auto x = json.template at<double>(pointer);   \
                return !x.error() && (cmp);                   \
            }                                                 \
            return false;                                     \
        }                                                     \
        return (cmp);                                         \
447 448
    } while (false)

449 450 451 452 453 454 455 456 457 458 459
#define UnaryRangeJSONCompareNotEqual(cmp)                    \
    do {                                                      \
        auto x = json.template at<GetType>(pointer);          \
        if (x.error()) {                                      \
            if constexpr (std::is_same_v<GetType, int64_t>) { \
                auto x = json.template at<double>(pointer);   \
                return x.error() || (cmp);                    \
            }                                                 \
            return true;                                      \
        }                                                     \
        return (cmp);                                         \
460 461
    } while (false)

462 463
    switch (op) {
        case OpType::Equal: {
464
            auto elem_func = [&](const milvus::Json& json) {
465
                UnaryRangeJSONCompare(x.value() == val);
466 467 468 469 470
            };
            return ExecRangeVisitorImpl<milvus::Json>(
                field_id, index_func, elem_func);
        }
        case OpType::NotEqual: {
471
            auto elem_func = [&](const milvus::Json& json) {
472
                UnaryRangeJSONCompareNotEqual(x.value() != val);
473 474 475 476 477
            };
            return ExecRangeVisitorImpl<milvus::Json>(
                field_id, index_func, elem_func);
        }
        case OpType::GreaterEqual: {
478
            auto elem_func = [&](const milvus::Json& json) {
479
                UnaryRangeJSONCompare(x.value() >= val);
480 481 482 483 484
            };
            return ExecRangeVisitorImpl<milvus::Json>(
                field_id, index_func, elem_func);
        }
        case OpType::GreaterThan: {
485
            auto elem_func = [&](const milvus::Json& json) {
486
                UnaryRangeJSONCompare(x.value() > val);
487 488 489 490 491
            };
            return ExecRangeVisitorImpl<milvus::Json>(
                field_id, index_func, elem_func);
        }
        case OpType::LessEqual: {
492
            auto elem_func = [&](const milvus::Json& json) {
493
                UnaryRangeJSONCompare(x.value() <= val);
494 495 496 497 498
            };
            return ExecRangeVisitorImpl<milvus::Json>(
                field_id, index_func, elem_func);
        }
        case OpType::LessThan: {
499
            auto elem_func = [&](const milvus::Json& json) {
500
                UnaryRangeJSONCompare(x.value() < val);
501 502 503 504 505
            };
            return ExecRangeVisitorImpl<milvus::Json>(
                field_id, index_func, elem_func);
        }
        case OpType::PrefixMatch: {
506
            auto elem_func = [&](const milvus::Json& json) {
507
                UnaryRangeJSONCompare(Match(ExprValueType(x.value()), val, op));
508 509 510 511 512 513 514 515 516 517 518
            };
            return ExecRangeVisitorImpl<milvus::Json>(
                field_id, index_func, elem_func);
        }
        // TODO: PostfixMatch
        default: {
            PanicInfo("unsupported range node");
        }
    }
}

519 520 521 522
#pragma clang diagnostic push
#pragma ide diagnostic ignored "Simplify"
template <typename T>
auto
Y
yah01 已提交
523 524
ExecExprVisitor::ExecBinaryArithOpEvalRangeVisitorDispatcher(
    BinaryArithOpEvalRangeExpr& expr_raw) -> BitsetType {
525
    auto& expr = static_cast<BinaryArithOpEvalRangeExprImpl<T>&>(expr_raw);
526
    using Index = index::ScalarIndex<T>;
527 528 529 530
    auto arith_op = expr.arith_op_;
    auto right_operand = expr.right_operand_;
    auto op = expr.op_type_;
    auto val = expr.value_;
531
    auto& nested_path = expr.column_.nested_path;
532 533 534 535 536

    switch (op) {
        case OpType::Equal: {
            switch (arith_op) {
                case ArithOpType::Add: {
Y
yah01 已提交
537 538
                    auto index_func = [val, right_operand](Index* index,
                                                           size_t offset) {
539 540 541
                        auto x = index->Reverse_Lookup(offset);
                        return (x + right_operand) == val;
                    };
542 543 544
                    auto elem_func = [val, right_operand, &nested_path](T x) {
                        // visit the nested field
                        // now it must be Json
Y
yah01 已提交
545 546 547
                        return ((x + right_operand) == val);
                    };
                    return ExecDataRangeVisitorImpl<T>(
548
                        expr.column_.field_id, index_func, elem_func);
549 550
                }
                case ArithOpType::Sub: {
Y
yah01 已提交
551 552
                    auto index_func = [val, right_operand](Index* index,
                                                           size_t offset) {
553 554 555
                        auto x = index->Reverse_Lookup(offset);
                        return (x - right_operand) == val;
                    };
Y
yah01 已提交
556 557 558 559
                    auto elem_func = [val, right_operand](T x) {
                        return ((x - right_operand) == val);
                    };
                    return ExecDataRangeVisitorImpl<T>(
560
                        expr.column_.field_id, index_func, elem_func);
561 562
                }
                case ArithOpType::Mul: {
Y
yah01 已提交
563 564
                    auto index_func = [val, right_operand](Index* index,
                                                           size_t offset) {
565 566 567
                        auto x = index->Reverse_Lookup(offset);
                        return (x * right_operand) == val;
                    };
Y
yah01 已提交
568 569 570 571
                    auto elem_func = [val, right_operand](T x) {
                        return ((x * right_operand) == val);
                    };
                    return ExecDataRangeVisitorImpl<T>(
572
                        expr.column_.field_id, index_func, elem_func);
573 574
                }
                case ArithOpType::Div: {
Y
yah01 已提交
575 576
                    auto index_func = [val, right_operand](Index* index,
                                                           size_t offset) {
577 578 579
                        auto x = index->Reverse_Lookup(offset);
                        return (x / right_operand) == val;
                    };
Y
yah01 已提交
580 581 582 583
                    auto elem_func = [val, right_operand](T x) {
                        return ((x / right_operand) == val);
                    };
                    return ExecDataRangeVisitorImpl<T>(
584
                        expr.column_.field_id, index_func, elem_func);
585 586
                }
                case ArithOpType::Mod: {
Y
yah01 已提交
587 588
                    auto index_func = [val, right_operand](Index* index,
                                                           size_t offset) {
589 590 591
                        auto x = index->Reverse_Lookup(offset);
                        return static_cast<T>(fmod(x, right_operand)) == val;
                    };
592 593 594
                    auto elem_func = [val, right_operand](T x) {
                        return (static_cast<T>(fmod(x, right_operand)) == val);
                    };
Y
yah01 已提交
595
                    return ExecDataRangeVisitorImpl<T>(
596
                        expr.column_.field_id, index_func, elem_func);
597 598 599 600 601 602 603 604 605
                }
                default: {
                    PanicInfo("unsupported arithmetic operation");
                }
            }
        }
        case OpType::NotEqual: {
            switch (arith_op) {
                case ArithOpType::Add: {
Y
yah01 已提交
606 607
                    auto index_func = [val, right_operand](Index* index,
                                                           size_t offset) {
608 609 610
                        auto x = index->Reverse_Lookup(offset);
                        return (x + right_operand) != val;
                    };
Y
yah01 已提交
611 612 613 614
                    auto elem_func = [val, right_operand](T x) {
                        return ((x + right_operand) != val);
                    };
                    return ExecDataRangeVisitorImpl<T>(
615
                        expr.column_.field_id, index_func, elem_func);
616 617
                }
                case ArithOpType::Sub: {
Y
yah01 已提交
618 619
                    auto index_func = [val, right_operand](Index* index,
                                                           size_t offset) {
620 621 622
                        auto x = index->Reverse_Lookup(offset);
                        return (x - right_operand) != val;
                    };
Y
yah01 已提交
623 624 625 626
                    auto elem_func = [val, right_operand](T x) {
                        return ((x - right_operand) != val);
                    };
                    return ExecDataRangeVisitorImpl<T>(
627
                        expr.column_.field_id, index_func, elem_func);
628 629
                }
                case ArithOpType::Mul: {
Y
yah01 已提交
630 631
                    auto index_func = [val, right_operand](Index* index,
                                                           size_t offset) {
632 633 634
                        auto x = index->Reverse_Lookup(offset);
                        return (x * right_operand) != val;
                    };
Y
yah01 已提交
635 636 637 638
                    auto elem_func = [val, right_operand](T x) {
                        return ((x * right_operand) != val);
                    };
                    return ExecDataRangeVisitorImpl<T>(
639
                        expr.column_.field_id, index_func, elem_func);
640 641
                }
                case ArithOpType::Div: {
Y
yah01 已提交
642 643
                    auto index_func = [val, right_operand](Index* index,
                                                           size_t offset) {
644 645 646
                        auto x = index->Reverse_Lookup(offset);
                        return (x / right_operand) != val;
                    };
Y
yah01 已提交
647 648 649 650
                    auto elem_func = [val, right_operand](T x) {
                        return ((x / right_operand) != val);
                    };
                    return ExecDataRangeVisitorImpl<T>(
651
                        expr.column_.field_id, index_func, elem_func);
652 653
                }
                case ArithOpType::Mod: {
Y
yah01 已提交
654 655
                    auto index_func = [val, right_operand](Index* index,
                                                           size_t offset) {
656 657 658
                        auto x = index->Reverse_Lookup(offset);
                        return static_cast<T>(fmod(x, right_operand)) != val;
                    };
659 660 661
                    auto elem_func = [val, right_operand](T x) {
                        return (static_cast<T>(fmod(x, right_operand)) != val);
                    };
Y
yah01 已提交
662
                    return ExecDataRangeVisitorImpl<T>(
663
                        expr.column_.field_id, index_func, elem_func);
664 665 666 667 668 669 670 671 672 673 674 675 676
                }
                default: {
                    PanicInfo("unsupported arithmetic operation");
                }
            }
        }
        default: {
            PanicInfo("unsupported range node with arithmetic operation");
        }
    }
}
#pragma clang diagnostic pop

677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692
template <typename ExprValueType>
auto
ExecExprVisitor::ExecBinaryArithOpEvalRangeVisitorDispatcherJson(
    BinaryArithOpEvalRangeExpr& expr_raw) -> BitsetType {
    auto& expr =
        static_cast<BinaryArithOpEvalRangeExprImpl<ExprValueType>&>(expr_raw);
    using Index = index::ScalarIndex<milvus::Json>;
    using GetType =
        std::conditional_t<std::is_same_v<ExprValueType, std::string>,
                           std::string_view,
                           ExprValueType>;

    auto arith_op = expr.arith_op_;
    auto right_operand = expr.right_operand_;
    auto op = expr.op_type_;
    auto val = expr.value_;
693 694 695 696 697 698 699 700 701 702 703 704 705
    auto pointer = milvus::Json::pointer(std::move(expr.column_.nested_path));

#define BinaryArithRangeJSONCompare(cmp)                      \
    do {                                                      \
        auto x = json.template at<GetType>(pointer);          \
        if (x.error()) {                                      \
            if constexpr (std::is_same_v<GetType, int64_t>) { \
                auto x = json.template at<double>(pointer);   \
                return !x.error() && (cmp);                   \
            }                                                 \
            return false;                                     \
        }                                                     \
        return (cmp);                                         \
706 707
    } while (false)

708 709 710 711 712 713 714 715 716 717 718
#define BinaryArithRangeJSONCompareNotEqual(cmp)              \
    do {                                                      \
        auto x = json.template at<GetType>(pointer);          \
        if (x.error()) {                                      \
            if constexpr (std::is_same_v<GetType, int64_t>) { \
                auto x = json.template at<double>(pointer);   \
                return x.error() || (cmp);                    \
            }                                                 \
            return true;                                      \
        }                                                     \
        return (cmp);                                         \
719 720
    } while (false)

721 722 723 724 725 726 727 728 729
    switch (op) {
        case OpType::Equal: {
            switch (arith_op) {
                case ArithOpType::Add: {
                    auto index_func = [val, right_operand](Index* index,
                                                           size_t offset) {
                        return false;
                    };
                    auto elem_func = [&](const milvus::Json& json) {
730 731
                        BinaryArithRangeJSONCompare(x.value() + right_operand ==
                                                    val);
732 733 734 735 736 737 738 739 740 741
                    };
                    return ExecDataRangeVisitorImpl<milvus::Json>(
                        expr.column_.field_id, index_func, elem_func);
                }
                case ArithOpType::Sub: {
                    auto index_func = [val, right_operand](Index* index,
                                                           size_t offset) {
                        return false;
                    };
                    auto elem_func = [&](const milvus::Json& json) {
742 743
                        BinaryArithRangeJSONCompare(x.value() - right_operand ==
                                                    val);
744 745 746 747 748 749 750 751 752 753
                    };
                    return ExecDataRangeVisitorImpl<milvus::Json>(
                        expr.column_.field_id, index_func, elem_func);
                }
                case ArithOpType::Mul: {
                    auto index_func = [val, right_operand](Index* index,
                                                           size_t offset) {
                        return false;
                    };
                    auto elem_func = [&](const milvus::Json& json) {
754 755
                        BinaryArithRangeJSONCompare(x.value() * right_operand ==
                                                    val);
756 757 758 759 760 761 762 763 764 765
                    };
                    return ExecDataRangeVisitorImpl<milvus::Json>(
                        expr.column_.field_id, index_func, elem_func);
                }
                case ArithOpType::Div: {
                    auto index_func = [val, right_operand](Index* index,
                                                           size_t offset) {
                        return false;
                    };
                    auto elem_func = [&](const milvus::Json& json) {
766 767
                        BinaryArithRangeJSONCompare(x.value() / right_operand ==
                                                    val);
768 769 770 771 772 773 774 775 776 777
                    };
                    return ExecDataRangeVisitorImpl<milvus::Json>(
                        expr.column_.field_id, index_func, elem_func);
                }
                case ArithOpType::Mod: {
                    auto index_func = [val, right_operand](Index* index,
                                                           size_t offset) {
                        return false;
                    };
                    auto elem_func = [&](const milvus::Json& json) {
778 779 780
                        BinaryArithRangeJSONCompare(
                            static_cast<ExprValueType>(
                                fmod(x.value(), right_operand)) == val);
781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797
                    };
                    return ExecDataRangeVisitorImpl<milvus::Json>(
                        expr.column_.field_id, index_func, elem_func);
                }
                default: {
                    PanicInfo("unsupported arithmetic operation");
                }
            }
        }
        case OpType::NotEqual: {
            switch (arith_op) {
                case ArithOpType::Add: {
                    auto index_func = [val, right_operand](Index* index,
                                                           size_t offset) {
                        return false;
                    };
                    auto elem_func = [&](const milvus::Json& json) {
798 799
                        BinaryArithRangeJSONCompareNotEqual(
                            x.value() + right_operand != val);
800 801 802 803 804 805 806 807 808 809
                    };
                    return ExecDataRangeVisitorImpl<milvus::Json>(
                        expr.column_.field_id, index_func, elem_func);
                }
                case ArithOpType::Sub: {
                    auto index_func = [val, right_operand](Index* index,
                                                           size_t offset) {
                        return false;
                    };
                    auto elem_func = [&](const milvus::Json& json) {
810 811
                        BinaryArithRangeJSONCompareNotEqual(
                            x.value() - right_operand != val);
812 813 814 815 816 817 818 819 820 821
                    };
                    return ExecDataRangeVisitorImpl<milvus::Json>(
                        expr.column_.field_id, index_func, elem_func);
                }
                case ArithOpType::Mul: {
                    auto index_func = [val, right_operand](Index* index,
                                                           size_t offset) {
                        return false;
                    };
                    auto elem_func = [&](const milvus::Json& json) {
822 823
                        BinaryArithRangeJSONCompareNotEqual(
                            x.value() * right_operand != val);
824 825 826 827 828 829 830 831 832 833
                    };
                    return ExecDataRangeVisitorImpl<milvus::Json>(
                        expr.column_.field_id, index_func, elem_func);
                }
                case ArithOpType::Div: {
                    auto index_func = [val, right_operand](Index* index,
                                                           size_t offset) {
                        return false;
                    };
                    auto elem_func = [&](const milvus::Json& json) {
834 835
                        BinaryArithRangeJSONCompareNotEqual(
                            x.value() / right_operand != val);
836 837 838 839 840 841 842 843 844 845
                    };
                    return ExecDataRangeVisitorImpl<milvus::Json>(
                        expr.column_.field_id, index_func, elem_func);
                }
                case ArithOpType::Mod: {
                    auto index_func = [val, right_operand](Index* index,
                                                           size_t offset) {
                        return false;
                    };
                    auto elem_func = [&](const milvus::Json& json) {
846 847 848
                        BinaryArithRangeJSONCompareNotEqual(
                            static_cast<ExprValueType>(
                                fmod(x.value(), right_operand)) != val);
849 850 851 852 853 854 855 856 857 858 859 860 861
                    };
                    return ExecDataRangeVisitorImpl<milvus::Json>(
                        expr.column_.field_id, index_func, elem_func);
                }
                default: {
                    PanicInfo("unsupported arithmetic operation");
                }
            }
        }
        default: {
            PanicInfo("unsupported range node with arithmetic operation");
        }
    }
862
}  // namespace milvus::query
863

864 865 866 867
#pragma clang diagnostic push
#pragma ide diagnostic ignored "Simplify"
template <typename T>
auto
Y
yah01 已提交
868 869 870 871 872
ExecExprVisitor::ExecBinaryRangeVisitorDispatcher(BinaryRangeExpr& expr_raw)
    -> BitsetType {
    typedef std::
        conditional_t<std::is_same_v<T, std::string_view>, std::string, T>
            IndexInnerType;
Y
yah01 已提交
873 874 875
    using Index = index::ScalarIndex<IndexInnerType>;
    auto& expr = static_cast<BinaryRangeExprImpl<IndexInnerType>&>(expr_raw);

876 877
    bool lower_inclusive = expr.lower_inclusive_;
    bool upper_inclusive = expr.upper_inclusive_;
878 879
    IndexInnerType val1 = expr.lower_value_;
    IndexInnerType val2 = expr.upper_value_;
880

Y
yah01 已提交
881 882 883
    auto index_func = [=](Index* index) {
        return index->Range(val1, lower_inclusive, val2, upper_inclusive);
    };
884 885
    if (lower_inclusive && upper_inclusive) {
        auto elem_func = [val1, val2](T x) { return (val1 <= x && x <= val2); };
886 887
        return ExecRangeVisitorImpl<T>(
            expr.column_.field_id, index_func, elem_func);
888 889
    } else if (lower_inclusive && !upper_inclusive) {
        auto elem_func = [val1, val2](T x) { return (val1 <= x && x < val2); };
890 891
        return ExecRangeVisitorImpl<T>(
            expr.column_.field_id, index_func, elem_func);
892 893
    } else if (!lower_inclusive && upper_inclusive) {
        auto elem_func = [val1, val2](T x) { return (val1 < x && x <= val2); };
894 895
        return ExecRangeVisitorImpl<T>(
            expr.column_.field_id, index_func, elem_func);
G
GuoRentong 已提交
896
    } else {
897
        auto elem_func = [val1, val2](T x) { return (val1 < x && x < val2); };
898 899
        return ExecRangeVisitorImpl<T>(
            expr.column_.field_id, index_func, elem_func);
G
GuoRentong 已提交
900 901 902 903
    }
}
#pragma clang diagnostic pop

904 905 906 907 908 909 910 911 912 913 914 915 916 917 918
template <typename ExprValueType>
auto
ExecExprVisitor::ExecBinaryRangeVisitorDispatcherJson(BinaryRangeExpr& expr_raw)
    -> BitsetType {
    using Index = index::ScalarIndex<milvus::Json>;
    using GetType =
        std::conditional_t<std::is_same_v<ExprValueType, std::string>,
                           std::string_view,
                           ExprValueType>;

    auto& expr = static_cast<BinaryRangeExprImpl<ExprValueType>&>(expr_raw);
    bool lower_inclusive = expr.lower_inclusive_;
    bool upper_inclusive = expr.upper_inclusive_;
    ExprValueType val1 = expr.lower_value_;
    ExprValueType val2 = expr.upper_value_;
919
    auto pointer = milvus::Json::pointer(std::move(expr.column_.nested_path));
920 921

    // no json index now
922
    auto index_func = [=](Index* index) { return TargetBitmap{}; };
923

924 925 926 927 928 929 930 931 932 933 934 935 936 937 938
#define BinaryRangeJSONCompare(cmp)                           \
    do {                                                      \
        auto x = json.template at<GetType>(pointer);          \
        if (x.error()) {                                      \
            if constexpr (std::is_same_v<GetType, int64_t>) { \
                auto x = json.template at<double>(pointer);   \
                if (!x.error()) {                             \
                    auto value = x.value();                   \
                    return (cmp);                             \
                }                                             \
            }                                                 \
            return false;                                     \
        }                                                     \
        auto value = x.value();                               \
        return (cmp);                                         \
939 940
    } while (false)

941 942
    if (lower_inclusive && upper_inclusive) {
        auto elem_func = [&](const milvus::Json& json) {
943
            BinaryRangeJSONCompare(val1 <= value && value <= val2);
944 945 946 947 948
        };
        return ExecRangeVisitorImpl<milvus::Json>(
            expr.column_.field_id, index_func, elem_func);
    } else if (lower_inclusive && !upper_inclusive) {
        auto elem_func = [&](const milvus::Json& json) {
949
            BinaryRangeJSONCompare(val1 <= value && value < val2);
950 951 952 953 954
        };
        return ExecRangeVisitorImpl<milvus::Json>(
            expr.column_.field_id, index_func, elem_func);
    } else if (!lower_inclusive && upper_inclusive) {
        auto elem_func = [&](const milvus::Json& json) {
955
            BinaryRangeJSONCompare(val1 < value && value <= val2);
956 957 958 959 960
        };
        return ExecRangeVisitorImpl<milvus::Json>(
            expr.column_.field_id, index_func, elem_func);
    } else {
        auto elem_func = [&](const milvus::Json& json) {
961
            BinaryRangeJSONCompare(val1 < value && value < val2);
962 963 964 965 966 967
        };
        return ExecRangeVisitorImpl<milvus::Json>(
            expr.column_.field_id, index_func, elem_func);
    }
}

N
neza2017 已提交
968
void
969
ExecExprVisitor::visit(UnaryRangeExpr& expr) {
970 971
    auto& field_meta = segment_.get_schema()[expr.column_.field_id];
    AssertInfo(expr.column_.data_type == field_meta.get_data_type(),
972
               "[ExecExprVisitor]DataType of expr isn't field_meta data type");
973
    BitsetType res;
974
    switch (expr.column_.data_type) {
N
neza2017 已提交
975
        case DataType::BOOL: {
976
            res = ExecUnaryRangeVisitorDispatcher<bool>(expr);
N
neza2017 已提交
977 978
            break;
        }
G
GuoRentong 已提交
979
        case DataType::INT8: {
980
            res = ExecUnaryRangeVisitorDispatcher<int8_t>(expr);
G
GuoRentong 已提交
981 982 983
            break;
        }
        case DataType::INT16: {
984
            res = ExecUnaryRangeVisitorDispatcher<int16_t>(expr);
G
GuoRentong 已提交
985 986 987
            break;
        }
        case DataType::INT32: {
988
            res = ExecUnaryRangeVisitorDispatcher<int32_t>(expr);
G
GuoRentong 已提交
989 990 991
            break;
        }
        case DataType::INT64: {
992
            res = ExecUnaryRangeVisitorDispatcher<int64_t>(expr);
G
GuoRentong 已提交
993 994 995
            break;
        }
        case DataType::FLOAT: {
996
            res = ExecUnaryRangeVisitorDispatcher<float>(expr);
G
GuoRentong 已提交
997 998 999
            break;
        }
        case DataType::DOUBLE: {
1000 1001 1002
            res = ExecUnaryRangeVisitorDispatcher<double>(expr);
            break;
        }
1003
        case DataType::VARCHAR: {
Y
yah01 已提交
1004 1005 1006 1007 1008
            if (segment_.type() == SegmentType::Growing) {
                res = ExecUnaryRangeVisitorDispatcher<std::string>(expr);
            } else {
                res = ExecUnaryRangeVisitorDispatcher<std::string_view>(expr);
            }
1009 1010
            break;
        }
1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031
        case DataType::JSON: {
            switch (expr.val_case_) {
                case proto::plan::GenericValue::ValCase::kBoolVal:
                    res = ExecUnaryRangeVisitorDispatcherJson<bool>(expr);
                    break;
                case proto::plan::GenericValue::ValCase::kInt64Val:
                    res = ExecUnaryRangeVisitorDispatcherJson<int64_t>(expr);
                    break;
                case proto::plan::GenericValue::ValCase::kFloatVal:
                    res = ExecUnaryRangeVisitorDispatcherJson<double>(expr);
                    break;
                case proto::plan::GenericValue::ValCase::kStringVal:
                    res =
                        ExecUnaryRangeVisitorDispatcherJson<std::string>(expr);
                    break;
                default:
                    PanicInfo(
                        fmt::format("unknown data type: {}", expr.val_case_));
            }
            break;
        }
1032
        default:
1033 1034
            PanicInfo(fmt::format("unsupported data type: {}",
                                  expr.column_.data_type));
1035
    }
Y
yah01 已提交
1036 1037
    AssertInfo(res.size() == row_count_,
               "[ExecExprVisitor]Size of results not equal row count");
1038
    bitset_opt_ = std::move(res);
1039 1040
}

1041 1042
void
ExecExprVisitor::visit(BinaryArithOpEvalRangeExpr& expr) {
1043 1044
    auto& field_meta = segment_.get_schema()[expr.column_.field_id];
    AssertInfo(expr.column_.data_type == field_meta.get_data_type(),
1045 1046
               "[ExecExprVisitor]DataType of expr isn't field_meta data type");
    BitsetType res;
1047
    switch (expr.column_.data_type) {
1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071
        case DataType::INT8: {
            res = ExecBinaryArithOpEvalRangeVisitorDispatcher<int8_t>(expr);
            break;
        }
        case DataType::INT16: {
            res = ExecBinaryArithOpEvalRangeVisitorDispatcher<int16_t>(expr);
            break;
        }
        case DataType::INT32: {
            res = ExecBinaryArithOpEvalRangeVisitorDispatcher<int32_t>(expr);
            break;
        }
        case DataType::INT64: {
            res = ExecBinaryArithOpEvalRangeVisitorDispatcher<int64_t>(expr);
            break;
        }
        case DataType::FLOAT: {
            res = ExecBinaryArithOpEvalRangeVisitorDispatcher<float>(expr);
            break;
        }
        case DataType::DOUBLE: {
            res = ExecBinaryArithOpEvalRangeVisitorDispatcher<double>(expr);
            break;
        }
1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090
        case DataType::JSON: {
            switch (expr.val_case_) {
                case proto::plan::GenericValue::ValCase::kBoolVal: {
                    res = ExecBinaryArithOpEvalRangeVisitorDispatcherJson<bool>(
                        expr);
                    break;
                }
                case proto::plan::GenericValue::ValCase::kInt64Val: {
                    res = ExecBinaryArithOpEvalRangeVisitorDispatcherJson<
                        int64_t>(expr);
                    break;
                }
                case proto::plan::GenericValue::ValCase::kFloatVal: {
                    res =
                        ExecBinaryArithOpEvalRangeVisitorDispatcherJson<double>(
                            expr);
                    break;
                }
                default: {
1091 1092 1093
                    PanicInfo(
                        fmt::format("unsupported value type {} in expression",
                                    expr.val_case_));
1094 1095 1096 1097
                }
            }
            break;
        }
1098
        default:
1099 1100
            PanicInfo(fmt::format("unsupported data type: {}",
                                  expr.column_.data_type));
1101
    }
Y
yah01 已提交
1102 1103
    AssertInfo(res.size() == row_count_,
               "[ExecExprVisitor]Size of results not equal row count");
1104 1105 1106
    bitset_opt_ = std::move(res);
}

1107 1108
void
ExecExprVisitor::visit(BinaryRangeExpr& expr) {
1109 1110
    auto& field_meta = segment_.get_schema()[expr.column_.field_id];
    AssertInfo(expr.column_.data_type == field_meta.get_data_type(),
1111
               "[ExecExprVisitor]DataType of expr isn't field_meta data type");
1112
    BitsetType res;
1113
    switch (expr.column_.data_type) {
1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139
        case DataType::BOOL: {
            res = ExecBinaryRangeVisitorDispatcher<bool>(expr);
            break;
        }
        case DataType::INT8: {
            res = ExecBinaryRangeVisitorDispatcher<int8_t>(expr);
            break;
        }
        case DataType::INT16: {
            res = ExecBinaryRangeVisitorDispatcher<int16_t>(expr);
            break;
        }
        case DataType::INT32: {
            res = ExecBinaryRangeVisitorDispatcher<int32_t>(expr);
            break;
        }
        case DataType::INT64: {
            res = ExecBinaryRangeVisitorDispatcher<int64_t>(expr);
            break;
        }
        case DataType::FLOAT: {
            res = ExecBinaryRangeVisitorDispatcher<float>(expr);
            break;
        }
        case DataType::DOUBLE: {
            res = ExecBinaryRangeVisitorDispatcher<double>(expr);
G
GuoRentong 已提交
1140 1141
            break;
        }
1142
        case DataType::VARCHAR: {
Y
yah01 已提交
1143 1144 1145 1146 1147
            if (segment_.type() == SegmentType::Growing) {
                res = ExecBinaryRangeVisitorDispatcher<std::string>(expr);
            } else {
                res = ExecBinaryRangeVisitorDispatcher<std::string_view>(expr);
            }
1148 1149
            break;
        }
1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169
        case DataType::JSON: {
            switch (expr.val_case_) {
                case proto::plan::GenericValue::ValCase::kBoolVal: {
                    res = ExecBinaryRangeVisitorDispatcherJson<bool>(expr);
                    break;
                }
                case proto::plan::GenericValue::ValCase::kInt64Val: {
                    res = ExecBinaryRangeVisitorDispatcherJson<int64_t>(expr);
                    break;
                }
                case proto::plan::GenericValue::ValCase::kFloatVal: {
                    res = ExecBinaryRangeVisitorDispatcherJson<double>(expr);
                    break;
                }
                case proto::plan::GenericValue::ValCase::kStringVal: {
                    res =
                        ExecBinaryRangeVisitorDispatcherJson<std::string>(expr);
                    break;
                }
                default: {
1170 1171 1172
                    PanicInfo(
                        fmt::format("unsupported value type {} in expression",
                                    expr.val_case_));
1173 1174 1175 1176
                }
            }
            break;
        }
G
GuoRentong 已提交
1177
        default:
1178 1179
            PanicInfo(fmt::format("unsupported data type: {}",
                                  expr.column_.data_type));
G
GuoRentong 已提交
1180
    }
Y
yah01 已提交
1181 1182
    AssertInfo(res.size() == row_count_,
               "[ExecExprVisitor]Size of results not equal row count");
1183
    bitset_opt_ = std::move(res);
N
neza2017 已提交
1184 1185
}

1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199
template <typename Op>
struct relational {
    template <typename T, typename U>
    bool
    operator()(T const& a, U const& b) const {
        return Op{}(a, b);
    }
    template <typename... T>
    bool
    operator()(T const&...) const {
        PanicInfo("incompatible operands");
    }
};

1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323
template <typename T, typename U, typename CmpFunc>
TargetBitmap
ExecExprVisitor::ExecCompareRightType(const T* left_raw_data,
                                      const FieldId& right_field_id,
                                      const int64_t current_chunk_id,
                                      CmpFunc cmp_func) {
    auto size_per_chunk = segment_.size_per_chunk();
    auto num_chunks = upper_div(row_count_, size_per_chunk);
    auto size = current_chunk_id == num_chunks - 1
                    ? row_count_ - current_chunk_id * size_per_chunk
                    : size_per_chunk;

    TargetBitmap result(size);
    const U* right_raw_data =
        segment_.chunk_data<U>(right_field_id, current_chunk_id).data();

    for (int i = 0; i < size; ++i) {
        result[i] = cmp_func(left_raw_data[i], right_raw_data[i]);
    }

    return result;
}

template <typename T, typename CmpFunc>
BitsetType
ExecExprVisitor::ExecCompareLeftType(const FieldId& left_field_id,
                                     const FieldId& right_field_id,
                                     const DataType& right_field_type,
                                     CmpFunc cmp_func) {
    std::vector<FixedVector<bool>> results;

    auto size_per_chunk = segment_.size_per_chunk();
    auto num_chunks = upper_div(row_count_, size_per_chunk);

    for (int64_t chunk_id = 0; chunk_id < num_chunks; ++chunk_id) {
        FixedVector<bool> result;
        const T* left_raw_data =
            segment_.chunk_data<T>(left_field_id, chunk_id).data();

        switch (right_field_type) {
            case DataType::BOOL:
                result = ExecCompareRightType<T, bool, CmpFunc>(
                    left_raw_data, right_field_id, chunk_id, cmp_func);
                break;
            case DataType::INT8:
                result = ExecCompareRightType<T, int8_t, CmpFunc>(
                    left_raw_data, right_field_id, chunk_id, cmp_func);
                break;
            case DataType::INT16:
                result = ExecCompareRightType<T, int16_t, CmpFunc>(
                    left_raw_data, right_field_id, chunk_id, cmp_func);
                break;
            case DataType::INT32:
                result = ExecCompareRightType<T, int32_t, CmpFunc>(
                    left_raw_data, right_field_id, chunk_id, cmp_func);
                break;
            case DataType::INT64:
                result = ExecCompareRightType<T, int64_t, CmpFunc>(
                    left_raw_data, right_field_id, chunk_id, cmp_func);
                break;
            case DataType::FLOAT:
                result = ExecCompareRightType<T, float, CmpFunc>(
                    left_raw_data, right_field_id, chunk_id, cmp_func);
                break;
            case DataType::DOUBLE:
                result = ExecCompareRightType<T, double, CmpFunc>(
                    left_raw_data, right_field_id, chunk_id, cmp_func);
                break;
            default:
                PanicInfo("unsupported left datatype of compare expr");
        }
        results.push_back(result);
    }
    auto final_result = AssembleChunk(results);
    AssertInfo(final_result.size() == row_count_,
               "[ExecExprVisitor]Size of results not equal row count");
    return final_result;
}

template <typename CmpFunc>
BitsetType
ExecExprVisitor::ExecCompareExprDispatcherForNonIndexedSegment(
    CompareExpr& expr, CmpFunc cmp_func) {
    switch (expr.left_data_type_) {
        case DataType::BOOL:
            return ExecCompareLeftType<bool, CmpFunc>(expr.left_field_id_,
                                                      expr.right_field_id_,
                                                      expr.right_data_type_,
                                                      cmp_func);
        case DataType::INT8:
            return ExecCompareLeftType<int8_t, CmpFunc>(expr.left_field_id_,
                                                        expr.right_field_id_,
                                                        expr.right_data_type_,
                                                        cmp_func);
        case DataType::INT16:
            return ExecCompareLeftType<int16_t, CmpFunc>(expr.left_field_id_,
                                                         expr.right_field_id_,
                                                         expr.right_data_type_,
                                                         cmp_func);
        case DataType::INT32:
            return ExecCompareLeftType<int32_t, CmpFunc>(expr.left_field_id_,
                                                         expr.right_field_id_,
                                                         expr.right_data_type_,
                                                         cmp_func);
        case DataType::INT64:
            return ExecCompareLeftType<int64_t, CmpFunc>(expr.left_field_id_,
                                                         expr.right_field_id_,
                                                         expr.right_data_type_,
                                                         cmp_func);
        case DataType::FLOAT:
            return ExecCompareLeftType<float, CmpFunc>(expr.left_field_id_,
                                                       expr.right_field_id_,
                                                       expr.right_data_type_,
                                                       cmp_func);
        case DataType::DOUBLE:
            return ExecCompareLeftType<double, CmpFunc>(expr.left_field_id_,
                                                        expr.right_field_id_,
                                                        expr.right_data_type_,
                                                        cmp_func);
        default:
            PanicInfo("unsupported right datatype of compare expr");
    }
}

1324 1325
template <typename Op>
auto
Y
yah01 已提交
1326 1327 1328 1329 1330 1331 1332 1333 1334 1335
ExecExprVisitor::ExecCompareExprDispatcher(CompareExpr& expr, Op op)
    -> BitsetType {
    using number = boost::variant<bool,
                                  int8_t,
                                  int16_t,
                                  int32_t,
                                  int64_t,
                                  float,
                                  double,
                                  std::string>;
1336 1337 1338 1339 1340
    auto is_string_expr = [&expr]() -> bool {
        return expr.left_data_type_ == DataType::VARCHAR ||
               expr.right_data_type_ == DataType::VARCHAR;
    };

1341 1342
    auto size_per_chunk = segment_.size_per_chunk();
    auto num_chunk = upper_div(row_count_, size_per_chunk);
1343
    std::deque<BitsetType> bitsets;
1344 1345 1346 1347

    // check for sealed segment, load either raw field data or index
    auto left_indexing_barrier = segment_.num_chunk_index(expr.left_field_id_);
    auto left_data_barrier = segment_.num_chunk_data(expr.left_field_id_);
1348 1349 1350
    AssertInfo(std::max(left_data_barrier, left_indexing_barrier) == num_chunk,
               "max(left_data_barrier, left_indexing_barrier) not equal to "
               "num_chunk");
1351

Y
yah01 已提交
1352 1353
    auto right_indexing_barrier =
        segment_.num_chunk_index(expr.right_field_id_);
1354
    auto right_data_barrier = segment_.num_chunk_data(expr.right_field_id_);
Y
yah01 已提交
1355 1356 1357 1358
    AssertInfo(
        std::max(right_data_barrier, right_indexing_barrier) == num_chunk,
        "max(right_data_barrier, right_indexing_barrier) not equal to "
        "num_chunk");
1359

1360 1361 1362 1363 1364 1365 1366 1367
    // For segment both fields has no index, can use SIMD to speed up.
    // Avoiding too much call stack that blocks SIMD.
    if (left_indexing_barrier == 0 && right_indexing_barrier == 0 &&
        !is_string_expr()) {
        return ExecCompareExprDispatcherForNonIndexedSegment<Op>(expr, op);
    }

    // TODO: refactoring the code that contains too much call stack.
1368
    for (int64_t chunk_id = 0; chunk_id < num_chunk; ++chunk_id) {
Y
yah01 已提交
1369 1370 1371 1372 1373 1374
        auto size = chunk_id == num_chunk - 1
                        ? row_count_ - chunk_id * size_per_chunk
                        : size_per_chunk;
        auto getChunkData =
            [&, chunk_id](DataType type, FieldId field_id, int64_t data_barrier)
            -> std::function<const number(int)> {
1375 1376
            switch (type) {
                case DataType::BOOL: {
1377
                    if (chunk_id < data_barrier) {
Y
yah01 已提交
1378 1379 1380 1381 1382 1383
                        auto chunk_data =
                            segment_.chunk_data<bool>(field_id, chunk_id)
                                .data();
                        return [chunk_data](int i) -> const number {
                            return chunk_data[i];
                        };
1384 1385
                    } else {
                        // for case, sealed segment has loaded index for scalar field instead of raw data
Y
yah01 已提交
1386 1387 1388 1389 1390
                        auto& indexing = segment_.chunk_scalar_index<bool>(
                            field_id, chunk_id);
                        return [&indexing](int i) -> const number {
                            return indexing.Reverse_Lookup(i);
                        };
1391
                    }
1392 1393
                }
                case DataType::INT8: {
1394
                    if (chunk_id < data_barrier) {
Y
yah01 已提交
1395 1396 1397 1398 1399 1400
                        auto chunk_data =
                            segment_.chunk_data<int8_t>(field_id, chunk_id)
                                .data();
                        return [chunk_data](int i) -> const number {
                            return chunk_data[i];
                        };
1401 1402
                    } else {
                        // for case, sealed segment has loaded index for scalar field instead of raw data
Y
yah01 已提交
1403 1404 1405 1406 1407
                        auto& indexing = segment_.chunk_scalar_index<int8_t>(
                            field_id, chunk_id);
                        return [&indexing](int i) -> const number {
                            return indexing.Reverse_Lookup(i);
                        };
1408
                    }
1409 1410
                }
                case DataType::INT16: {
1411
                    if (chunk_id < data_barrier) {
Y
yah01 已提交
1412 1413 1414 1415 1416 1417
                        auto chunk_data =
                            segment_.chunk_data<int16_t>(field_id, chunk_id)
                                .data();
                        return [chunk_data](int i) -> const number {
                            return chunk_data[i];
                        };
1418 1419
                    } else {
                        // for case, sealed segment has loaded index for scalar field instead of raw data
Y
yah01 已提交
1420 1421 1422 1423 1424
                        auto& indexing = segment_.chunk_scalar_index<int16_t>(
                            field_id, chunk_id);
                        return [&indexing](int i) -> const number {
                            return indexing.Reverse_Lookup(i);
                        };
1425
                    }
1426 1427
                }
                case DataType::INT32: {
1428
                    if (chunk_id < data_barrier) {
Y
yah01 已提交
1429 1430 1431 1432 1433 1434
                        auto chunk_data =
                            segment_.chunk_data<int32_t>(field_id, chunk_id)
                                .data();
                        return [chunk_data](int i) -> const number {
                            return chunk_data[i];
                        };
1435 1436
                    } else {
                        // for case, sealed segment has loaded index for scalar field instead of raw data
Y
yah01 已提交
1437 1438 1439 1440 1441
                        auto& indexing = segment_.chunk_scalar_index<int32_t>(
                            field_id, chunk_id);
                        return [&indexing](int i) -> const number {
                            return indexing.Reverse_Lookup(i);
                        };
1442
                    }
1443 1444
                }
                case DataType::INT64: {
1445
                    if (chunk_id < data_barrier) {
Y
yah01 已提交
1446 1447 1448 1449 1450 1451
                        auto chunk_data =
                            segment_.chunk_data<int64_t>(field_id, chunk_id)
                                .data();
                        return [chunk_data](int i) -> const number {
                            return chunk_data[i];
                        };
1452 1453
                    } else {
                        // for case, sealed segment has loaded index for scalar field instead of raw data
Y
yah01 已提交
1454 1455 1456 1457 1458
                        auto& indexing = segment_.chunk_scalar_index<int64_t>(
                            field_id, chunk_id);
                        return [&indexing](int i) -> const number {
                            return indexing.Reverse_Lookup(i);
                        };
1459
                    }
1460 1461
                }
                case DataType::FLOAT: {
1462
                    if (chunk_id < data_barrier) {
Y
yah01 已提交
1463 1464 1465 1466 1467 1468
                        auto chunk_data =
                            segment_.chunk_data<float>(field_id, chunk_id)
                                .data();
                        return [chunk_data](int i) -> const number {
                            return chunk_data[i];
                        };
1469 1470
                    } else {
                        // for case, sealed segment has loaded index for scalar field instead of raw data
Y
yah01 已提交
1471 1472 1473 1474 1475
                        auto& indexing = segment_.chunk_scalar_index<float>(
                            field_id, chunk_id);
                        return [&indexing](int i) -> const number {
                            return indexing.Reverse_Lookup(i);
                        };
1476
                    }
1477 1478
                }
                case DataType::DOUBLE: {
1479
                    if (chunk_id < data_barrier) {
Y
yah01 已提交
1480 1481 1482 1483 1484 1485
                        auto chunk_data =
                            segment_.chunk_data<double>(field_id, chunk_id)
                                .data();
                        return [chunk_data](int i) -> const number {
                            return chunk_data[i];
                        };
1486 1487
                    } else {
                        // for case, sealed segment has loaded index for scalar field instead of raw data
Y
yah01 已提交
1488 1489 1490 1491 1492
                        auto& indexing = segment_.chunk_scalar_index<double>(
                            field_id, chunk_id);
                        return [&indexing](int i) -> const number {
                            return indexing.Reverse_Lookup(i);
                        };
1493
                    }
1494 1495
                }
                case DataType::VARCHAR: {
1496
                    if (chunk_id < data_barrier) {
Y
yah01 已提交
1497
                        if (segment_.type() == SegmentType::Growing) {
Y
yah01 已提交
1498 1499 1500 1501 1502 1503 1504
                            auto chunk_data =
                                segment_
                                    .chunk_data<std::string>(field_id, chunk_id)
                                    .data();
                            return [chunk_data](int i) -> const number {
                                return chunk_data[i];
                            };
Y
yah01 已提交
1505
                        } else {
Y
yah01 已提交
1506 1507 1508 1509 1510 1511 1512
                            auto chunk_data = segment_
                                                  .chunk_data<std::string_view>(
                                                      field_id, chunk_id)
                                                  .data();
                            return [chunk_data](int i) -> const number {
                                return std::string(chunk_data[i]);
                            };
Y
yah01 已提交
1513
                        }
1514 1515
                    } else {
                        // for case, sealed segment has loaded index for scalar field instead of raw data
Y
yah01 已提交
1516 1517 1518 1519 1520 1521
                        auto& indexing =
                            segment_.chunk_scalar_index<std::string>(field_id,
                                                                     chunk_id);
                        return [&indexing](int i) -> const number {
                            return indexing.Reverse_Lookup(i);
                        };
1522
                    }
1523 1524
                }
                default:
1525
                    PanicInfo(fmt::format("unsupported data type: {}", type));
1526 1527
            }
        };
Y
yah01 已提交
1528 1529 1530 1531
        auto left = getChunkData(
            expr.left_data_type_, expr.left_field_id_, left_data_barrier);
        auto right = getChunkData(
            expr.right_data_type_, expr.right_field_id_, right_data_barrier);
1532

1533
        BitsetType bitset(size);
1534
        for (int i = 0; i < size; ++i) {
Y
yah01 已提交
1535 1536
            bool is_in = boost::apply_visitor(
                Relational<decltype(op)>{}, left(i), right(i));
1537 1538 1539 1540
            bitset[i] = is_in;
        }
        bitsets.emplace_back(std::move(bitset));
    }
1541
    auto final_result = Assemble(bitsets);
Y
yah01 已提交
1542 1543
    AssertInfo(final_result.size() == row_count_,
               "[ExecExprVisitor]Size of results not equal row count");
1544
    return final_result;
1545 1546 1547 1548 1549
}

void
ExecExprVisitor::visit(CompareExpr& expr) {
    auto& schema = segment_.get_schema();
1550 1551
    auto& left_field_meta = schema[expr.left_field_id_];
    auto& right_field_meta = schema[expr.right_field_id_];
1552
    AssertInfo(expr.left_data_type_ == left_field_meta.get_data_type(),
1553 1554
               "[ExecExprVisitor]Left data type not equal to left field "
               "meta type");
1555 1556 1557
    AssertInfo(expr.right_data_type_ == right_field_meta.get_data_type(),
               "[ExecExprVisitor]right data type not equal to right field "
               "meta type");
1558

1559
    BitsetType res;
1560
    switch (expr.op_type_) {
1561
        case OpType::Equal: {
1562
            res = ExecCompareExprDispatcher(expr, std::equal_to<>{});
1563 1564 1565
            break;
        }
        case OpType::NotEqual: {
1566
            res = ExecCompareExprDispatcher(expr, std::not_equal_to<>{});
1567 1568 1569
            break;
        }
        case OpType::GreaterEqual: {
1570
            res = ExecCompareExprDispatcher(expr, std::greater_equal<>{});
1571 1572 1573
            break;
        }
        case OpType::GreaterThan: {
1574
            res = ExecCompareExprDispatcher(expr, std::greater<>{});
1575 1576 1577
            break;
        }
        case OpType::LessEqual: {
1578
            res = ExecCompareExprDispatcher(expr, std::less_equal<>{});
1579 1580 1581
            break;
        }
        case OpType::LessThan: {
1582
            res = ExecCompareExprDispatcher(expr, std::less<>{});
1583 1584
            break;
        }
1585
        case OpType::PrefixMatch: {
Y
yah01 已提交
1586 1587
            res =
                ExecCompareExprDispatcher(expr, MatchOp<OpType::PrefixMatch>{});
1588 1589 1590 1591
            break;
        }
            // case OpType::PostfixMatch: {
            // }
1592 1593 1594 1595
        default: {
            PanicInfo("unsupported optype");
        }
    }
Y
yah01 已提交
1596 1597
    AssertInfo(res.size() == row_count_,
               "[ExecExprVisitor]Size of results not equal row count");
1598
    bitset_opt_ = std::move(res);
1599 1600
}

S
sunby 已提交
1601 1602
template <typename T>
auto
1603
ExecExprVisitor::ExecTermVisitorImpl(TermExpr& expr_raw) -> BitsetType {
S
sunby 已提交
1604 1605
    auto& expr = static_cast<TermExprImpl<T>&>(expr_raw);
    auto& schema = segment_.get_schema();
1606
    auto primary_filed_id = schema.get_primary_field_id();
1607
    auto field_id = expr_raw.column_.field_id;
1608
    auto& field_meta = schema[field_id];
1609 1610

    bool use_pk_index = false;
1611
    if (primary_filed_id.has_value()) {
Y
yah01 已提交
1612 1613
        use_pk_index = primary_filed_id.value() == field_id &&
                       IsPrimaryKeyDataType(field_meta.get_data_type());
1614 1615 1616 1617
    }

    if (use_pk_index) {
        auto id_array = std::make_unique<IdArray>();
1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635
        switch (field_meta.get_data_type()) {
            case DataType::INT64: {
                auto dst_ids = id_array->mutable_int_id();
                for (const auto& id : expr.terms_) {
                    dst_ids->add_data((int64_t&)id);
                }
                break;
            }
            case DataType::VARCHAR: {
                auto dst_ids = id_array->mutable_str_id();
                for (const auto& id : expr.terms_) {
                    dst_ids->add_data((std::string&)id);
                }
                break;
            }
            default: {
                PanicInfo("unsupported type");
            }
1636
        }
1637

1638 1639 1640 1641 1642 1643
        auto [uids, seg_offsets] = segment_.search_ids(*id_array, timestamp_);
        BitsetType bitset(row_count_);
        for (const auto& offset : seg_offsets) {
            auto _offset = (int64_t)offset.get();
            bitset[_offset] = true;
        }
Y
yah01 已提交
1644 1645
        AssertInfo(bitset.size() == row_count_,
                   "[ExecExprVisitor]Size of results not equal row count");
1646 1647 1648
        return bitset;
    }

1649
    return ExecTermVisitorImplTemplate<T>(expr_raw);
S
sunby 已提交
1650 1651
}

1652 1653
template <>
auto
Y
yah01 已提交
1654 1655
ExecExprVisitor::ExecTermVisitorImpl<std::string>(TermExpr& expr_raw)
    -> BitsetType {
1656 1657 1658
    return ExecTermVisitorImplTemplate<std::string>(expr_raw);
}

Y
yah01 已提交
1659 1660
template <>
auto
Y
yah01 已提交
1661 1662
ExecExprVisitor::ExecTermVisitorImpl<std::string_view>(TermExpr& expr_raw)
    -> BitsetType {
Y
yah01 已提交
1663 1664 1665
    return ExecTermVisitorImplTemplate<std::string_view>(expr_raw);
}

1666 1667 1668
template <typename T>
auto
ExecExprVisitor::ExecTermVisitorImplTemplate(TermExpr& expr_raw) -> BitsetType {
Y
yah01 已提交
1669 1670 1671
    typedef std::
        conditional_t<std::is_same_v<T, std::string_view>, std::string, T>
            IndexInnerType;
Y
yah01 已提交
1672 1673
    using Index = index::ScalarIndex<IndexInnerType>;
    auto& expr = static_cast<TermExprImpl<IndexInnerType>&>(expr_raw);
Y
yah01 已提交
1674 1675
    const std::vector<IndexInnerType> terms(expr.terms_.begin(),
                                            expr.terms_.end());
1676 1677 1678
    auto n = terms.size();
    std::unordered_set<T> term_set(expr.terms_.begin(), expr.terms_.end());

Y
yah01 已提交
1679 1680 1681
    auto index_func = [&terms, n](Index* index) {
        return index->In(n, terms.data());
    };
1682 1683 1684 1685 1686 1687
    auto elem_func = [&terms, &term_set](T x) {
        //// terms has already been sorted.
        // return std::binary_search(terms.begin(), terms.end(), x);
        return term_set.find(x) != term_set.end();
    };

1688 1689
    return ExecRangeVisitorImpl<T>(
        expr.column_.field_id, index_func, elem_func);
1690 1691
}

1692 1693 1694
// TODO: bool is so ugly here.
template <>
auto
Y
yah01 已提交
1695 1696
ExecExprVisitor::ExecTermVisitorImplTemplate<bool>(TermExpr& expr_raw)
    -> BitsetType {
1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720
    using T = bool;
    auto& expr = static_cast<TermExprImpl<T>&>(expr_raw);
    using Index = index::ScalarIndex<T>;
    const auto& terms = expr.terms_;
    auto n = terms.size();
    std::unordered_set<T> term_set(expr.terms_.begin(), expr.terms_.end());

    auto index_func = [&terms, n](Index* index) {
        auto bool_arr_copy = new bool[terms.size()];
        int it = 0;
        for (auto elem : terms) {
            bool_arr_copy[it++] = elem;
        }
        auto bitset = index->In(n, bool_arr_copy);
        delete[] bool_arr_copy;
        return bitset;
    };

    auto elem_func = [&terms, &term_set](T x) {
        //// terms has already been sorted.
        // return std::binary_search(terms.begin(), terms.end(), x);
        return term_set.find(x) != term_set.end();
    };

1721 1722 1723 1724 1725 1726 1727 1728 1729 1730
    return ExecRangeVisitorImpl<T>(
        expr.column_.field_id, index_func, elem_func);
}

template <typename ExprValueType>
auto
ExecExprVisitor::ExecTermVisitorImplTemplateJson(TermExpr& expr_raw)
    -> BitsetType {
    using Index = index::ScalarIndex<milvus::Json>;
    auto& expr = static_cast<TermExprImpl<ExprValueType>&>(expr_raw);
1731
    auto pointer = milvus::Json::pointer(std::move(expr.column_.nested_path));
1732
    auto index_func = [=](Index* index) { return TargetBitmap{}; };
1733 1734 1735 1736 1737 1738 1739 1740 1741 1742

    std::unordered_set<ExprValueType> term_set(expr.terms_.begin(),
                                               expr.terms_.end());

    if (term_set.empty()) {
        auto elem_func = [=](const milvus::Json& json) { return false; };
        return ExecRangeVisitorImpl<milvus::Json>(
            expr.column_.field_id, index_func, elem_func);
    }

1743
    auto elem_func = [&term_set, &pointer](const milvus::Json& json) {
1744 1745 1746 1747
        using GetType =
            std::conditional_t<std::is_same_v<ExprValueType, std::string>,
                               std::string_view,
                               ExprValueType>;
1748
        auto x = json.template at<GetType>(pointer);
1749 1750 1751 1752 1753 1754 1755 1756
        if (x.error()) {
            return false;
        }
        return term_set.find(ExprValueType(x.value())) != term_set.end();
    };

    return ExecRangeVisitorImpl<milvus::Json>(
        expr.column_.field_id, index_func, elem_func);
1757 1758
}

S
sunby 已提交
1759 1760
void
ExecExprVisitor::visit(TermExpr& expr) {
1761 1762
    auto& field_meta = segment_.get_schema()[expr.column_.field_id];
    AssertInfo(expr.column_.data_type == field_meta.get_data_type(),
1763 1764
               "[ExecExprVisitor]DataType of expr isn't field_meta "
               "data type ");
1765
    BitsetType res;
1766
    switch (expr.column_.data_type) {
S
sunby 已提交
1767
        case DataType::BOOL: {
1768
            res = ExecTermVisitorImpl<bool>(expr);
S
sunby 已提交
1769 1770 1771
            break;
        }
        case DataType::INT8: {
1772
            res = ExecTermVisitorImpl<int8_t>(expr);
S
sunby 已提交
1773 1774 1775
            break;
        }
        case DataType::INT16: {
1776
            res = ExecTermVisitorImpl<int16_t>(expr);
S
sunby 已提交
1777 1778 1779
            break;
        }
        case DataType::INT32: {
1780
            res = ExecTermVisitorImpl<int32_t>(expr);
S
sunby 已提交
1781 1782 1783
            break;
        }
        case DataType::INT64: {
1784
            res = ExecTermVisitorImpl<int64_t>(expr);
S
sunby 已提交
1785 1786 1787
            break;
        }
        case DataType::FLOAT: {
1788
            res = ExecTermVisitorImpl<float>(expr);
S
sunby 已提交
1789 1790 1791
            break;
        }
        case DataType::DOUBLE: {
1792
            res = ExecTermVisitorImpl<double>(expr);
S
sunby 已提交
1793 1794
            break;
        }
1795
        case DataType::VARCHAR: {
Y
yah01 已提交
1796 1797 1798 1799 1800
            if (segment_.type() == SegmentType::Growing) {
                res = ExecTermVisitorImpl<std::string>(expr);
            } else {
                res = ExecTermVisitorImpl<std::string_view>(expr);
            }
1801 1802
            break;
        }
1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825
        case DataType::JSON: {
            switch (expr.val_case_) {
                case proto::plan::GenericValue::ValCase::kBoolVal:
                    res = ExecTermVisitorImplTemplateJson<bool>(expr);
                    break;
                case proto::plan::GenericValue::ValCase::kInt64Val:
                    res = ExecTermVisitorImplTemplateJson<int64_t>(expr);
                    break;
                case proto::plan::GenericValue::ValCase::kFloatVal:
                    res = ExecTermVisitorImplTemplateJson<double>(expr);
                    break;
                case proto::plan::GenericValue::ValCase::kStringVal:
                    res = ExecTermVisitorImplTemplateJson<std::string>(expr);
                    break;
                case proto::plan::GenericValue::ValCase::VAL_NOT_SET:
                    res = ExecTermVisitorImplTemplateJson<bool>(expr);
                    break;
                default:
                    PanicInfo(
                        fmt::format("unknown data type: {}", expr.val_case_));
            }
            break;
        }
S
sunby 已提交
1826
        default:
1827 1828
            PanicInfo(fmt::format("unsupported data type: {}",
                                  expr.column_.data_type));
S
sunby 已提交
1829
    }
Y
yah01 已提交
1830 1831
    AssertInfo(res.size() == row_count_,
               "[ExecExprVisitor]Size of results not equal row count");
1832
    bitset_opt_ = std::move(res);
S
sunby 已提交
1833
}
1834 1835 1836 1837 1838 1839 1840

void
ExecExprVisitor::visit(ExistsExpr& expr) {
    auto& field_meta = segment_.get_schema()[expr.column_.field_id];
    AssertInfo(expr.column_.data_type == field_meta.get_data_type(),
               "[ExecExprVisitor]DataType of expr isn't field_meta data type");
    BitsetType res;
1841
    auto pointer = milvus::Json::pointer(std::move(expr.column_.nested_path));
1842 1843 1844
    switch (expr.column_.data_type) {
        case DataType::JSON: {
            using Index = index::ScalarIndex<milvus::Json>;
1845 1846 1847
            auto index_func = [&](Index* index) { return TargetBitmap{}; };
            auto elem_func = [&](const milvus::Json& json) {
                auto x = json.exist(pointer);
1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862
                return x;
            };
            res = ExecRangeVisitorImpl<milvus::Json>(
                expr.column_.field_id, index_func, elem_func);
            break;
        }
        default:
            PanicInfo(fmt::format("unsupported data type {}",
                                  expr.column_.data_type));
    }
    AssertInfo(res.size() == row_count_,
               "[ExecExprVisitor]Size of results not equal row count");
    bitset_opt_ = std::move(res);
}

N
neza2017 已提交
1863
}  // namespace milvus::query