ExecExprVisitor.cpp 99.8 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 17
#include <cmath>
#include <cstdint>
18
#include <ctime>
19
#include <deque>
N
neza2017 已提交
20
#include <optional>
21 22 23
#include <string>
#include <string_view>
#include <type_traits>
24
#include <unordered_set>
25 26
#include <utility>

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

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

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

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

71 72 73 74
    template <typename T>
    auto
    ExecUnaryRangeVisitorDispatcherImpl(UnaryRangeExpr& expr_raw) -> BitsetType;

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

79 80
    template <typename T>
    auto
Y
yah01 已提交
81 82
    ExecBinaryArithOpEvalRangeVisitorDispatcher(
        BinaryArithOpEvalRangeExpr& expr_raw) -> BitsetType;
83

84 85
    template <typename T>
    auto
86
    ExecBinaryRangeVisitorDispatcher(BinaryRangeExpr& expr_raw) -> BitsetType;
G
GuoRentong 已提交
87

S
sunby 已提交
88 89
    template <typename T>
    auto
90
    ExecTermVisitorImpl(TermExpr& expr_raw) -> BitsetType;
S
sunby 已提交
91

92 93 94 95
    template <typename T>
    auto
    ExecTermVisitorImplTemplate(TermExpr& expr_raw) -> BitsetType;

96 97
    template <typename CmpFunc>
    auto
Y
yah01 已提交
98 99
    ExecCompareExprDispatcher(CompareExpr& expr, CmpFunc cmp_func)
        -> BitsetType;
100

N
neza2017 已提交
101
 private:
102 103
    const segcore::SegmentInternalInterface& segment_;
    int64_t row_count_;
104
    Timestamp timestamp_;
105
    BitsetTypeOpt bitset_opt_;
N
neza2017 已提交
106 107 108 109
};
}  // namespace impl

void
F
FluorineDog 已提交
110 111
ExecExprVisitor::visit(LogicalUnaryExpr& expr) {
    using OpType = LogicalUnaryExpr::OpType;
112
    auto child_res = call_child(*expr.child_);
113
    BitsetType res = std::move(child_res);
114 115 116 117 118 119 120
    switch (expr.op_type_) {
        case OpType::LogicalNot: {
            res.flip();
            break;
        }
        default: {
            PanicInfo("Invalid Unary Op");
F
FluorineDog 已提交
121 122
        }
    }
Y
yah01 已提交
123 124
    AssertInfo(res.size() == row_count_,
               "[ExecExprVisitor]Size of results not equal row count");
125
    bitset_opt_ = std::move(res);
N
neza2017 已提交
126 127 128
}

void
F
FluorineDog 已提交
129 130
ExecExprVisitor::visit(LogicalBinaryExpr& expr) {
    using OpType = LogicalBinaryExpr::OpType;
131 132 133 134 135 136
    auto skip_right_expr = [](const BitsetType& left_res,
                              const OpType& op_type) -> bool {
        return (op_type == OpType::LogicalAnd && left_res.none()) ||
               (op_type == OpType::LogicalOr && left_res.all());
    };

F
FluorineDog 已提交
137
    auto left = call_child(*expr.left_);
138 139 140 141 142 143 144
    // skip execute right node for some situations
    if (skip_right_expr(left, expr.op_type_)) {
        AssertInfo(left.size() == row_count_,
                   "[ExecExprVisitor]Size of results not equal row count");
        bitset_opt_ = std::move(left);
        return;
    }
F
FluorineDog 已提交
145
    auto right = call_child(*expr.right_);
Y
yah01 已提交
146 147
    AssertInfo(left.size() == right.size(),
               "[ExecExprVisitor]Left size not equal to right size");
148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
    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 已提交
170 171
    AssertInfo(res.size() == row_count_,
               "[ExecExprVisitor]Size of results not equal row count");
172
    bitset_opt_ = std::move(res);
173
}
F
FluorineDog 已提交
174

175
static auto
176 177
Assemble(const std::deque<BitsetType>& srcs) -> BitsetType {
    BitsetType res;
178

179 180 181 182
    if (srcs.size() == 1) {
        return srcs[0];
    }

183 184 185 186 187 188 189 190 191 192
    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 已提交
193
        }
194
        counter += chunk.size();
F
FluorineDog 已提交
195
    }
196
    return res;
N
neza2017 已提交
197 198
}

199 200 201 202 203
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) {
204 205 206 207
#if defined(USE_DYNAMIC_SIMD)
            auto val = milvus::simd::get_bitset_block(ptr);
#else
            BitsetBlockType val = 0;
208 209 210 211 212 213 214 215
            // 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) {
216
                val |= BitsetBlockType(vals[j]) << (8 * j);
217
            }
218
#endif
219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265
            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 已提交
266
template <typename T, typename IndexFunc, typename ElementFunc>
G
GuoRentong 已提交
267
auto
Y
yah01 已提交
268 269 270
ExecExprVisitor::ExecRangeVisitorImpl(FieldId field_id,
                                      IndexFunc index_func,
                                      ElementFunc element_func) -> BitsetType {
G
GuoRentong 已提交
271
    auto& schema = segment_.get_schema();
272 273
    auto& field_meta = schema[field_id];
    auto indexing_barrier = segment_.num_chunk_index(field_id);
B
BossZou 已提交
274 275
    auto size_per_chunk = segment_.size_per_chunk();
    auto num_chunk = upper_div(row_count_, size_per_chunk);
276
    std::vector<FixedVector<bool>> results;
277 278
    results.reserve(num_chunk);

Y
yah01 已提交
279 280 281
    typedef std::
        conditional_t<std::is_same_v<T, std::string_view>, std::string, T>
            IndexInnerType;
Y
yah01 已提交
282
    using Index = index::ScalarIndex<IndexInnerType>;
F
FluorineDog 已提交
283
    for (auto chunk_id = 0; chunk_id < indexing_barrier; ++chunk_id) {
Y
yah01 已提交
284 285
        const Index& indexing =
            segment_.chunk_scalar_index<IndexInnerType>(field_id, chunk_id);
286 287 288
        // NOTE: knowhere is not const-ready
        // This is a dirty workaround
        auto data = index_func(const_cast<Index*>(&indexing));
289
        AssertInfo(data.size() == size_per_chunk,
Y
yah01 已提交
290
                   "[ExecExprVisitor]Data size not equal to size_per_chunk");
291
        results.emplace_back(std::move(data));
F
FluorineDog 已提交
292
    }
293
    for (auto chunk_id = indexing_barrier; chunk_id < num_chunk; ++chunk_id) {
Y
yah01 已提交
294 295 296
        auto this_size = chunk_id == num_chunk - 1
                             ? row_count_ - chunk_id * size_per_chunk
                             : size_per_chunk;
297
        FixedVector<bool> chunk_res(this_size);
298
        auto chunk = segment_.chunk_data<T>(field_id, chunk_id);
G
GuoRentong 已提交
299
        const T* data = chunk.data();
300
        // Can use CPU SIMD optimazation to speed up
301
        for (int index = 0; index < this_size; ++index) {
302
            chunk_res[index] = element_func(data[index]);
G
GuoRentong 已提交
303
        }
304
        results.emplace_back(std::move(chunk_res));
G
GuoRentong 已提交
305
    }
306
    auto final_result = AssembleChunk(results);
Y
yah01 已提交
307 308
    AssertInfo(final_result.size() == row_count_,
               "[ExecExprVisitor]Final result size not equal to row count");
309
    return final_result;
G
GuoRentong 已提交
310
}
311

312
template <typename T, typename IndexFunc, typename ElementFunc>
313
auto
Y
yah01 已提交
314 315 316
ExecExprVisitor::ExecDataRangeVisitorImpl(FieldId field_id,
                                          IndexFunc index_func,
                                          ElementFunc element_func)
317
    -> BitsetType {
318
    auto& schema = segment_.get_schema();
319
    auto& field_meta = schema[field_id];
320 321
    auto size_per_chunk = segment_.size_per_chunk();
    auto num_chunk = upper_div(row_count_, size_per_chunk);
322 323 324 325
    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");
326
    std::vector<FixedVector<bool>> results;
327
    results.reserve(num_chunk);
328

329 330 331 332 333
    // 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 已提交
334 335 336
        auto this_size = chunk_id == num_chunk - 1
                             ? row_count_ - chunk_id * size_per_chunk
                             : size_per_chunk;
337
        FixedVector<bool> result(this_size);
338
        auto chunk = segment_.chunk_data<T>(field_id, chunk_id);
339 340 341 342
        const T* data = chunk.data();
        for (int index = 0; index < this_size; ++index) {
            result[index] = element_func(data[index]);
        }
343 344 345
        AssertInfo(result.size() == this_size,
                   "[ExecExprVisitor]Chunk result size not equal to "
                   "expected size");
346 347
        results.emplace_back(std::move(result));
    }
348 349 350

    // 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 已提交
351 352 353
    typedef std::
        conditional_t<std::is_same_v<T, std::string_view>, std::string, T>
            IndexInnerType;
Y
yah01 已提交
354
    using Index = index::ScalarIndex<IndexInnerType>;
