feat: add fts support (#408)

Add BM25-based full-text search with CJK (jieba) tokenization, supporting
  query_string and match_string syntax, phrase queries, boolean operators
  (AND/OR/NOT/MUST), and hybrid retrieval with existing vector search.

  ## Core
  - BitPacked posting format with block-max WAND pruning
  - Tokenizer pipeline: jieba (cut/cut_for_search/hmm/full), whitespace,
    lowercase, with extensible pipeline composition
  - Query parser: boolean operators, phrase queries, field scoping,
    boost, MUST(+) modifier inside OR (ES query_string semantics)
  - AST rewriter: dedup repeated terms with linear boost aggregation,
    flatten same-type composites, canonicalize OR-with-must_not into AND
    wrapper, empty-node propagation, contradiction detection
  - FTS reduce/merge integrated into Optimize compaction
  - Multi-segment score-descending sort
  - Auto-register bundled jieba dict on SDK import

  ## Performance
  - Block-max WAND with cached block_max_info_for (single binary search)
  - AVX2/SSE bitpacked encoding with cross-arch scalar fallback
  - MultiGet for batch posting retrieval and phrase position verification
  - HashSkipList memtable for posting writes
  - PinnableSlice zero-copy reads
  - Filter pushdown into composite iterators (Disjunction/Conjunction/Phrase)
  - Candidate-driven (brute-force) evaluation for selective invert filters
  - Precomputed BM25 IDF weights, cached SIMD dispatch pointers
  - Shortest-list anchor for phrase position matching
  - Single-open per-term posting iterator

  ## Query
  - Tokenize query terms through the same pipeline as indexing
  - EmptyNode for zero-token queries (all stop-words / punctuation)
  - Backslash unescape after lexing in query parser
  - Schema allows collections without vector fields (FTS-only use case)
  - Create/Drop Index validates supported index types
  - FTS fields disallowed in SQL filter expressions

  ## Bindings
  - C API: fts query params, brute-force ratio config
  - Python SDK: FTS search, jieba dict auto-registration

  ## Internals
  - Bypass cppjieba::Jieba to drop KeywordExtractor (~12MB fewer required files)
  - Hide tokenizer pipeline from public header (Pimpl-style FtsState)
  - ListColumnFamilies to avoid double-open on segment load
  - Reorganized fts_column into tokenizer/, posting/, iterator/ subdirs
This commit is contained in:
egolearner
2026-06-01 15:02:54 +08:00
committed by GitHub
parent 74beb2a828
commit 02bfb31cf5
154 changed files with 22646 additions and 223 deletions
@@ -400,6 +400,11 @@ Result<QueryInfo::Ptr> QueryAnalyzer::create_queryinfo_from_sqlinfo(
// set group by
query_info->set_group_by(select_info->group_by());
// set fts query
if (select_info->has_fts_query()) {
query_info->set_fts_cond_info(select_info->fts_cond_info());
}
return query_info;
}
+6
View File
@@ -85,6 +85,12 @@ std::string QueryInfo::to_string() const {
")\n");
}
str += "fts_cond:\n";
if (fts_cond_info_ != nullptr) {
str += fts_cond_info_->to_string();
str += "\n";
}
str += "filter_cond:\n";
if (filter_cond_ != nullptr) {
str += filter_cond_->text();
+11
View File
@@ -22,6 +22,7 @@
#include <zvec/core/framework/index_meta.h>
#include <zvec/db/schema.h>
#include "db/common/constants.h"
#include "db/sqlengine/common/fts_cond_info.h"
#include "db/sqlengine/common/group_by.h"
#include "query_field_info.h"
#include "query_node.h"
@@ -125,6 +126,7 @@ class QueryInfo {
bool reverse_sort_{false};
};
public:
QueryInfo() = default;
~QueryInfo() = default;
@@ -161,6 +163,14 @@ class QueryInfo {
return vector_cond_info_;
}
void set_fts_cond_info(FtsCondInfo::Ptr value) {
fts_cond_info_ = std::move(value);
}
const FtsCondInfo::Ptr &fts_cond_info() const {
return fts_cond_info_;
}
void set_query_topn(uint32_t value) {
query_topn_ = value;
}
@@ -340,6 +350,7 @@ class QueryInfo {
QueryNode::Ptr filter_cond_{nullptr};
QueryVectorCondInfo::Ptr vector_cond_info_{nullptr};
FtsCondInfo::Ptr fts_cond_info_{nullptr};
// these two are for post filtering only
QueryNode::Ptr post_invert_cond_{nullptr};
+11 -3
View File
@@ -173,6 +173,14 @@ ControlOp SearchCondCheckWalker::access(const QueryNode::Ptr &query_node,
return ControlOp::BREAK;
}
// FTS field can only be used as a query target, not as a filter condition.
if (forward_field->index_type() == zvec::IndexType::FTS) {
err_msg_ = ailego::StringHelper::Concat(
"fts field is not allowed in filter condition: ",
query_rel_node->text());
return ControlOp::BREAK;
}
// only string field or is null allow empty string value
if (right->text().empty() &&
(forward_field->element_data_type() != DataType::STRING &&
@@ -185,7 +193,7 @@ ControlOp SearchCondCheckWalker::access(const QueryNode::Ptr &query_node,
if (query_node->op() == QueryNodeOp::Q_IS_NULL ||
query_node->op() == QueryNodeOp::Q_IS_NOT_NULL) {
if (forward_field->index_params() != nullptr) {
if (forward_field->has_invert_index()) {
add_invert_filter(query_rel_node.get());
} else {
add_forward_filter(query_rel_node.get(), field_name);
@@ -205,7 +213,7 @@ ControlOp SearchCondCheckWalker::access(const QueryNode::Ptr &query_node,
// invert index analysis, if field exists on both forward and index,
// as long as the cond conform to index cond criteria,
// it is regarded as index cond, not forward cond.
if (forward_field->index_params() != nullptr) {
if (forward_field->has_invert_index()) {
if (const auto ret = check_array_and_contain_compatible(
query_rel_node, forward_field, true);
ret != std::nullopt) {
@@ -371,7 +379,7 @@ tl::expected<void, std::string> SearchCondCheckWalker::array_length_func_check(
right_node->op_name());
}
if (arg0_schema->index_params() != nullptr) {
if (arg0_schema->has_invert_index()) {
if (!check_and_convert_value_type(DataType::UINT32, right_node)) {
return tl::make_unexpected(
"array_length right side only support integer, got " +
+43
View File
@@ -0,0 +1,43 @@
// Copyright 2025-present the zvec project
//
// 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.
#pragma once
#include <memory>
#include <string>
#include "db/index/column/fts_column/fts_query_ast.h"
namespace zvec::sqlengine {
struct FtsCondInfo {
using Ptr = std::shared_ptr<FtsCondInfo>;
FtsCondInfo() = default;
FtsCondInfo(std::string field_name, fts::FtsAstNodePtr ast)
: field_name(std::move(field_name)), fts_ast(std::move(ast)) {}
std::string to_string() const {
std::string str = field_name + " MATCH ";
if (fts_ast) {
str += fts_ast->text();
}
return str;
}
std::string field_name;
fts::FtsAstNodePtr fts_ast;
};
} // namespace zvec::sqlengine
+5
View File
@@ -196,6 +196,11 @@ std::string SelectInfo::to_string() {
str += "\n";
}
if (fts_cond_info_ != nullptr) {
str += "fts_cond: " + fts_cond_info_->to_string();
str += "\n";
}
return str;
}
+14
View File
@@ -17,6 +17,7 @@
#include <map>
#include <memory>
#include <vector>
#include "db/sqlengine/common/fts_cond_info.h"
#include "db/sqlengine/common/group_by.h"
#include "base_info.h"
#include "node.h"
@@ -69,6 +70,18 @@ class SelectInfo : public BaseInfo {
return group_by_;
}
void set_fts_cond_info(FtsCondInfo::Ptr value) {
fts_cond_info_ = std::move(value);
}
const FtsCondInfo::Ptr &fts_cond_info() const {
return fts_cond_info_;
}
bool has_fts_query() const {
return fts_cond_info_ != nullptr;
}
std::string to_string();
private:
@@ -82,6 +95,7 @@ class SelectInfo : public BaseInfo {
int limit_{-1};
bool include_vector_{false};
bool include_doc_id_{false};
FtsCondInfo::Ptr fts_cond_info_{nullptr};
};
} // namespace zvec::sqlengine
+10 -9
View File
@@ -17,7 +17,6 @@
#include <arrow/acero/exec_plan.h>
#include <arrow/table.h>
#include <zvec/ailego/logger/logger.h>
#include <zvec/db/config.h>
#include "db/sqlengine/planner/invert_search.h"
namespace zvec::sqlengine {
@@ -107,7 +106,8 @@ std::optional<bool> DocFilter::get_forward_bit(uint64_t id) const {
return std::nullopt;
}
std::optional<std::vector<uint64_t>> DocFilter::get_bf_by_keys_and_update() {
std::optional<std::vector<uint64_t>> DocFilter::get_bf_by_keys_and_update(
float ratio) {
auto meta = segment_->meta();
if (!meta) {
return std::nullopt;
@@ -117,9 +117,7 @@ std::optional<std::vector<uint64_t>> DocFilter::get_bf_by_keys_and_update() {
return std::nullopt;
}
size_t doc_count = meta->doc_count();
float brute_force_by_keys_ratio =
GlobalConfig::Instance().brute_force_by_keys_ratio();
uint64_t bf_by_keys_threshold = meta->doc_count() * brute_force_by_keys_ratio;
uint64_t bf_by_keys_threshold = static_cast<uint64_t>(doc_count * ratio);
// decide to use brute force by keys or not
if (size_t match_count = invert_result_->count();
@@ -128,13 +126,16 @@ std::optional<std::vector<uint64_t>> DocFilter::get_bf_by_keys_and_update() {
invert_result_->extract_ids(&ids);
invert_filter_.reset();
invert_result_.reset();
LOG_INFO("Use brute force by keys, doc_count[%zu] invert_result_count[%zu]",
doc_count, match_count);
LOG_INFO(
"Use brute force by keys, doc_count[%zu] invert_result_count[%zu] "
"ratio[%.4f]",
doc_count, match_count, ratio);
return std::vector<uint64_t>(ids.begin(), ids.end());
} else {
LOG_DEBUG(
"Not use brute force by keys, doc_count[%zu] invert_result_count[%zu]",
doc_count, match_count);
"Not use brute force by keys, doc_count[%zu] invert_result_count[%zu] "
"ratio[%.4f]",
doc_count, match_count, ratio);
}
return std::nullopt;
}
+5 -2
View File
@@ -44,8 +44,11 @@ class DocFilter : public IndexFilter {
bool is_filtered(uint64_t id) const override;
//! get brute force by keys and clear `invert_filter_` if suitable
std::optional<std::vector<uint64_t>> get_bf_by_keys_and_update();
//! When invert cardinality <= \p ratio * doc_count, extract the ids and
//! clear invert_filter_ so the caller drives evaluation by ids instead of
//! bitmap-checking. Ratio is per-caller (vector vs FTS use different
//! GlobalConfig knobs) because per-candidate cost differs.
std::optional<std::vector<uint64_t>> get_bf_by_keys_and_update(float ratio);
bool empty() const;
+143
View File
@@ -0,0 +1,143 @@
// Copyright 2025-present the zvec project
//
// 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.
#include "db/sqlengine/planner/fts_recall_node.h"
#include <arrow/api.h>
#include <zvec/ailego/logger/logger.h>
#include <zvec/db/config.h>
#include "db/sqlengine/common/util.h"
namespace cp = arrow::compute;
namespace zvec::sqlengine {
FtsRecallNode::FtsRecallNode(Segment::Ptr segment, QueryInfo::Ptr query_info,
DocFilter::Ptr doc_filter, int batch_size)
: segment_(std::move(segment)),
query_info_(std::move(query_info)),
doc_filter_(std::move(doc_filter)),
fetched_columns_(query_info_->get_all_fetched_scalar_field_names()),
batch_size_(batch_size) {
auto table = segment_->fetch(fetched_columns_, std::vector<int>{});
// Append BM25 score column so downstream fill_doc_score() surfaces it to
// the Python Doc.score, matching the vector-recall path.
schema_ = Util::append_field(*table->schema(), kFieldScore, arrow::float32());
}
arrow::AsyncGenerator<std::optional<cp::ExecBatch>> FtsRecallNode::gen() {
auto state_ptr = std::make_shared<State>();
return [self = shared_from_this(), state_ptr = std::move(state_ptr)]()
-> arrow::Future<std::optional<cp::ExecBatch>> {
auto &state = *state_ptr;
if (!state.iter_) {
auto fts_ret = self->prepare();
if (!fts_ret) {
return arrow::Future<std::optional<cp::ExecBatch>>::MakeFinished(
arrow::Status::ExecutionError("prepare fts failed:",
fts_ret.error().c_str()));
}
state.fts_result_ = fts_ret.value();
state.iter_ = state.fts_result_->create_iterator();
}
if (!state.iter_->valid()) {
return arrow::Future<std::optional<cp::ExecBatch>>::MakeFinished(
std::nullopt);
}
std::vector<int> indices;
indices.reserve(self->batch_size_);
arrow::FloatBuilder score_builder;
for (int i = 0; state.iter_->valid() && i < self->batch_size_;
i++, state.iter_->next()) {
indices.push_back(state.iter_->doc_id());
auto s = score_builder.Append(state.iter_->score());
if (!s.ok()) {
return arrow::Future<std::optional<cp::ExecBatch>>::MakeFinished(
arrow::Status::ExecutionError("score builder append failed:",
s.ToString()));
}
}
if (indices.empty()) {
return arrow::Future<std::optional<cp::ExecBatch>>::MakeFinished(
std::nullopt);
}
auto table = self->segment_->fetch(self->fetched_columns_, indices);
if (!table) {
return arrow::Future<std::optional<cp::ExecBatch>>::MakeFinished(
arrow::Status::UnknownError("fetch table failed"));
}
auto batch = table->CombineChunksToBatch();
if (!batch.ok()) {
return arrow::Future<std::optional<cp::ExecBatch>>::MakeFinished(
arrow::Status::ExecutionError("combine chunks to batch failed:",
batch.status().ToString()));
}
auto score_array = score_builder.Finish();
if (!score_array.ok()) {
return arrow::Future<std::optional<cp::ExecBatch>>::MakeFinished(
arrow::Status::ExecutionError("finish score builder failed:",
score_array.status().ToString()));
}
auto record_batch = std::move(batch.ValueUnsafe());
auto with_score =
record_batch->AddColumn(record_batch->num_columns(), kFieldScore,
score_array.MoveValueUnsafe());
if (!with_score.ok()) {
return arrow::Future<std::optional<cp::ExecBatch>>::MakeFinished(
arrow::Status::ExecutionError("add score column failed:",
with_score.status().ToString()));
}
cp::ExecBatch exec_batch(*with_score.ValueUnsafe());
return arrow::Future<std::optional<cp::ExecBatch>>::MakeFinished(
std::move(exec_batch));
};
}
Result<FtsIndexResults::Ptr> FtsRecallNode::prepare() {
auto filter_status = doc_filter_->compute_filter();
if (!filter_status.ok()) {
return tl::make_unexpected(filter_status);
}
const auto &fts_cond = query_info_->fts_cond_info();
if (!fts_cond) {
return tl::make_unexpected(
Status::InvalidArgument("FtsRecallNode: no fts_cond_info in query"));
}
fts::FtsQueryParams params;
params.topk = query_info_->query_topn();
// Brute-force path: get_bf_by_keys_and_update also clears invert_filter_
// when it returns ids, so the filter set below won't double-check them.
if (auto bf_keys = doc_filter_->get_bf_by_keys_and_update(
GlobalConfig::Instance().fts_brute_force_by_keys_ratio())) {
params.candidate_ids = std::move(bf_keys.value());
}
// Push down remaining filters (delete / forward) so filtered docs are
// skipped during scoring and we still return up to topk results.
params.filter = doc_filter_->empty() ? nullptr : doc_filter_;
auto results =
segment_->fts_search(fts_cond->field_name, *fts_cond->fts_ast, params);
if (!results) {
return tl::make_unexpected(results.error());
}
return std::make_shared<FtsIndexResults>(std::move(results.value()));
}
} // namespace zvec::sqlengine
@@ -0,0 +1,59 @@
// Copyright 2025-present the zvec project
//
// 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.
#pragma once
#include <memory>
#include <arrow/acero/api.h>
#include <arrow/api.h>
#include "db/index/column/common/index_results.h"
#include "db/index/column/fts_column/fts_index_results.h"
#include "db/index/segment/segment.h"
#include "db/sqlengine/analyzer/query_info.h"
#include "db/sqlengine/planner/doc_filter.h"
namespace cp = arrow::compute;
namespace zvec::sqlengine {
class FtsRecallNode : public std::enable_shared_from_this<FtsRecallNode> {
public:
FtsRecallNode(Segment::Ptr segment, QueryInfo::Ptr query_info,
DocFilter::Ptr doc_filter, int batch_size);
//! get schema
std::shared_ptr<arrow::Schema> schema() const {
return schema_;
}
arrow::AsyncGenerator<std::optional<cp::ExecBatch>> gen();
private:
Result<FtsIndexResults::Ptr> prepare();
private:
struct State {
FtsIndexResults::Ptr fts_result_;
IndexResults::IteratorUPtr iter_;
};
Segment::Ptr segment_;
QueryInfo::Ptr query_info_;
DocFilter::Ptr doc_filter_;
const std::vector<std::string> &fetched_columns_;
int batch_size_;
std::shared_ptr<arrow::Schema> schema_;
};
} // namespace zvec::sqlengine
+51 -8
View File
@@ -28,6 +28,7 @@
#include "db/sqlengine/analyzer/query_info.h"
#include "db/sqlengine/analyzer/query_node.h"
#include "db/sqlengine/common/util.h"
#include "db/sqlengine/planner/fts_recall_node.h"
#include "db/sqlengine/planner/invert_recall_node.h"
#include "db/sqlengine/planner/ops/check_not_filtered_op.h"
#include "db/sqlengine/planner/ops/contain_op.h"
@@ -356,6 +357,7 @@ Result<PlanInfo::Ptr> QueryPlanner::make_physical_plan(
query_info->to_string().c_str());
int topn = query_info->query_topn();
auto vector_cond = query_info->vector_cond_info();
auto fts_cond = query_info->fts_cond_info();
bool has_group_by = query_info->group_by() != nullptr;
// optimize plan by instrument query info condition, eg adjust invert cond
@@ -406,6 +408,9 @@ Result<PlanInfo::Ptr> QueryPlanner::make_physical_plan(
if (query_info->vector_cond_info()) {
seg_plan = vector_scan(segment, std::move(segment_query_info),
std::move(forward_filter), single_stage_search);
} else if (query_info->fts_cond_info()) {
seg_plan = fts_scan(segment, std::move(segment_query_info),
std::move(forward_filter), single_stage_search);
} else if (query_info->invert_cond()) {
seg_plan = invert_scan(segment, std::move(segment_query_info),
std::move(forward_filter));
@@ -439,6 +444,14 @@ Result<PlanInfo::Ptr> QueryPlanner::make_physical_plan(
kFieldScore, vector_cond->is_reverse_sort()
? cp::SortOrder::Descending
: cp::SortOrder::Ascending}}}}};
} else if (fts_cond) {
// FTS uses BM25 where higher score = more relevant. Per-segment results
// are already in descending score order; merging multiple segments
// requires a global re-sort to keep the contract.
node = ac::Declaration{"order_by",
{std::move(node)},
ac::OrderByNodeOptions{cp::Ordering{{cp::SortKey{
kFieldScore, cp::SortOrder::Descending}}}}};
}
// group by need to collect all docs
@@ -515,14 +528,14 @@ Result<PlanInfo::Ptr> QueryPlanner::forward_scan(
return std::make_shared<PlanInfo>(std::move(node), std::move(schema));
}
Result<PlanInfo::Ptr> QueryPlanner::vector_scan(
Segment::Ptr seg, QueryInfo::Ptr query_info,
std::unique_ptr<arrow::compute::Expression> forward_filter,
DocFilter::Ptr QueryPlanner::build_doc_filter(
const Segment::Ptr &seg, const QueryInfo::Ptr &query_info,
std::unique_ptr<arrow::compute::Expression> &forward_filter,
bool single_stage_search) {
std::unique_ptr<ac::Declaration> forward_filter_plan;
// if single stage search is not enabled, first run acero plan to get
// forward bitmap, then filter during vector search. otherwise, filter
// forward during forward search.
// forward bitmap, then filter during search. otherwise, filter forward
// during search.
if (forward_filter && !single_stage_search) {
ac::RecordBatchReaderSourceNodeOptions source_options{
seg->scan(query_info->get_forward_filter_field_names())};
@@ -536,9 +549,17 @@ Result<PlanInfo::Ptr> QueryPlanner::vector_scan(
})});
forward_filter.reset();
}
auto doc_filter = std::make_shared<DocFilter>(seg, query_info,
std::move(forward_filter_plan),
std::move(forward_filter));
return std::make_shared<DocFilter>(seg, query_info,
std::move(forward_filter_plan),
std::move(forward_filter));
}
Result<PlanInfo::Ptr> QueryPlanner::vector_scan(
Segment::Ptr seg, QueryInfo::Ptr query_info,
std::unique_ptr<arrow::compute::Expression> forward_filter,
bool single_stage_search) {
auto doc_filter =
build_doc_filter(seg, query_info, forward_filter, single_stage_search);
int topn = query_info->query_topn();
int batch_size = get_batch_size(*query_info, false);
@@ -616,6 +637,28 @@ Result<PlanInfo::Ptr> QueryPlanner::invert_scan(
return std::make_shared<PlanInfo>(std::move(node), std::move(schema));
}
Result<PlanInfo::Ptr> QueryPlanner::fts_scan(
Segment::Ptr seg, QueryInfo::Ptr query_info,
std::unique_ptr<arrow::compute::Expression> forward_filter,
bool single_stage_search) {
auto doc_filter =
build_doc_filter(seg, query_info, forward_filter, single_stage_search);
auto topn = query_info->query_topn();
int batch_size = get_batch_size(*query_info, false);
auto recall_node = std::make_shared<FtsRecallNode>(
std::move(seg), std::move(query_info), std::move(doc_filter), batch_size);
auto source_node_options =
arrow::acero::SourceNodeOptions{recall_node->schema(), recall_node->gen(),
arrow::compute::Ordering::Implicit()};
ac::Declaration node{"source", source_node_options};
node = ac::Declaration{
"fetch", {std::move(node)}, ac::FetchNodeOptions{0, topn}};
return std::make_shared<PlanInfo>(std::move(node), recall_node->schema());
}
int QueryPlanner::get_batch_size(const QueryInfo &info, bool has_later_filter) {
// ref https://arrow.apache.org/docs/developers/cpp/acero.html#batch-size
if (!info.query_orderbys().empty() || has_later_filter) {
+10
View File
@@ -22,6 +22,7 @@
#include <zvec/db/status.h>
#include "db/index/segment/segment.h"
#include "db/sqlengine/analyzer/query_info.h"
#include "db/sqlengine/planner/doc_filter.h"
#include "plan_info.h"
namespace zvec::sqlengine {
@@ -59,6 +60,15 @@ class QueryPlanner {
Result<PlanInfo::Ptr> forward_scan(
Segment::Ptr seg, QueryInfo::Ptr query_info,
std::unique_ptr<arrow::compute::Expression> forward_filter);
Result<PlanInfo::Ptr> fts_scan(
Segment::Ptr seg, QueryInfo::Ptr query_info,
std::unique_ptr<arrow::compute::Expression> forward_filter,
bool single_stage_search);
static DocFilter::Ptr build_doc_filter(
const Segment::Ptr &seg, const QueryInfo::Ptr &query_info,
std::unique_ptr<arrow::compute::Expression> &forward_filter,
bool single_stage_search);
static int get_batch_size(const QueryInfo &info, bool has_later_filter);
@@ -21,6 +21,7 @@
#include <zvec/ailego/logger/logger.h>
#include <zvec/ailego/pattern/expected.hpp>
#include <zvec/core/framework/index_meta.h>
#include <zvec/db/config.h>
#include <zvec/db/index_params.h>
#include <zvec/db/schema.h>
#include <zvec/db/type.h>
@@ -159,7 +160,8 @@ Result<IndexResults::Ptr> VectorRecallNode::prepare() {
query_params.data_type = vector_cond_->vector_schema()->data_type();
query_params.dimension = vector_cond_->dimension();
query_params.query_params = vector_cond_->query_params();
auto brute_force_keys = doc_filter_->get_bf_by_keys_and_update();
auto brute_force_keys = doc_filter_->get_bf_by_keys_and_update(
GlobalConfig::Instance().brute_force_by_keys_ratio());
if (brute_force_keys) {
query_params.bf_pks.emplace_back(std::move(brute_force_keys.value()));
}
+129 -1
View File
@@ -14,11 +14,17 @@
#include "db/sqlengine/sqlengine_impl.h"
#include <unordered_map>
#include <zvec/ailego/internal/platform.h>
#include <zvec/ailego/logger/logger.h>
#include <zvec/db/doc.h>
#include <zvec/db/index_params.h>
#include <zvec/db/type.h>
#include "db/common/constants.h"
#include "db/index/column/fts_column/fts_ast_rewriter.h"
#include "db/index/column/fts_column/fts_pipeline.h"
#include "db/index/column/fts_column/fts_query_ast.h"
#include "db/sqlengine/analyzer/query_analyzer.h"
#include "db/sqlengine/parser/select_info.h"
#include "db/sqlengine/parser/sql_info_helper.h"
#include "db/sqlengine/parser/zvec_parser.h"
#include "db/sqlengine/planner/op_register.h"
@@ -116,6 +122,113 @@ Result<GroupResults> SQLEngineImpl::execute_group_by(
return fill_group_by_result(*query_info.value(), reader.value().get());
}
Result<FtsCondInfo::Ptr> SQLEngineImpl::parse_fts_query(
CollectionSchema::Ptr collection, const std::string &field_name,
const FtsClause &fts, const QueryParams::Ptr &query_params) {
// Exactly one of query_string_ or match_string_ must be provided.
bool has_query = !fts.query_string_.empty();
bool has_match_string = !fts.match_string_.empty();
if (has_query == has_match_string) {
return tl::make_unexpected(Status::InvalidArgument(
"Exactly one of query_string or match_string must be provided"));
}
auto *fts_query_param = dynamic_cast<FtsQueryParams *>(query_params.get());
// Determine default operator once, shared by both query_string and
// match_string paths. Accept "and"/"or" case-insensitively, empty means OR;
// any other value is a user error and must be reported, not silently
// downgraded to OR. strcasecmp is mapped to _stricmp on MSVC by platform.h.
fts::FtsDefaultOperator default_op = fts::FtsDefaultOperator::OR;
if (fts_query_param) {
const auto &op_str = fts_query_param->default_operator();
if (op_str.empty() || strcasecmp(op_str.c_str(), "or") == 0) {
default_op = fts::FtsDefaultOperator::OR;
} else if (strcasecmp(op_str.c_str(), "and") == 0) {
default_op = fts::FtsDefaultOperator::AND;
} else {
return tl::make_unexpected(Status::InvalidArgument(
"FTS default_operator must be empty, 'and' or 'or' (case-insensitive)"
", got: ",
op_str));
}
}
// Tokenizer pipeline is required by both branches: query_string needs it to
// tokenize phrase contents and bare terms, match_string needs it to split
// the natural-language input. Resolve once and share.
auto *field_schema = collection->get_field(field_name);
if (!field_schema) {
return tl::make_unexpected(
Status::InvalidArgument("FTS field not found: ", field_name));
}
auto fts_idx_param =
std::dynamic_pointer_cast<FtsIndexParams>(field_schema->index_params());
if (!fts_idx_param) {
return tl::make_unexpected(Status::InvalidArgument(
"FTS field has no FtsIndexParams: ", field_name));
}
auto pipeline_result = detail::AcquireFtsPipeline(*fts_idx_param);
if (!pipeline_result.has_value()) {
return tl::make_unexpected(Status::InternalError(
"Failed to create tokenizer pipeline for field: ", field_name, " ",
pipeline_result.error().message()));
}
auto &pipeline = pipeline_result.value();
fts::FtsAstNodePtr ast;
if (has_query) {
// Structured query expression: parse via ANTLR grammar; phrase/term
// bodies are tokenized through the same pipeline used at index time.
fts::FtsQueryParser fts_parser;
ast = fts_parser.parse(fts.query_string_, pipeline, default_op);
if (!ast) {
LOG_ERROR("FTS query parse failed: %s", fts_parser.err_msg().c_str());
return tl::make_unexpected(Status::InvalidArgument(
"FTS query parse failed: ", fts_parser.err_msg()));
}
} else {
// Natural language match_string: tokenize and combine with default_op.
auto tokens = pipeline->process(fts.match_string_);
if (tokens.empty()) {
// Analyzer dropped everything → zero-doc query, not an error.
return std::make_shared<FtsCondInfo>(field_name,
std::make_unique<fts::EmptyNode>());
}
if (tokens.size() == 1) {
ast = std::make_unique<fts::TermNode>(std::move(tokens[0].text));
} else {
if (default_op == fts::FtsDefaultOperator::AND) {
auto and_node = std::make_unique<fts::AndNode>();
for (auto &token : tokens) {
and_node->children.push_back(
std::make_unique<fts::TermNode>(std::move(token.text)));
}
ast = std::move(and_node);
} else {
auto or_node = std::make_unique<fts::OrNode>();
for (auto &token : tokens) {
or_node->children.push_back(
std::make_unique<fts::TermNode>(std::move(token.text)));
}
ast = std::move(or_node);
}
}
}
// Structural rewrite: dedup repeated terms (collapsed into a single node
// with summed boost), flatten same-type composites for better WAND pruning,
// propagate EmptyNode, and detect must/must_not contradictions. The pre-
// rewrite AST is logged at DEBUG so the transform is auditable. LOG_DEBUG
// is gated by the configured log level, so ast->text() is only built when
// debug logging is enabled.
LOG_DEBUG("FTS AST before rewrite: %s", ast ? ast->text().c_str() : "<null>");
fts::simplify(ast);
LOG_DEBUG("FTS AST after rewrite : %s", ast ? ast->text().c_str() : "<null>");
return std::make_shared<FtsCondInfo>(field_name, std::move(ast));
}
Result<QueryInfo::Ptr> SQLEngineImpl::parse_sql_info(
const CollectionSchema &schema, const SQLInfo::Ptr &sql_info) {
profiler_->open_stage("analyze stage");
@@ -168,6 +281,21 @@ Result<QueryInfo::Ptr> SQLEngineImpl::parse_request(
return tl::make_unexpected(Status::InvalidArgument(
"Convert message to SQL info failed: ", err_msg));
}
// If the request carries an FTS query, parse it and attach to SelectInfo
// so that query_analyzer can propagate it to QueryInfo.
if (const auto *fts_clause = request.target_.get_fts_clause()) {
auto fts_result =
parse_fts_query(collection, request.target_.field_name_, *fts_clause,
request.target_.query_params_);
if (!fts_result) {
return tl::make_unexpected(fts_result.error());
}
auto select_info =
std::dynamic_pointer_cast<SelectInfo>(sql_info->base_info());
select_info->set_fts_cond_info(std::move(fts_result.value()));
}
LOG_DEBUG("Sql info is %s", sql_info->to_string().c_str());
return parse_sql_info(*collection, std::move(sql_info));
}
@@ -573,4 +701,4 @@ Result<GroupResults> SQLEngineImpl::fill_group_by_result(
return group_results;
}
} // namespace zvec::sqlengine
} // namespace zvec::sqlengine
+7
View File
@@ -22,6 +22,8 @@
#include <zvec/db/schema.h>
#include "analyzer/query_info.h"
#include "common/group_by.h"
#include "db/index/column/fts_column/fts_query_ast.h"
#include "db/index/column/fts_column/parser/fts_query_parser.h"
#include "db/sqlengine/common/util.h"
#include "db/sqlengine/parser/sql_info.h"
#include "db/sqlengine/sqlengine.h"
@@ -67,6 +69,11 @@ class SQLEngineImpl : public SQLEngine {
Result<GroupResults> fill_group_by_result(const QueryInfo &query_info,
arrow::RecordBatchReader *reader);
//! Parse FTS query into a FtsCondInfo (AST + field name).
Result<FtsCondInfo::Ptr> parse_fts_query(
CollectionSchema::Ptr collection, const std::string &field_name,
const FtsClause &fts, const QueryParams::Ptr &query_params);
private:
zvec::Profiler::Ptr profiler_;
std::string execution_time_info_{};