Y
yah01 已提交
355 356 357 358
    for (auto chunk_id = data_barrier; chunk_id < indexing_barrier;
         ++chunk_id) {
        auto& indexing =
            segment_.chunk_scalar_index<IndexInnerType>(field_id, chunk_id);
359
        auto this_size = const_cast<Index*>(&indexing)->Count();
360
        FixedVector<bool> result(this_size);
361 362 363 364 365 366
        for (int offset = 0; offset < this_size; ++offset) {
            result[offset] = index_func(const_cast<Index*>(&indexing), offset);
        }
        results.emplace_back(std::move(result));
    }

367
    auto final_result = AssembleChunk(results);
Y
yah01 已提交
368 369
    AssertInfo(final_result.size() == row_count_,
               "[ExecExprVisitor]Final result size not equal to row count");
370 371 372
    return final_result;
}

G
GuoRentong 已提交
373 374 375 376
#pragma clang diagnostic push
#pragma ide diagnostic ignored "Simplify"
template <typename T>
auto
377
ExecExprVisitor::ExecUnaryRangeVisitorDispatcherImpl(UnaryRangeExpr& expr_raw)
Y
yah01 已提交
378 379 380 381
    -> BitsetType {
    typedef std::
        conditional_t<std::is_same_v<T, std::string_view>, std::string, T>
            IndexInnerType;
Y
yah01 已提交
382 383 384
    using Index = index::ScalarIndex<IndexInnerType>;
    auto& expr = static_cast<UnaryRangeExprImpl<IndexInnerType>&>(expr_raw);

385
    auto op = expr.op_type_;
Y
yah01 已提交
386
    auto val = IndexInnerType(expr.value_);
387
    auto field_id = expr.column_.field_id;
388 389
    switch (op) {
        case OpType::Equal: {
390
            auto index_func = [&](Index* index) { return index->In(1, &val); };
391
            auto elem_func = [&](MayConstRef<T> x) { return (x == val); };
392
            return ExecRangeVisitorImpl<T>(field_id, index_func, elem_func);
393 394
        }
        case OpType::NotEqual: {
395
            auto index_func = [&](Index* index) {
Y
yah01 已提交
396 397
                return index->NotIn(1, &val);
            };
398
            auto elem_func = [&](MayConstRef<T> x) { return (x != val); };
399
            return ExecRangeVisitorImpl<T>(field_id, index_func, elem_func);
400 401
        }
        case OpType::GreaterEqual: {
402
            auto index_func = [&](Index* index) {
Y
yah01 已提交
403 404
                return index->Range(val, OpType::GreaterEqual);
            };
405
            auto elem_func = [&](MayConstRef<T> x) { return (x >= val); };
406
            return ExecRangeVisitorImpl<T>(field_id, index_func, elem_func);
G
GuoRentong 已提交
407
        }
408
        case OpType::GreaterThan: {
409
            auto index_func = [&](Index* index) {
Y
yah01 已提交
410 411
                return index->Range(val, OpType::GreaterThan);
            };
412
            auto elem_func = [&](MayConstRef<T> x) { return (x > val); };
413
            return ExecRangeVisitorImpl<T>(field_id, index_func, elem_func);
414 415
        }
        case OpType::LessEqual: {
416
            auto index_func = [&](Index* index) {
Y
yah01 已提交
417 418
                return index->Range(val, OpType::LessEqual);
            };
419
            auto elem_func = [&](MayConstRef<T> x) { return (x <= val); };
420
            return ExecRangeVisitorImpl<T>(field_id, index_func, elem_func);
421 422
        }
        case OpType::LessThan: {
423
            auto index_func = [&](Index* index) {
Y
yah01 已提交
424 425
                return index->Range(val, OpType::LessThan);
            };
426
            auto elem_func = [&](MayConstRef<T> x) { return (x < val); };
427
            return ExecRangeVisitorImpl<T>(field_id, index_func, elem_func);
428 429
        }
        case OpType::PrefixMatch: {
430
            auto index_func = [&](Index* index) {
P
presburger 已提交
431
                auto dataset = std::make_unique<Dataset>();
432 433
                dataset->Set(milvus::index::OPERATOR_TYPE, OpType::PrefixMatch);
                dataset->Set(milvus::index::PREFIX_VALUE, val);
434 435
                return index->Query(std::move(dataset));
            };
436 437 438
            auto elem_func = [&](MayConstRef<T> x) {
                return Match(x, val, op);
            };
439
            return ExecRangeVisitorImpl<T>(field_id, index_func, elem_func);
440 441
        }
        // TODO: PostfixMatch
442
        default: {
G
GuoRentong 已提交
443 444
            PanicInfo("unsupported range node");
        }
445 446 447 448
    }
}
#pragma clang diagnostic pop

449 450 451 452
template <typename T>
auto
ExecExprVisitor::ExecUnaryRangeVisitorDispatcher(UnaryRangeExpr& expr_raw)
    -> BitsetType {
453 454 455 456
    // bool type is integral but will never be overflowed,
    // the check method may evaluate it out of range with bool type,
    // exclude bool type here
    if constexpr (std::is_integral_v<T> && !std::is_same_v<T, bool>) {
457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503
        auto& expr = static_cast<UnaryRangeExprImpl<int64_t>&>(expr_raw);
        auto val = expr.value_;

        if (!out_of_range<T>(val)) {
            return ExecUnaryRangeVisitorDispatcherImpl<T>(expr_raw);
        }

        // see also: https://github.com/milvus-io/milvus/issues/23646.
        switch (expr.op_type_) {
            case proto::plan::GreaterThan:
            case proto::plan::GreaterEqual: {
                BitsetType r(row_count_);
                if (lt_lb<T>(val)) {
                    r.set();
                }
                return r;
            }

            case proto::plan::LessThan:
            case proto::plan::LessEqual: {
                BitsetType r(row_count_);
                if (gt_ub<T>(val)) {
                    r.set();
                }
                return r;
            }

            case proto::plan::Equal: {
                BitsetType r(row_count_);
                r.reset();
                return r;
            }

            case proto::plan::NotEqual: {
                BitsetType r(row_count_);
                r.set();
                return r;
            }

            default: {
                PanicInfo("unsupported range node");
            }
        }
    }
    return ExecUnaryRangeVisitorDispatcherImpl<T>(expr_raw);
}

504 505 506 507 508 509 510 511 512
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_;
513
    auto pointer = milvus::Json::pointer(expr.column_.nested_path);
514
    auto field_id = expr.column_.field_id;
515
    auto index_func = [=](Index* index) { return TargetBitmap{}; };
516 517 518 519 520
    using GetType =
        std::conditional_t<std::is_same_v<ExprValueType, std::string>,
                           std::string_view,
                           ExprValueType>;

521 522 523 524 525 526 527 528 529 530 531
#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);                                         \
532 533
    } while (false)

534 535 536 537 538 539 540 541 542 543 544
#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);                                         \
545 546
    } while (false)

547 548
    switch (op) {
        case OpType::Equal: {
549
            auto elem_func = [&](const milvus::Json& json) {
550
                UnaryRangeJSONCompare(x.value() == val);
551 552 553 554 555
            };
            return ExecRangeVisitorImpl<milvus::Json>(
                field_id, index_func, elem_func);
        }
        case OpType::NotEqual: {
556
            auto elem_func = [&](const milvus::Json& json) {
557
                UnaryRangeJSONCompareNotEqual(x.value() != val);
558 559 560 561 562
            };
            return ExecRangeVisitorImpl<milvus::Json>(
                field_id, index_func, elem_func);
        }
        case OpType::GreaterEqual: {
563
            auto elem_func = [&](const milvus::Json& json) {
564
                UnaryRangeJSONCompare(x.value() >= val);
565 566 567 568 569
            };
            return ExecRangeVisitorImpl<milvus::Json>(
                field_id, index_func, elem_func);
        }
        case OpType::GreaterThan: {
570
            auto elem_func = [&](const milvus::Json& json) {
571
                UnaryRangeJSONCompare(x.value() > val);
572 573 574 575 576
            };
            return ExecRangeVisitorImpl<milvus::Json>(
                field_id, index_func, elem_func);
        }
        case OpType::LessEqual: {
577
            auto elem_func = [&](const milvus::Json& json) {
578
                UnaryRangeJSONCompare(x.value() <= val);
579 580 581 582 583
            };
            return ExecRangeVisitorImpl<milvus::Json>(
                field_id, index_func, elem_func);
        }
        case OpType::LessThan: {
584
            auto elem_func = [&](const milvus::Json& json) {
585
                UnaryRangeJSONCompare(x.value() < val);
586 587 588 589 590
            };
            return ExecRangeVisitorImpl<milvus::Json>(
                field_id, index_func, elem_func);
        }
        case OpType::PrefixMatch: {
591
            auto elem_func = [&](const milvus::Json& json) {
592
                UnaryRangeJSONCompare(Match(ExprValueType(x.value()), val, op));
593 594 595 596 597 598 599 600 601 602 603
            };
            return ExecRangeVisitorImpl<milvus::Json>(
                field_id, index_func, elem_func);
        }
        // TODO: PostfixMatch
        default: {
            PanicInfo("unsupported range node");
        }
    }
}

604 605 606 607
#pragma clang diagnostic push
#pragma ide diagnostic ignored "Simplify"
template <typename T>
auto
Y
yah01 已提交
608 609
ExecExprVisitor::ExecBinaryArithOpEvalRangeVisitorDispatcher(
    BinaryArithOpEvalRangeExpr& expr_raw) -> BitsetType {
610
    // see also: https://github.com/milvus-io/milvus/issues/23646.
611 612 613 614
    typedef std::conditional_t<std::is_integral_v<T> &&
                                   !std::is_same_v<bool, T>,
                               int64_t,
                               T>
615 616 617 618 619
        HighPrecisionType;

    auto& expr =
        static_cast<BinaryArithOpEvalRangeExprImpl<HighPrecisionType>&>(
            expr_raw);
620
    using Index = index::ScalarIndex<T>;
621 622 623 624 625 626 627 628 629
    auto arith_op = expr.arith_op_;
    auto right_operand = expr.right_operand_;
    auto op = expr.op_type_;
    auto val = expr.value_;

    switch (op) {
        case OpType::Equal: {
            switch (arith_op) {
                case ArithOpType::Add: {
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;
                    };
635 636 637
                    auto elem_func = [val, right_operand](MayConstRef<T> x) {
                        return ((x + right_operand) == val);
                    };
Y
yah01 已提交
638
                    return ExecDataRangeVisitorImpl<T>(
639
                        expr.column_.field_id, index_func, elem_func);
640 641
                }
                case ArithOpType::Sub: {
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;
                    };
647
                    auto elem_func = [val, right_operand](MayConstRef<T> x) {
Y
yah01 已提交
648 649 650
                        return ((x - right_operand) == val);
                    };
                    return ExecDataRangeVisitorImpl<T>(
651
                        expr.column_.field_id, index_func, elem_func);
652 653
                }
                case ArithOpType::Mul: {
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 (x * right_operand) == val;
                    };
659
                    auto elem_func = [val, right_operand](MayConstRef<T> x) {
Y
yah01 已提交
660 661 662
                        return ((x * right_operand) == val);
                    };
                    return ExecDataRangeVisitorImpl<T>(
663
                        expr.column_.field_id, index_func, elem_func);
664 665
                }
                case ArithOpType::Div: {
Y
yah01 已提交
666 667
                    auto index_func = [val, right_operand](Index* index,
                                                           size_t offset) {
668 669 670
                        auto x = index->Reverse_Lookup(offset);
                        return (x / right_operand) == val;
                    };
671
                    auto elem_func = [val, right_operand](MayConstRef<T> x) {
Y
yah01 已提交
672 673 674
                        return ((x / right_operand) == val);
                    };
                    return ExecDataRangeVisitorImpl<T>(
675
                        expr.column_.field_id, index_func, elem_func);
676 677
                }
                case ArithOpType::Mod: {
Y
yah01 已提交
678 679
                    auto index_func = [val, right_operand](Index* index,
                                                           size_t offset) {
680 681 682
                        auto x = index->Reverse_Lookup(offset);
                        return static_cast<T>(fmod(x, right_operand)) == val;
                    };
683
                    auto elem_func = [val, right_operand](MayConstRef<T> x) {
684 685
                        return (static_cast<T>(fmod(x, right_operand)) == val);
                    };
Y
yah01 已提交
686
                    return ExecDataRangeVisitorImpl<T>(
687
                        expr.column_.field_id, index_func, elem_func);
688 689 690 691 692 693 694 695 696
                }
                default: {
                    PanicInfo("unsupported arithmetic operation");
                }
            }
        }
        case OpType::NotEqual: {
            switch (arith_op) {
                case ArithOpType::Add: {
Y
yah01 已提交
697 698
                    auto index_func = [val, right_operand](Index* index,
                                                           size_t offset) {
699 700 701
                        auto x = index->Reverse_Lookup(offset);
                        return (x + right_operand) != val;
                    };
702
                    auto elem_func = [val, right_operand](MayConstRef<T> x) {
Y
yah01 已提交
703 704 705
                        return ((x + right_operand) != val);
                    };
                    return ExecDataRangeVisitorImpl<T>(
706
                        expr.column_.field_id, index_func, elem_func);
707 708
                }
                case ArithOpType::Sub: {
Y
yah01 已提交
709 710
                    auto index_func = [val, right_operand](Index* index,
                                                           size_t offset) {
711 712 713
                        auto x = index->Reverse_Lookup(offset);
                        return (x - right_operand) != val;
                    };
714
                    auto elem_func = [val, right_operand](MayConstRef<T> x) {
Y
yah01 已提交
715 716 717
                        return ((x - right_operand) != val);
                    };
                    return ExecDataRangeVisitorImpl<T>(
718
                        expr.column_.field_id, index_func, elem_func);
719 720
                }
                case ArithOpType::Mul: {
Y
yah01 已提交
721 722
                    auto index_func = [val, right_operand](Index* index,
                                                           size_t offset) {
723 724 725
                        auto x = index->Reverse_Lookup(offset);
                        return (x * right_operand) != val;
                    };
726
                    auto elem_func = [val, right_operand](MayConstRef<T> x) {
Y
yah01 已提交
727 728 729
                        return ((x * right_operand) != val);
                    };
                    return ExecDataRangeVisitorImpl<T>(
730
                        expr.column_.field_id, index_func, elem_func);
731 732
                }
                case ArithOpType::Div: {
Y
yah01 已提交
733 734
                    auto index_func = [val, right_operand](Index* index,
                                                           size_t offset) {
735 736 737
                        auto x = index->Reverse_Lookup(offset);
                        return (x / right_operand) != val;
                    };
738
                    auto elem_func = [val, right_operand](MayConstRef<T> x) {
Y
yah01 已提交
739 740 741
                        return ((x / right_operand) != val);
                    };
                    return ExecDataRangeVisitorImpl<T>(
742
                        expr.column_.field_id, index_func, elem_func);
743 744
                }
                case ArithOpType::Mod: {
Y
yah01 已提交
745 746
                    auto index_func = [val, right_operand](Index* index,
                                                           size_t offset) {
747 748 749
                        auto x = index->Reverse_Lookup(offset);
                        return static_cast<T>(fmod(x, right_operand)) != val;
                    };
750
                    auto elem_func = [val, right_operand](MayConstRef<T> x) {
751 752
                        return (static_cast<T>(fmod(x, right_operand)) != val);
                    };
Y
yah01 已提交
753
                    return ExecDataRangeVisitorImpl<T>(
754
                        expr.column_.field_id, index_func, elem_func);
755 756 757 758 759 760 761 762 763 764 765 766 767
                }
                default: {
                    PanicInfo("unsupported arithmetic operation");
                }
            }
        }
        default: {
            PanicInfo("unsupported range node with arithmetic operation");
        }
    }
}
#pragma clang diagnostic pop

768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783
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_;
784
    auto pointer = milvus::Json::pointer(expr.column_.nested_path);
785 786 787 788 789 790 791 792 793 794 795 796

#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);                                         \
797 798
    } while (false)

799 800 801 802 803 804 805 806 807 808 809
#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);                                         \
810 811
    } while (false)

812 813 814 815 816 817 818 819 820
    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) {
821 822
                        BinaryArithRangeJSONCompare(x.value() + right_operand ==
                                                    val);
823 824 825 826 827 828 829 830 831 832
                    };
                    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) {
833 834
                        BinaryArithRangeJSONCompare(x.value() - right_operand ==
                                                    val);
835 836 837 838 839 840 841 842 843 844
                    };
                    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) {
845 846
                        BinaryArithRangeJSONCompare(x.value() * right_operand ==
                                                    val);
847 848 849 850 851 852 853 854 855 856
                    };
                    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) {
857 858
                        BinaryArithRangeJSONCompare(x.value() / right_operand ==
                                                    val);
859 860 861 862 863 864 865 866 867 868
                    };
                    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) {
869 870 871
                        BinaryArithRangeJSONCompare(
                            static_cast<ExprValueType>(
                                fmod(x.value(), right_operand)) == val);
872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888
                    };
                    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) {
889 890
                        BinaryArithRangeJSONCompareNotEqual(
                            x.value() + right_operand != val);
891 892 893 894 895 896 897 898 899 900
                    };
                    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) {
901 902
                        BinaryArithRangeJSONCompareNotEqual(
                            x.value() - right_operand != val);
903 904 905 906 907 908 909 910 911 912
                    };
                    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) {
913 914
                        BinaryArithRangeJSONCompareNotEqual(
                            x.value() * right_operand != val);
915 916 917 918 919 920 921 922 923 924
                    };
                    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) {
925 926
                        BinaryArithRangeJSONCompareNotEqual(
                            x.value() / right_operand != val);
927 928 929 930 931 932 933 934 935 936
                    };
                    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) {
937 938 939
                        BinaryArithRangeJSONCompareNotEqual(
                            static_cast<ExprValueType>(
                                fmod(x.value(), right_operand)) != val);
940 941 942 943 944 945 946 947 948 949 950 951 952
                    };
                    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");
        }
    }
953
}  // namespace milvus::query
954

955 956 957 958
#pragma clang diagnostic push
#pragma ide diagnostic ignored "Simplify"
template <typename T>
auto
Y
yah01 已提交
959 960 961 962 963
ExecExprVisitor::ExecBinaryRangeVisitorDispatcher(BinaryRangeExpr& expr_raw)
    -> BitsetType {
    typedef std::
        conditional_t<std::is_same_v<T, std::string_view>, std::string, T>
            IndexInnerType;
Y
yah01 已提交
964
    using Index = index::ScalarIndex<IndexInnerType>;
965 966

    // see also: https://github.com/milvus-io/milvus/issues/23646.
967 968
    typedef std::conditional_t<std::is_integral_v<IndexInnerType> &&
                                   !std::is_same_v<bool, T>,
969 970 971
                               int64_t,
                               IndexInnerType>
        HighPrecisionType;
972
    auto& expr = static_cast<BinaryRangeExprImpl<HighPrecisionType>&>(expr_raw);
973

974 975
    bool lower_inclusive = expr.lower_inclusive_;
    bool upper_inclusive = expr.upper_inclusive_;
976 977
    auto val1 = static_cast<HighPrecisionType>(expr.lower_value_);
    auto val2 = static_cast<HighPrecisionType>(expr.upper_value_);
978

979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995
    if constexpr (std::is_integral_v<T> && !std::is_same_v<bool, T>) {
        if (gt_ub<T>(val1)) {
            BitsetType r(row_count_);
            r.reset();
            return r;
        } else if (lt_lb<T>(val1)) {
            val1 = std::numeric_limits<T>::min();
            lower_inclusive = true;
        }

        if (gt_ub<T>(val2)) {
            val2 = std::numeric_limits<T>::max();
            upper_inclusive = true;
        } else if (lt_lb<T>(val2)) {
            BitsetType r(row_count_);
            r.reset();
            return r;
996
        }
997 998 999
    }

    auto index_func = [=](Index* index) {
Y
yah01 已提交
1000 1001
        return index->Range(val1, lower_inclusive, val2, upper_inclusive);
    };
1002

1003
    if (lower_inclusive && upper_inclusive) {
1004 1005 1006
        auto elem_func = [val1, val2](MayConstRef<T> x) {
            return (val1 <= x && x <= val2);
        };
1007 1008
        return ExecRangeVisitorImpl<T>(
            expr.column_.field_id, index_func, elem_func);
1009
    } else if (lower_inclusive && !upper_inclusive) {
1010 1011 1012
        auto elem_func = [val1, val2](MayConstRef<T> x) {
            return (val1 <= x && x < val2);
        };
1013 1014
        return ExecRangeVisitorImpl<T>(
            expr.column_.field_id, index_func, elem_func);
1015
    } else if (!lower_inclusive && upper_inclusive) {
1016 1017 1018
        auto elem_func = [val1, val2](MayConstRef<T> x) {
            return (val1 < x && x <= val2);
        };
1019 1020
        return ExecRangeVisitorImpl<T>(
            expr.column_.field_id, index_func, elem_func);
G
GuoRentong 已提交
1021
    } else {
1022 1023 1024
        auto elem_func = [val1, val2](MayConstRef<T> x) {
            return (val1 < x && x < val2);
        };
1025 1026
        return ExecRangeVisitorImpl<T>(
            expr.column_.field_id, index_func, elem_func);
G
GuoRentong 已提交
1027 1028 1029 1030
    }
}
#pragma clang diagnostic pop

1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045
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_;
1046
    auto pointer = milvus::Json::pointer(expr.column_.nested_path);
1047 1048

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

1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065
#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);                                         \
1066 1067
    } while (false)

1068 1069
    if (lower_inclusive && upper_inclusive) {
        auto elem_func = [&](const milvus::Json& json) {
1070
            BinaryRangeJSONCompare(val1 <= value && value <= val2);
1071 1072 1073 1074 1075
        };
        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) {
1076
            BinaryRangeJSONCompare(val1 <= value && value < val2);
1077 1078 1079 1080 1081
        };
        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) {
1082
            BinaryRangeJSONCompare(val1 < value && value <= val2);
1083 1084 1085 1086 1087
        };
        return ExecRangeVisitorImpl<milvus::Json>(
            expr.column_.field_id, index_func, elem_func);
    } else {
        auto elem_func = [&](const milvus::Json& json) {
1088
            BinaryRangeJSONCompare(val1 < value && value < val2);
1089 1090 1091 1092 1093 1094
        };
        return ExecRangeVisitorImpl<milvus::Json>(
            expr.column_.field_id, index_func, elem_func);
    }
}

N
neza2017 已提交
1095
void
1096
ExecExprVisitor::visit(UnaryRangeExpr& expr) {
1097 1098
    auto& field_meta = segment_.get_schema()[expr.column_.field_id];
    AssertInfo(expr.column_.data_type == field_meta.get_data_type(),
1099
               "[ExecExprVisitor]DataType of expr isn't field_meta data type");
1100
    BitsetType res;
1101
    switch (expr.column_.data_type) {
N
neza2017 已提交
1102
        case DataType::BOOL: {
1103
            res = ExecUnaryRangeVisitorDispatcher<bool>(expr);
N
neza2017 已提交
1104 1105
            break;
        }
G
GuoRentong 已提交
1106
        case DataType::INT8: {
1107
            res = ExecUnaryRangeVisitorDispatcher<int8_t>(expr);
G
GuoRentong 已提交
1108 1109 1110
            break;
        }
        case DataType::INT16: {
1111
            res = ExecUnaryRangeVisitorDispatcher<int16_t>(expr);
G
GuoRentong 已提交
1112 1113 1114
            break;
        }
        case DataType::INT32: {
1115
            res = ExecUnaryRangeVisitorDispatcher<int32_t>(expr);
G
GuoRentong 已提交
1116 1117 1118
            break;
        }
        case DataType::INT64: {
1119
            res = ExecUnaryRangeVisitorDispatcher<int64_t>(expr);
G
GuoRentong 已提交
1120 1121 1122
            break;
        }
        case DataType::FLOAT: {
1123
            res = ExecUnaryRangeVisitorDispatcher<float>(expr);
G
GuoRentong 已提交
1124 1125 1126
            break;
        }
        case DataType::DOUBLE: {
1127 1128 1129
            res = ExecUnaryRangeVisitorDispatcher<double>(expr);
            break;
        }
1130
        case DataType::VARCHAR: {
Y
yah01 已提交
1131 1132 1133 1134 1135
            if (segment_.type() == SegmentType::Growing) {
                res = ExecUnaryRangeVisitorDispatcher<std::string>(expr);
            } else {
                res = ExecUnaryRangeVisitorDispatcher<std::string_view>(expr);
            }
1136 1137
            break;
        }
1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158
        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;
        }
1159
        default:
1160 1161
            PanicInfo(fmt::format("unsupported data type: {}",
                                  expr.column_.data_type));
1162
    }
Y
yah01 已提交
1163 1164
    AssertInfo(res.size() == row_count_,
               "[ExecExprVisitor]Size of results not equal row count");
1165
    bitset_opt_ = std::move(res);
1166 1167
}

1168 1169
void
ExecExprVisitor::visit(BinaryArithOpEvalRangeExpr& expr) {
1170 1171
    auto& field_meta = segment_.get_schema()[expr.column_.field_id];
    AssertInfo(expr.column_.data_type == field_meta.get_data_type(),
1172 1173
               "[ExecExprVisitor]DataType of expr isn't field_meta data type");
    BitsetType res;
1174
    switch (expr.column_.data_type) {
1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198
        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;
        }
1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217
        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: {
1218 1219 1220
                    PanicInfo(
                        fmt::format("unsupported value type {} in expression",
                                    expr.val_case_));
1221 1222 1223 1224
                }
            }
            break;
        }
1225
        default:
1226 1227
            PanicInfo(fmt::format("unsupported data type: {}",
                                  expr.column_.data_type));
1228
    }
Y
yah01 已提交
1229 1230
    AssertInfo(res.size() == row_count_,
               "[ExecExprVisitor]Size of results not equal row count");
1231 1232 1233
    bitset_opt_ = std::move(res);
}

1234 1235
void
ExecExprVisitor::visit(BinaryRangeExpr& expr) {
1236 1237
    auto& field_meta = segment_.get_schema()[expr.column_.field_id];
    AssertInfo(expr.column_.data_type == field_meta.get_data_type(),
1238
               "[ExecExprVisitor]DataType of expr isn't field_meta data type");
1239
    BitsetType res;
1240
    switch (expr.column_.data_type) {
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
        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 已提交
1267 1268
            break;
        }
1269
        case DataType::VARCHAR: {
Y
yah01 已提交
1270 1271 1272 1273 1274
            if (segment_.type() == SegmentType::Growing) {
                res = ExecBinaryRangeVisitorDispatcher<std::string>(expr);
            } else {
                res = ExecBinaryRangeVisitorDispatcher<std::string_view>(expr);
            }
1275 1276
            break;
        }
1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296
        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: {
1297 1298 1299
                    PanicInfo(
                        fmt::format("unsupported value type {} in expression",
                                    expr.val_case_));
1300 1301 1302 1303
                }
            }
            break;
        }
G
GuoRentong 已提交
1304
        default:
1305 1306
            PanicInfo(fmt::format("unsupported data type: {}",
                                  expr.column_.data_type));
G
GuoRentong 已提交
1307
    }
Y
yah01 已提交
1308 1309
    AssertInfo(res.size() == row_count_,
               "[ExecExprVisitor]Size of results not equal row count");
1310
    bitset_opt_ = std::move(res);
N
neza2017 已提交
1311 1312
}

1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326
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");
    }
};

1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357
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) {
    auto size_per_chunk = segment_.size_per_chunk();
    auto num_chunks = upper_div(row_count_, size_per_chunk);
1358 1359
    std::vector<FixedVector<bool>> results;
    results.reserve(num_chunks);
1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450

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

1451 1452
template <typename Op>
auto
Y
yah01 已提交
1453 1454 1455 1456 1457 1458 1459 1460 1461 1462
ExecExprVisitor::ExecCompareExprDispatcher(CompareExpr& expr, Op op)
    -> BitsetType {
    using number = boost::variant<bool,
                                  int8_t,
                                  int16_t,
                                  int32_t,
                                  int64_t,
                                  float,
                                  double,
                                  std::string>;
1463 1464 1465 1466 1467
    auto is_string_expr = [&expr]() -> bool {
        return expr.left_data_type_ == DataType::VARCHAR ||
               expr.right_data_type_ == DataType::VARCHAR;
    };

1468 1469
    auto size_per_chunk = segment_.size_per_chunk();
    auto num_chunk = upper_div(row_count_, size_per_chunk);
1470
    std::deque<BitsetType> bitsets;
1471 1472 1473 1474

    // 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_);
1475 1476 1477
    AssertInfo(std::max(left_data_barrier, left_indexing_barrier) == num_chunk,
               "max(left_data_barrier, left_indexing_barrier) not equal to "
               "num_chunk");
1478

Y
yah01 已提交
1479 1480
    auto right_indexing_barrier =
        segment_.num_chunk_index(expr.right_field_id_);
1481
    auto right_data_barrier = segment_.num_chunk_data(expr.right_field_id_);
Y
yah01 已提交
1482 1483 1484 1485
    AssertInfo(
        std::max(right_data_barrier, right_indexing_barrier) == num_chunk,
        "max(right_data_barrier, right_indexing_barrier) not equal to "
        "num_chunk");
1486

1487 1488 1489 1490 1491 1492 1493 1494
    // 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.
1495
    for (int64_t chunk_id = 0; chunk_id < num_chunk; ++chunk_id) {
Y
yah01 已提交
1496 1497 1498 1499 1500 1501
        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)> {
1502 1503
            switch (type) {
                case DataType::BOOL: {
1504
                    if (chunk_id < data_barrier) {
Y
yah01 已提交
1505 1506 1507 1508 1509 1510
                        auto chunk_data =
                            segment_.chunk_data<bool>(field_id, chunk_id)
                                .data();
                        return [chunk_data](int i) -> const number {
                            return chunk_data[i];
                        };
1511 1512
                    } else {
                        // for case, sealed segment has loaded index for scalar field instead of raw data
Y
yah01 已提交
1513 1514 1515 1516 1517
                        auto& indexing = segment_.chunk_scalar_index<bool>(
                            field_id, chunk_id);
                        return [&indexing](int i) -> const number {
                            return indexing.Reverse_Lookup(i);
                        };
1518
                    }
1519 1520
                }
                case DataType::INT8: {
1521
                    if (chunk_id < data_barrier) {
Y
yah01 已提交
1522 1523 1524 1525 1526 1527
                        auto chunk_data =
                            segment_.chunk_data<int8_t>(field_id, chunk_id)
                                .data();
                        return [chunk_data](int i) -> const number {
                            return chunk_data[i];
                        };
1528 1529
                    } else {
                        // for case, sealed segment has loaded index for scalar field instead of raw data
Y
yah01 已提交
1530 1531 1532 1533 1534
                        auto& indexing = segment_.chunk_scalar_index<int8_t>(
                            field_id, chunk_id);
                        return [&indexing](int i) -> const number {
                            return indexing.Reverse_Lookup(i);
                        };
1535
                    }
1536 1537
                }
                case DataType::INT16: {
1538
                    if (chunk_id < data_barrier) {
Y
yah01 已提交
1539 1540 1541 1542 1543 1544
                        auto chunk_data =
                            segment_.chunk_data<int16_t>(field_id, chunk_id)
                                .data();
                        return [chunk_data](int i) -> const number {
                            return chunk_data[i];
                        };
1545 1546
                    } else {
                        // for case, sealed segment has loaded index for scalar field instead of raw data
Y
yah01 已提交
1547 1548 1549 1550 1551
                        auto& indexing = segment_.chunk_scalar_index<int16_t>(
                            field_id, chunk_id);
                        return [&indexing](int i) -> const number {
                            return indexing.Reverse_Lookup(i);
                        };
1552
                    }
1553 1554
                }
                case DataType::INT32: {
1555
                    if (chunk_id < data_barrier) {
Y
yah01 已提交
1556 1557 1558 1559 1560 1561
                        auto chunk_data =
                            segment_.chunk_data<int32_t>(field_id, chunk_id)
                                .data();
                        return [chunk_data](int i) -> const number {
                            return chunk_data[i];
                        };
1562 1563
                    } else {
                        // for case, sealed segment has loaded index for scalar field instead of raw data
Y
yah01 已提交
1564 1565 1566 1567 1568
                        auto& indexing = segment_.chunk_scalar_index<int32_t>(
                            field_id, chunk_id);
                        return [&indexing](int i) -> const number {
                            return indexing.Reverse_Lookup(i);
                        };
1569
                    }
1570 1571
                }
                case DataType::INT64: {
1572
                    if (chunk_id < data_barrier) {
Y
yah01 已提交
1573 1574 1575 1576 1577 1578
                        auto chunk_data =
                            segment_.chunk_data<int64_t>(field_id, chunk_id)
                                .data();
                        return [chunk_data](int i) -> const number {
                            return chunk_data[i];
                        };
1579 1580
                    } else {
                        // for case, sealed segment has loaded index for scalar field instead of raw data
Y
yah01 已提交
1581 1582 1583 1584 1585
                        auto& indexing = segment_.chunk_scalar_index<int64_t>(
                            field_id, chunk_id);
                        return [&indexing](int i) -> const number {
                            return indexing.Reverse_Lookup(i);
                        };
1586
                    }
1587 1588
                }
                case DataType::FLOAT: {
1589
                    if (chunk_id < data_barrier) {
Y
yah01 已提交
1590 1591 1592 1593 1594 1595
                        auto chunk_data =
                            segment_.chunk_data<float>(field_id, chunk_id)
                                .data();
                        return [chunk_data](int i) -> const number {
                            return chunk_data[i];
                        };
1596 1597
                    } else {
                        // for case, sealed segment has loaded index for scalar field instead of raw data
Y
yah01 已提交
1598 1599 1600 1601 1602
                        auto& indexing = segment_.chunk_scalar_index<float>(
                            field_id, chunk_id);
                        return [&indexing](int i) -> const number {
                            return indexing.Reverse_Lookup(i);
                        };
1603
                    }
1604 1605
                }
                case DataType::DOUBLE: {
1606
                    if (chunk_id < data_barrier) {
Y
yah01 已提交
1607 1608 1609 1610 1611 1612
                        auto chunk_data =
                            segment_.chunk_data<double>(field_id, chunk_id)
                                .data();
                        return [chunk_data](int i) -> const number {
                            return chunk_data[i];
                        };
1613 1614
                    } else {
                        // for case, sealed segment has loaded index for scalar field instead of raw data
Y
yah01 已提交
1615 1616 1617 1618 1619
                        auto& indexing = segment_.chunk_scalar_index<double>(
                            field_id, chunk_id);
                        return [&indexing](int i) -> const number {
                            return indexing.Reverse_Lookup(i);
                        };
1620
                    }
1621 1622
                }
                case DataType::VARCHAR: {
1623
                    if (chunk_id < data_barrier) {
Y
yah01 已提交
1624
                        if (segment_.type() == SegmentType::Growing) {
Y
yah01 已提交
1625 1626 1627 1628 1629 1630 1631
                            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 已提交
1632
                        } else {
Y
yah01 已提交
1633 1634 1635 1636 1637 1638 1639
                            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 已提交
1640
                        }
1641 1642
                    } else {
                        // for case, sealed segment has loaded index for scalar field instead of raw data
Y
yah01 已提交
1643 1644 1645 1646 1647 1648
                        auto& indexing =
                            segment_.chunk_scalar_index<std::string>(field_id,
                                                                     chunk_id);
                        return [&indexing](int i) -> const number {
                            return indexing.Reverse_Lookup(i);
                        };
1649
                    }
1650 1651
                }
                default:
1652
                    PanicInfo(fmt::format("unsupported data type: {}", type));
1653 1654
            }
        };
Y
yah01 已提交
1655 1656 1657 1658
        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);
1659

1660
        BitsetType bitset(size);
1661
        for (int i = 0; i < size; ++i) {
Y
yah01 已提交
1662 1663
            bool is_in = boost::apply_visitor(
                Relational<decltype(op)>{}, left(i), right(i));
1664 1665 1666 1667
            bitset[i] = is_in;
        }
        bitsets.emplace_back(std::move(bitset));
    }
1668
    auto final_result = Assemble(bitsets);
Y
yah01 已提交
1669 1670
    AssertInfo(final_result.size() == row_count_,
               "[ExecExprVisitor]Size of results not equal row count");
1671
    return final_result;
1672 1673 1674 1675 1676
}

void
ExecExprVisitor::visit(CompareExpr& expr) {
    auto& schema = segment_.get_schema();
1677 1678
    auto& left_field_meta = schema[expr.left_field_id_];
    auto& right_field_meta = schema[expr.right_field_id_];
1679
    AssertInfo(expr.left_data_type_ == left_field_meta.get_data_type(),
1680 1681
               "[ExecExprVisitor]Left data type not equal to left field "
               "meta type");
1682 1683 1684
    AssertInfo(expr.right_data_type_ == right_field_meta.get_data_type(),
               "[ExecExprVisitor]right data type not equal to right field "
               "meta type");
1685

1686
    BitsetType res;
1687
    switch (expr.op_type_) {
1688
        case OpType::Equal: {
1689
            res = ExecCompareExprDispatcher(expr, std::equal_to<>{});
1690 1691 1692
            break;
        }
        case OpType::NotEqual: {
1693
            res = ExecCompareExprDispatcher(expr, std::not_equal_to<>{});
1694 1695 1696
            break;
        }
        case OpType::GreaterEqual: {
1697
            res = ExecCompareExprDispatcher(expr, std::greater_equal<>{});
1698 1699 1700
            break;
        }
        case OpType::GreaterThan: {
1701
            res = ExecCompareExprDispatcher(expr, std::greater<>{});
1702 1703 1704
            break;
        }
        case OpType::LessEqual: {
1705
            res = ExecCompareExprDispatcher(expr, std::less_equal<>{});
1706 1707 1708
            break;
        }
        case OpType::LessThan: {
1709
            res = ExecCompareExprDispatcher(expr, std::less<>{});
1710 1711
            break;
        }
1712
        case OpType::PrefixMatch: {
Y
yah01 已提交
1713 1714
            res =
                ExecCompareExprDispatcher(expr, MatchOp<OpType::PrefixMatch>{});
1715 1716 1717 1718
            break;
        }
            // case OpType::PostfixMatch: {
            // }
1719 1720 1721 1722
        default: {
            PanicInfo("unsupported optype");
        }
    }
Y
yah01 已提交
1723 1724
    AssertInfo(res.size() == row_count_,
               "[ExecExprVisitor]Size of results not equal row count");
1725
    bitset_opt_ = std::move(res);
1726 1727
}

S
sunby 已提交
1728 1729
template <typename T>
auto
1730
ExecExprVisitor::ExecTermVisitorImpl(TermExpr& expr_raw) -> BitsetType {
1731 1732 1733 1734
    typedef std::
        conditional_t<std::is_same_v<T, std::string_view>, std::string, T>
            InnerType;
    auto& expr = static_cast<TermExprImpl<InnerType>&>(expr_raw);
S
sunby 已提交
1735
    auto& schema = segment_.get_schema();
1736
    auto primary_filed_id = schema.get_primary_field_id();
1737
    auto field_id = expr_raw.column_.field_id;
1738
    auto& field_meta = schema[field_id];
1739 1740

    bool use_pk_index = false;
1741
    if (primary_filed_id.has_value()) {
Y
yah01 已提交
1742 1743
        use_pk_index = primary_filed_id.value() == field_id &&
                       IsPrimaryKeyDataType(field_meta.get_data_type());
1744 1745 1746 1747
    }

    if (use_pk_index) {
        auto id_array = std::make_unique<IdArray>();
1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765
        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");
            }
1766
        }
1767

1768 1769
        auto [uids, seg_offsets] = segment_.search_ids(*id_array, timestamp_);
        BitsetType bitset(row_count_);
1770
        std::vector<int64_t> cached_offsets;
1771 1772 1773
        for (const auto& offset : seg_offsets) {
            auto _offset = (int64_t)offset.get();
            bitset[_offset] = true;
1774 1775 1776 1777 1778 1779
            cached_offsets.push_back(_offset);
        }
        // If enable plan_visitor pk index cache, pass offsets to it
        if (plan_visitor_ != nullptr) {
            plan_visitor_->SetExprUsePkIndex(true);
            plan_visitor_->SetExprCacheOffsets(std::move(cached_offsets));
1780
        }
Y
yah01 已提交
1781 1782
        AssertInfo(bitset.size() == row_count_,
                   "[ExecExprVisitor]Size of results not equal row count");
1783 1784 1785
        return bitset;
    }

1786
    return ExecTermVisitorImplTemplate<T>(expr_raw);
S
sunby 已提交
1787 1788
}

1789 1790 1791
template <typename T>
auto
ExecExprVisitor::ExecTermVisitorImplTemplate(TermExpr& expr_raw) -> BitsetType {
Y
yah01 已提交
1792 1793 1794
    typedef std::
        conditional_t<std::is_same_v<T, std::string_view>, std::string, T>
            IndexInnerType;
Y
yah01 已提交
1795 1796
    using Index = index::ScalarIndex<IndexInnerType>;
    auto& expr = static_cast<TermExprImpl<IndexInnerType>&>(expr_raw);
1797
    const auto& terms = expr.terms_;
1798 1799 1800
    auto n = terms.size();
    std::unordered_set<T> term_set(expr.terms_.begin(), expr.terms_.end());

Y
yah01 已提交
1801 1802 1803
    auto index_func = [&terms, n](Index* index) {
        return index->In(n, terms.data());
    };
1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825

#if defined(USE_DYNAMIC_SIMD)
    std::function<bool(MayConstRef<T> x)> elem_func;
    if (n <= milvus::simd::TERM_EXPR_IN_SIZE_THREAD) {
        elem_func = [&terms, &term_set, n](MayConstRef<T> x) {
            if constexpr (std::is_integral<T>::value ||
                          std::is_floating_point<T>::value) {
                return milvus::simd::find_term_func<T>(terms.data(), n, x);
            } else {
                // For string type, simd performance not better than set mode
                static_assert(std::is_same<T, std::string>::value ||
                              std::is_same<T, std::string_view>::value);
                return term_set.find(x) != term_set.end();
            }
        };
    } else {
        elem_func = [&term_set, n](MayConstRef<T> x) {
            return term_set.find(x) != term_set.end();
        };
    }
#else
    auto elem_func = [&term_set](MayConstRef<T> x) {
1826 1827
        return term_set.find(x) != term_set.end();
    };
1828
#endif
1829

1830 1831
    return ExecRangeVisitorImpl<T>(
        expr.column_.field_id, index_func, elem_func);
1832 1833
}

1834 1835 1836
// TODO: bool is so ugly here.
template <>
auto
Y
yah01 已提交
1837 1838
ExecExprVisitor::ExecTermVisitorImplTemplate<bool>(TermExpr& expr_raw)
    -> BitsetType {
1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856
    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;
    };

1857
    auto elem_func = [&terms, &term_set](MayConstRef<T> x) {
1858 1859 1860 1861 1862
        //// terms has already been sorted.
        // return std::binary_search(terms.begin(), terms.end(), x);
        return term_set.find(x) != term_set.end();
    };

1863 1864 1865 1866 1867 1868
    return ExecRangeVisitorImpl<T>(
        expr.column_.field_id, index_func, elem_func);
}

template <typename ExprValueType>
auto
1869
ExecExprVisitor::ExecTermJsonFieldInVariable(TermExpr& expr_raw) -> BitsetType {
1870 1871
    using Index = index::ScalarIndex<milvus::Json>;
    auto& expr = static_cast<TermExprImpl<ExprValueType>&>(expr_raw);
1872
    auto pointer = milvus::Json::pointer(expr.column_.nested_path);
1873
    auto index_func = [](Index* index) { return TargetBitmap{}; };
1874 1875 1876 1877 1878 1879 1880 1881 1882 1883

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

1884
    auto elem_func = [&term_set, &pointer](const milvus::Json& json) {
1885 1886 1887 1888
        using GetType =
            std::conditional_t<std::is_same_v<ExprValueType, std::string>,
                               std::string_view,
                               ExprValueType>;
1889
        auto x = json.template at<GetType>(pointer);
1890
        if (x.error()) {
1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901
            if constexpr (std::is_same_v<GetType, std::int64_t>) {
                auto x = json.template at<double>(pointer);
                if (x.error()) {
                    return false;
                }

                auto value = x.value();
                // if the term set is {1}, and the value is 1.1, we should not return true.
                return std::floor(value) == value &&
                       term_set.find(ExprValueType(value)) != term_set.end();
            }
1902 1903 1904 1905 1906 1907 1908
            return false;
        }
        return term_set.find(ExprValueType(x.value())) != term_set.end();
    };

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

1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936
template <typename ExprValueType>
auto
ExecExprVisitor::ExecTermJsonVariableInField(TermExpr& expr_raw) -> BitsetType {
    using Index = index::ScalarIndex<milvus::Json>;
    auto& expr = static_cast<TermExprImpl<ExprValueType>&>(expr_raw);
    auto pointer = milvus::Json::pointer(expr.column_.nested_path);
    auto index_func = [](Index* index) { return TargetBitmap{}; };

    AssertInfo(expr.terms_.size() == 1,
               "element length in json array must be one");
    ExprValueType target_val = expr.terms_[0];

    auto elem_func = [&target_val, &pointer](const milvus::Json& json) {
        using GetType =
            std::conditional_t<std::is_same_v<ExprValueType, std::string>,
                               std::string_view,
                               ExprValueType>;
        auto doc = json.doc();
        auto array = doc.at_pointer(pointer).get_array();
        if (array.error())
            return false;
        for (auto it = array.begin(); it != array.end(); ++it) {
            auto val = (*it).template get<GetType>();
            if (val.error()) {
                return false;
            }
1937
            if (val.value() == target_val) {
1938
                return true;
1939
            }
1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958
        }
        return false;
    };

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

template <typename ExprValueType>
auto
ExecExprVisitor::ExecTermVisitorImplTemplateJson(TermExpr& expr_raw)
    -> BitsetType {
    if (expr_raw.is_in_field_) {
        return ExecTermJsonVariableInField<ExprValueType>(expr_raw);
    } else {
        return ExecTermJsonFieldInVariable<ExprValueType>(expr_raw);
    }
}

S
sunby 已提交
1959 1960
void
ExecExprVisitor::visit(TermExpr& expr) {
1961 1962
    auto& field_meta = segment_.get_schema()[expr.column_.field_id];
    AssertInfo(expr.column_.data_type == field_meta.get_data_type(),
1963 1964
               "[ExecExprVisitor]DataType of expr isn't field_meta "
               "data type ");
1965
    BitsetType res;
1966
    switch (expr.column_.data_type) {
S
sunby 已提交
1967
        case DataType::BOOL: {
1968
            res = ExecTermVisitorImpl<bool>(expr);
S
sunby 已提交
1969 1970 1971
            break;
        }
        case DataType::INT8: {
1972
            res = ExecTermVisitorImpl<int8_t>(expr);
S
sunby 已提交
1973 1974 1975
            break;
        }
        case DataType::INT16: {
1976
            res = ExecTermVisitorImpl<int16_t>(expr);
S
sunby 已提交
1977 1978 1979
            break;
        }
        case DataType::INT32: {
1980
            res = ExecTermVisitorImpl<int32_t>(expr);
S
sunby 已提交
1981 1982 1983
            break;
        }
        case DataType::INT64: {
1984
            res = ExecTermVisitorImpl<int64_t>(expr);
S
sunby 已提交
1985 1986 1987
            break;
        }
        case DataType::FLOAT: {
1988
            res = ExecTermVisitorImpl<float>(expr);
S
sunby 已提交
1989 1990 1991
            break;
        }
        case DataType::DOUBLE: {
1992
            res = ExecTermVisitorImpl<double>(expr);
S
sunby 已提交
1993 1994
            break;
        }
1995
        case DataType::VARCHAR: {
Y
yah01 已提交
1996 1997 1998 1999 2000
            if (segment_.type() == SegmentType::Growing) {
                res = ExecTermVisitorImpl<std::string>(expr);
            } else {
                res = ExecTermVisitorImpl<std::string_view>(expr);
            }
2001 2002
            break;
        }
2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025
        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 已提交
2026
        default:
2027 2028
            PanicInfo(fmt::format("unsupported data type: {}",
                                  expr.column_.data_type));
S
sunby 已提交
2029
    }
Y
yah01 已提交
2030 2031
    AssertInfo(res.size() == row_count_,
               "[ExecExprVisitor]Size of results not equal row count");
2032
    bitset_opt_ = std::move(res);
S
sunby 已提交
2033
}
2034 2035 2036 2037 2038 2039 2040

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;
2041
    auto pointer = milvus::Json::pointer(expr.column_.nested_path);
2042 2043 2044
    switch (expr.column_.data_type) {
        case DataType::JSON: {
            using Index = index::ScalarIndex<milvus::Json>;
2045 2046 2047
            auto index_func = [&](Index* index) { return TargetBitmap{}; };
            auto elem_func = [&](const milvus::Json& json) {
                auto x = json.exist(pointer);
2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062
                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);
}

J
Jiquan Long 已提交
2063 2064 2065 2066 2067 2068 2069
void
ExecExprVisitor::visit(AlwaysTrueExpr& expr) {
    BitsetType res(row_count_);
    res.set();
    bitset_opt_ = std::move(res);
}

2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534
bool
compareTwoJsonArray(
    simdjson::simdjson_result<simdjson::fallback::ondemand::array> arr1,
    const proto::plan::Array& arr2) {
    if (arr2.array_size() != arr1.count_elements()) {
        return false;
    }
    int i = 0;
    for (auto&& it : arr1) {
        switch (arr2.array(i).val_case()) {
            case proto::plan::GenericValue::kBoolVal: {
                auto val = it.template get<bool>();
                if (val.error() || val.value() != arr2.array(i).bool_val()) {
                    return false;
                }
                break;
            }
            case proto::plan::GenericValue::kInt64Val: {
                auto val = it.template get<int64_t>();
                if (val.error() || val.value() != arr2.array(i).int64_val()) {
                    return false;
                }
                break;
            }
            case proto::plan::GenericValue::kFloatVal: {
                auto val = it.template get<double>();
                if (val.error() || val.value() != arr2.array(i).float_val()) {
                    return false;
                }
                break;
            }
            case proto::plan::GenericValue::kStringVal: {
                auto val = it.template get<std::string_view>();
                if (val.error() || val.value() != arr2.array(i).string_val()) {
                    return false;
                }
                break;
            }
            default:
                PanicInfo(fmt::format("unsupported data type {}",
                                      arr2.array(i).val_case()));
        }
        i++;
    }
    return true;
}

template <typename ExprValueType>
auto
ExecExprVisitor::ExecJsonContains(JsonContainsExpr& expr_raw) -> BitsetType {
    using Index = index::ScalarIndex<milvus::Json>;
    auto& expr = static_cast<JsonContainsExprImpl<ExprValueType>&>(expr_raw);
    auto pointer = milvus::Json::pointer(expr.column_.nested_path);
    auto index_func = [](Index* index) { return TargetBitmap{}; };
    using GetType =
        std::conditional_t<std::is_same_v<ExprValueType, std::string>,
                           std::string_view,
                           ExprValueType>;
    std::unordered_set<GetType> elements;
    for (auto const& element : expr.elements_) {
        elements.insert(element);
    }
    auto elem_func = [&elements, &pointer](const milvus::Json& json) {
        auto doc = json.doc();
        auto array = doc.at_pointer(pointer).get_array();
        if (array.error()) {
            return false;
        }
        for (auto&& it : array) {
            auto val = it.template get<GetType>();
            if (val.error()) {
                continue;
            }
            if (elements.count(val.value()) > 0) {
                return true;
            }
        }
        return false;
    };

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

auto
ExecExprVisitor::ExecJsonContainsArray(JsonContainsExpr& expr_raw)
    -> BitsetType {
    using Index = index::ScalarIndex<milvus::Json>;
    auto& expr =
        static_cast<JsonContainsExprImpl<proto::plan::Array>&>(expr_raw);
    auto pointer = milvus::Json::pointer(expr.column_.nested_path);
    auto index_func = [](Index* index) { return TargetBitmap{}; };
    auto& elements = expr.elements_;
    auto elem_func = [&elements, &pointer](const milvus::Json& json) {
        auto doc = json.doc();
        auto array = doc.at_pointer(pointer).get_array();
        if (array.error()) {
            return false;
        }
        for (auto const& element : elements) {
            for (auto&& it : array) {
                auto val = it.get_array();
                if (val.error()) {
                    continue;
                }
                if (compareTwoJsonArray(val, element)) {
                    return true;
                }
            }
        }
        return false;
    };

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

auto
ExecExprVisitor::ExecJsonContainsWithDiffType(JsonContainsExpr& expr_raw)
    -> BitsetType {
    using Index = index::ScalarIndex<milvus::Json>;
    auto& expr =
        static_cast<JsonContainsExprImpl<proto::plan::GenericValue>&>(expr_raw);
    auto pointer = milvus::Json::pointer(expr.column_.nested_path);
    auto index_func = [](Index* index) { return TargetBitmap{}; };
    auto& elements = expr.elements_;
    auto elem_func = [&elements, &pointer](const milvus::Json& json) {
        auto doc = json.doc();
        auto array = doc.at_pointer(pointer).get_array();
        if (array.error()) {
            return false;
        }
        // Note: array can only be iterated once
        for (auto&& it : array) {
            for (auto const& element : elements) {
                switch (element.val_case()) {
                    case proto::plan::GenericValue::kBoolVal: {
                        auto val = it.template get<bool>();
                        if (val.error()) {
                            continue;
                        }
                        if (val.value() == element.bool_val()) {
                            return true;
                        }
                        break;
                    }
                    case proto::plan::GenericValue::kInt64Val: {
                        auto val = it.template get<int64_t>();
                        if (val.error()) {
                            continue;
                        }
                        if (val.value() == element.int64_val()) {
                            return true;
                        }
                        break;
                    }
                    case proto::plan::GenericValue::kFloatVal: {
                        auto val = it.template get<double>();
                        if (val.error()) {
                            continue;
                        }
                        if (val.value() == element.float_val()) {
                            return true;
                        }
                        break;
                    }
                    case proto::plan::GenericValue::kStringVal: {
                        auto val = it.template get<std::string_view>();
                        if (val.error()) {
                            continue;
                        }
                        if (val.value() == element.string_val()) {
                            return true;
                        }
                        break;
                    }
                    case proto::plan::GenericValue::kArrayVal: {
                        auto val = it.get_array();
                        if (val.error()) {
                            continue;
                        }
                        if (compareTwoJsonArray(val, element.array_val())) {
                            return true;
                        }
                        break;
                    }
                    default:
                        PanicInfo(fmt::format("unsupported data type {}",
                                              element.val_case()));
                }
            }
        }
        return false;
    };

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

template <typename ExprValueType>
auto
ExecExprVisitor::ExecJsonContainsAll(JsonContainsExpr& expr_raw) -> BitsetType {
    using Index = index::ScalarIndex<milvus::Json>;
    auto& expr = static_cast<JsonContainsExprImpl<ExprValueType>&>(expr_raw);
    auto pointer = milvus::Json::pointer(expr.column_.nested_path);
    auto index_func = [](Index* index) { return TargetBitmap{}; };
    using GetType =
        std::conditional_t<std::is_same_v<ExprValueType, std::string>,
                           std::string_view,
                           ExprValueType>;

    std::unordered_set<GetType> elements;
    for (auto const& element : expr.elements_) {
        elements.insert(element);
    }
    //    auto elements = expr.elements_;
    auto elem_func = [&elements, &pointer](const milvus::Json& json) {
        auto doc = json.doc();
        auto array = doc.at_pointer(pointer).get_array();
        if (array.error()) {
            return false;
        }
        std::unordered_set<GetType> tmp_elements(elements);
        // Note: array can only be iterated once
        for (auto&& it : array) {
            auto val = it.template get<GetType>();
            if (val.error()) {
                continue;
            }
            tmp_elements.erase(val.value());
            if (tmp_elements.size() == 0) {
                return true;
            }
        }
        return tmp_elements.size() == 0;
    };

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

auto
ExecExprVisitor::ExecJsonContainsAllArray(JsonContainsExpr& expr_raw)
    -> BitsetType {
    using Index = index::ScalarIndex<milvus::Json>;
    auto& expr =
        static_cast<JsonContainsExprImpl<proto::plan::Array>&>(expr_raw);
    auto pointer = milvus::Json::pointer(expr.column_.nested_path);
    auto index_func = [](Index* index) { return TargetBitmap{}; };
    auto& elements = expr.elements_;
    std::unordered_set<int> elements_index;
    int i = 0;
    for (auto& element : expr.elements_) {
        elements_index.insert(i);
        i++;
    }
    auto elem_func =
        [&elements, &elements_index, &pointer](const milvus::Json& json) {
            auto doc = json.doc();
            auto array = doc.at_pointer(pointer).get_array();
            if (array.error()) {
                return false;
            }
            std::unordered_set<int> tmp_elements_index(elements_index);
            for (auto&& it : array) {
                auto val = it.get_array();
                if (val.error()) {
                    continue;
                }
                int i = -1;
                for (auto const& element : elements) {
                    i++;
                    if (compareTwoJsonArray(val, element)) {
                        tmp_elements_index.erase(i);
                        break;
                    }
                }
                if (tmp_elements_index.size() == 0) {
                    return true;
                }
            }
            return tmp_elements_index.size() == 0;
        };

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

auto
ExecExprVisitor::ExecJsonContainsAllWithDiffType(JsonContainsExpr& expr_raw)
    -> BitsetType {
    using Index = index::ScalarIndex<milvus::Json>;
    auto& expr =
        static_cast<JsonContainsExprImpl<proto::plan::GenericValue>&>(expr_raw);
    auto pointer = milvus::Json::pointer(expr.column_.nested_path);
    auto index_func = [](Index* index) { return TargetBitmap{}; };

    auto elements = expr.elements_;
    std::unordered_set<int> elements_index;
    int i = 0;
    for (auto& element : expr.elements_) {
        elements_index.insert(i);
        i++;
    }
    auto elem_func =
        [&elements, &elements_index, &pointer](const milvus::Json& json) {
            auto doc = json.doc();
            auto array = doc.at_pointer(pointer).get_array();
            if (array.error()) {
                return false;
            }
            std::unordered_set<int> tmp_elements_index(elements_index);
            for (auto&& it : array) {
                int i = -1;
                for (auto& element : elements) {
                    i++;
                    switch (element.val_case()) {
                        case proto::plan::GenericValue::kBoolVal: {
                            auto val = it.template get<bool>();
                            if (val.error()) {
                                continue;
                            }
                            if (val.value() == element.bool_val()) {
                                tmp_elements_index.erase(i);
                            }
                            break;
                        }
                        case proto::plan::GenericValue::kInt64Val: {
                            auto val = it.template get<int64_t>();
                            if (val.error()) {
                                continue;
                            }
                            if (val.value() == element.int64_val()) {
                                tmp_elements_index.erase(i);
                            }
                            break;
                        }
                        case proto::plan::GenericValue::kFloatVal: {
                            auto val = it.template get<double>();
                            if (val.error()) {
                                continue;
                            }
                            if (val.value() == element.float_val()) {
                                tmp_elements_index.erase(i);
                            }
                            break;
                        }
                        case proto::plan::GenericValue::kStringVal: {
                            auto val = it.template get<std::string_view>();
                            if (val.error()) {
                                continue;
                            }
                            if (val.value() == element.string_val()) {
                                tmp_elements_index.erase(i);
                            }
                            break;
                        }
                        case proto::plan::GenericValue::kArrayVal: {
                            auto val = it.get_array();
                            if (val.error()) {
                                continue;
                            }
                            if (compareTwoJsonArray(val, element.array_val())) {
                                tmp_elements_index.erase(i);
                            }
                            break;
                        }
                        default:
                            PanicInfo(fmt::format("unsupported data type {}",
                                                  element.val_case()));
                    }
                    if (tmp_elements_index.size() == 0) {
                        return true;
                    }
                }
                if (tmp_elements_index.size() == 0) {
                    return true;
                }
            }
            return tmp_elements_index.size() == 0;
        };

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

void
ExecExprVisitor::visit(JsonContainsExpr& expr) {
    auto& field_meta = segment_.get_schema()[expr.column_.field_id];
    AssertInfo(
        expr.column_.data_type == DataType::JSON,
        "[ExecExprVisitor]DataType of JsonContainsExpr isn't json data type");
    BitsetType res;
    switch (expr.op_) {
        case proto::plan::JSONContainsExpr_JSONOp_Contains:
        case proto::plan::JSONContainsExpr_JSONOp_ContainsAny: {
            if (expr.same_type_) {
                switch (expr.val_case_) {
                    case proto::plan::GenericValue::kBoolVal: {
                        res = ExecJsonContains<bool>(expr);
                        break;
                    }
                    case proto::plan::GenericValue::kInt64Val: {
                        res = ExecJsonContains<int64_t>(expr);
                        break;
                    }
                    case proto::plan::GenericValue::kFloatVal: {
                        res = ExecJsonContains<double>(expr);
                        break;
                    }
                    case proto::plan::GenericValue::kStringVal: {
                        res = ExecJsonContains<std::string>(expr);
                        break;
                    }
                    case proto::plan::GenericValue::kArrayVal: {
                        res = ExecJsonContainsArray(expr);
                        break;
                    }
                    default:
                        PanicInfo(fmt::format("unsupported data type"));
                }
                break;
            }
            res = ExecJsonContainsWithDiffType(expr);
            break;
        }
        case proto::plan::JSONContainsExpr_JSONOp_ContainsAll: {
            if (expr.same_type_) {
                switch (expr.val_case_) {
                    case proto::plan::GenericValue::kBoolVal: {
                        res = ExecJsonContainsAll<bool>(expr);
                        break;
                    }
                    case proto::plan::GenericValue::kInt64Val: {
                        res = ExecJsonContainsAll<int64_t>(expr);
                        break;
                    }
                    case proto::plan::GenericValue::kFloatVal: {
                        res = ExecJsonContainsAll<double>(expr);
                        break;
                    }
                    case proto::plan::GenericValue::kStringVal: {
                        res = ExecJsonContainsAll<std::string>(expr);
                        break;
                    }
                    case proto::plan::GenericValue::kArrayVal: {
                        res = ExecJsonContainsAllArray(expr);
                        break;
                    }
                    default:
                        PanicInfo(fmt::format("unsupported data type"));
                }
                break;
            }
            res = ExecJsonContainsAllWithDiffType(expr);
            break;
        }
        default:
            PanicInfo(fmt::format("unsupported json contains type"));
    }
    AssertInfo(res.size() == row_count_,
               "[ExecExprVisitor]Size of results not equal row count");
    bitset_opt_ = std::move(res);
}

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