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
+1
View File
@@ -25,6 +25,7 @@ foreach(CC_SRCS ${ALL_TEST_SRCS})
LIBS zvec_common
zvec_proto
zvec_sqlengine
zvec_db
zvec_ailego
core_metric
core_utility
@@ -0,0 +1,233 @@
// 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 <memory>
#include <string>
#include <vector>
#include <gtest/gtest.h>
#include "db/common/file_helper.h"
#include "db/index/common/version_manager.h"
#include "db/index/segment/segment.h"
#include "db/sqlengine/sqlengine.h"
#include "zvec/db/doc.h"
#include "zvec/db/index_params.h"
#include "zvec/db/schema.h"
#include "zvec/db/type.h"
namespace zvec::sqlengine {
// Multi-segment FTS recall regression:
//
// The planner's SegmentNode drains per-segment readers in LIFO order, so the
// per-segment BM25 ordering is *not* preserved across the merged stream. The
// planner must therefore add a global order_by on the score column for FTS,
// mirroring what it already does for vector queries.
//
// To make the regression observable we engineer the two segments so that
// * segments_[0] (read LAST) holds the globally highest-scoring doc, and
// * segments_[1] (read FIRST) holds many low-scoring docs.
//
// Per-segment BM25 stats (rare term -> high IDF in segments_[0], common term
// -> low IDF in segments_[1]) guarantee s0_0 outranks every doc in
// segments_[1]. Without the global sort the first doc in the merged stream is
// the much lower-scoring s1_*, which breaks both the descending invariant and
// topk truncation.
class FtsMultiSegmentTest : public ::testing::Test {
protected:
static void SetUpTestSuite() {
FileHelper::RemoveDirectory(root_path_);
FileHelper::CreateDirectory(root_path_);
build_schema();
// segments_[0]: only one doc contains "apple" but with very high TF and
// very low df (rare term) -> high BM25.
auto seg0 = create_segment(root_path_ + "/seg0", "fts_ms_seg0");
ASSERT_NE(seg0, nullptr);
insert_docs(seg0, /*pk_prefix=*/"s0_",
{
{"apple apple apple apple apple"}, // doc 0: TF=5, df=1
{"banana"},
{"cherry"},
{"date"},
{"elderberry"},
});
// segments_[1]: all docs contain "apple" (df=N) -> very low IDF -> low
// BM25 across the board.
auto seg1 = create_segment(root_path_ + "/seg1", "fts_ms_seg1");
ASSERT_NE(seg1, nullptr);
insert_docs(seg1, /*pk_prefix=*/"s1_",
{
{"apple banana"},
{"apple cherry"},
{"apple date"},
{"apple elderberry"},
});
segments_.push_back(seg0);
segments_.push_back(seg1);
engine_ = SQLEngine::create(std::make_shared<Profiler>());
}
static void TearDownTestSuite() {
segments_.clear();
engine_.reset();
schema_.reset();
FileHelper::RemoveDirectory(root_path_);
}
Result<DocPtrList> fts_search(const std::string &query_string,
int topk = 10) {
SearchQuery vq;
vq.topk_ = topk;
vq.target_.field_name_ = "content";
FtsClause fts;
fts.query_string_ = query_string;
vq.target_.clause_ = fts;
return engine_->execute(schema_, vq, segments_);
}
private:
static void build_schema() {
auto fts_params = std::make_shared<FtsIndexParams>(
"whitespace", std::vector<std::string>{"lowercase"}, "");
schema_ = std::make_shared<CollectionSchema>(
"fts_multi_segment_test",
std::vector<FieldSchema::Ptr>{
std::make_shared<FieldSchema>("content", DataType::STRING, false,
fts_params),
// Dummy vector field keeps the schema parity with the single-
// segment FTS fixture so the analyzer/planner paths behave the
// same.
std::make_shared<FieldSchema>(
"vec", DataType::VECTOR_FP32, 4, false,
std::make_shared<FlatIndexParams>(MetricType::L2)),
});
}
static Segment::Ptr create_segment(const std::string &seg_path,
const std::string &name) {
FileHelper::CreateDirectory(seg_path);
auto segment_meta = std::make_shared<SegmentMeta>();
segment_meta->set_id(0);
auto id_map = IDMap::CreateAndOpen(name, seg_path + "/id_map", true, false);
auto delete_store = std::make_shared<DeleteStore>(name);
Version v1;
v1.set_schema(*schema_);
std::string v_path = seg_path + "/manifest";
FileHelper::CreateDirectory(v_path);
auto vm = VersionManager::Create(v_path, v1);
if (!vm.has_value()) {
return nullptr;
}
BlockMeta mem_block;
mem_block.id_ = 0;
mem_block.type_ = BlockType::SCALAR;
mem_block.min_doc_id_ = 0;
mem_block.max_doc_id_ = 0;
mem_block.doc_count_ = 0;
segment_meta->set_writing_forward_block(mem_block);
SegmentOptions options;
options.read_only_ = false;
options.enable_mmap_ = true;
options.max_buffer_size_ = 256 * 1024;
auto result = Segment::CreateAndOpen(seg_path, *schema_, 0, 0, id_map,
delete_store, vm.value(), options);
if (!result) {
return nullptr;
}
return result.value();
}
struct Entry {
std::string content;
};
static void insert_docs(const Segment::Ptr &segment,
const std::string &pk_prefix,
const std::vector<Entry> &entries) {
for (size_t i = 0; i < entries.size(); ++i) {
Doc doc;
doc.set_pk(pk_prefix + std::to_string(i));
doc.set_doc_id(i);
doc.set<std::string>("content", entries[i].content);
auto status = segment->Insert(doc);
ASSERT_TRUE(status.ok())
<< pk_prefix << i << " insert failed: " << status.c_str();
}
}
protected:
static inline std::string root_path_ = "./fts_multi_segment_test_collection";
static inline CollectionSchema::Ptr schema_;
static inline std::vector<Segment::Ptr> segments_;
static inline SQLEngine::Ptr engine_;
};
// The merged stream from all segments must be strictly non-increasing in
// score. Without the global order_by, segments_[1]'s low-scoring docs would
// appear before segments_[0]'s much higher-scoring s0_0, violating BM25 rank.
TEST_F(FtsMultiSegmentTest, ScoreDescendingAcrossSegments) {
auto result = fts_search("apple");
ASSERT_TRUE(result.has_value()) << result.error().c_str();
// s0_0 + s1_0..s1_3 = 5 matches.
ASSERT_EQ(result->size(), 5u);
// s0_0 (TF=5, rare term in seg0) dominates the 4 low-IDF s1_* docs.
EXPECT_EQ((*result)[0]->pk(), "s0_0");
EXPECT_GT((*result)[0]->score(), (*result)[1]->score());
for (size_t i = 0; i + 1 < result->size(); ++i) {
EXPECT_GE((*result)[i]->score(), (*result)[i + 1]->score())
<< "score not descending at rank " << i << ": " << (*result)[i]->pk()
<< "=" << (*result)[i]->score() << " vs " << (*result)[i + 1]->pk()
<< "=" << (*result)[i + 1]->score();
}
}
// topk must cut against the globally-sorted stream. Without the fix the
// first batch surfaced from SegmentNode comes from segments_[1] (LIFO read),
// so topk=1 would silently drop the highest-scoring s0_0.
TEST_F(FtsMultiSegmentTest, TopkPicksGloballyHighestScore) {
auto result = fts_search("apple", /*topk=*/1);
ASSERT_TRUE(result.has_value()) << result.error().c_str();
ASSERT_EQ(result->size(), 1u);
EXPECT_EQ((*result)[0]->pk(), "s0_0");
}
// Sanity: a cross-segment OR query still returns the union of matches and
// stays descending across the segment boundary.
TEST_F(FtsMultiSegmentTest, CrossSegmentUnionDescending) {
// apple: 5 docs (s0_0, s1_0..s1_3). banana: s0_1 (seg0), s1_0 (seg1).
// OR-union: {s0_0, s0_1, s1_0, s1_1, s1_2, s1_3} = 6 docs.
auto result = fts_search("apple banana");
ASSERT_TRUE(result.has_value()) << result.error().c_str();
ASSERT_EQ(result->size(), 6u);
for (size_t i = 0; i + 1 < result->size(); ++i) {
EXPECT_GE((*result)[i]->score(), (*result)[i + 1]->score())
<< "score not descending at rank " << i;
}
}
} // namespace zvec::sqlengine
+875
View File
@@ -0,0 +1,875 @@
// 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 <gtest/gtest.h>
#include "db/index/column/fts_column/fts_query_ast.h"
#include "db/index/column/fts_column/fts_types.h"
#include "db/index/column/fts_column/parser/fts_query_parser.h"
#include "db/index/column/fts_column/tokenizer/tokenizer_factory.h"
namespace zvec::fts {
// ============================================================
// Test fixture
// ============================================================
class FtsParserTest : public ::testing::Test {
protected:
void SetUp() override {
// Standard tokenizer + lowercase filter: ASCII tests behave the same as
// the previous whitespace split (alnum runs become tokens, delimiters
// get dropped) while CJK tests can exercise the per-character tokens
// standard produces from non-alnum bytes.
FtsIndexParams params;
params.tokenizer_name = "standard";
params.filters = {"lowercase"};
pipeline_ = TokenizerFactory::create(params);
ASSERT_NE(pipeline_, nullptr);
}
FtsAstNodePtr parse(const std::string &query) {
return parser_.parse(query, pipeline_);
}
// Overload for tests that need to specify the default operator explicitly.
FtsAstNodePtr parse(const std::string &query, FtsDefaultOperator default_op) {
return parser_.parse(query, pipeline_, default_op);
}
const std::string &err_msg() {
return parser_.err_msg();
}
// Helpers for type-safe downcasting
static const TermNode &as_term(const FtsAstNode &node) {
EXPECT_EQ(node.type(), FtsNodeType::TERM);
return static_cast<const TermNode &>(node);
}
static const PhraseNode &as_phrase(const FtsAstNode &node) {
EXPECT_EQ(node.type(), FtsNodeType::PHRASE);
return static_cast<const PhraseNode &>(node);
}
static const AndNode &as_and(const FtsAstNode &node) {
EXPECT_EQ(node.type(), FtsNodeType::AND);
return static_cast<const AndNode &>(node);
}
static const OrNode &as_or(const FtsAstNode &node) {
EXPECT_EQ(node.type(), FtsNodeType::OR);
return static_cast<const OrNode &>(node);
}
private:
FtsQueryParser parser_;
TokenizerPipelinePtr pipeline_;
};
// ============================================================
// Single term
// ============================================================
TEST_F(FtsParserTest, SingleTerm) {
auto ast = parse("vector");
ASSERT_NE(ast, nullptr);
ASSERT_EQ(ast->type(), FtsNodeType::TERM);
const auto &term = as_term(*ast);
EXPECT_EQ(term.term, "vector");
EXPECT_FALSE(term.must);
EXPECT_FALSE(term.must_not);
}
TEST_F(FtsParserTest, SingleTermNumeric) {
auto ast = parse("2024");
ASSERT_NE(ast, nullptr);
ASSERT_EQ(ast->type(), FtsNodeType::TERM);
EXPECT_EQ(as_term(*ast).term, "2024");
}
TEST_F(FtsParserTest, SingleTermWithHyphen) {
// The lexer's REGULAR_ID rule keeps hyphenated text as one token, but the
// standard tokenizer on the parser side splits non-alphanumerics. With the
// default OR operator the term decomposes into Or[full, text] so query
// segmentation matches the index segmentation.
auto ast = parse("full-text");
ASSERT_NE(ast, nullptr);
ASSERT_EQ(ast->type(), FtsNodeType::OR);
const auto &or_node = as_or(*ast);
ASSERT_EQ(or_node.children.size(), 2u);
EXPECT_EQ(as_term(*or_node.children[0]).term, "full");
EXPECT_EQ(as_term(*or_node.children[1]).term, "text");
}
// ============================================================
// Must (+) and must_not (-/NOT) modifiers
// ============================================================
TEST_F(FtsParserTest, MustModifier) {
auto ast = parse("+vector");
ASSERT_NE(ast, nullptr);
const auto &term = as_term(*ast);
EXPECT_EQ(term.term, "vector");
EXPECT_TRUE(term.must);
EXPECT_FALSE(term.must_not);
}
TEST_F(FtsParserTest, MustNotModifierMinus) {
// "-slow" is lexed as a single REGULAR_ID token (hyphen is part of the id).
// To express must_not, use a space: "- slow" -> MINUS_SIGN + REGULAR_ID.
auto ast = parse("- slow");
ASSERT_NE(ast, nullptr);
const auto &term = as_term(*ast);
EXPECT_EQ(term.term, "slow");
EXPECT_FALSE(term.must);
EXPECT_TRUE(term.must_not);
}
TEST_F(FtsParserTest, MustNotModifierMinusNoSpace) {
// "-slow" without space: FtsLexer treats '-' as MINUS_SIGN modifier,
// so "-slow" is parsed as must_not:slow (same as "- slow").
auto ast = parse("-slow");
ASSERT_NE(ast, nullptr);
ASSERT_EQ(ast->type(), FtsNodeType::TERM);
EXPECT_EQ(as_term(*ast).term, "slow");
EXPECT_TRUE(as_term(*ast).must_not);
}
TEST_F(FtsParserTest, MustNotModifierNot) {
// NOT is now a strict binary operator (`a NOT b` <=> `a AND NOT b`).
// A leading `NOT a` is therefore a syntax error — there is no left-hand
// operand for NOT to subtract from.
auto ast = parse("NOT slow");
EXPECT_EQ(ast, nullptr);
EXPECT_FALSE(err_msg().empty());
}
// ============================================================
// Phrase query
// ============================================================
TEST_F(FtsParserTest, DoubleQuotedPhrase) {
auto ast = parse("\"exact phrase\"");
ASSERT_NE(ast, nullptr);
ASSERT_EQ(ast->type(), FtsNodeType::PHRASE);
const auto &phrase = as_phrase(*ast);
ASSERT_EQ(phrase.terms.size(), 2u);
EXPECT_EQ(phrase.terms[0], "exact");
EXPECT_EQ(phrase.terms[1], "phrase");
EXPECT_FALSE(phrase.must);
EXPECT_FALSE(phrase.must_not);
}
TEST_F(FtsParserTest, SingleQuotedPhrase) {
// Single-quoted strings are not supported as phrase queries (no SQUOTA_STRING
// token). The lexer's TERM rule absorbs "'hello", "world", and "'" as
// individual term tokens, so the query parses as an implicit OR of terms.
auto ast = parse("'hello world'");
ASSERT_NE(ast, nullptr);
ASSERT_EQ(ast->type(), FtsNodeType::OR);
}
TEST_F(FtsParserTest, PhraseWithMustModifier) {
auto ast = parse("+\"exact phrase\"");
ASSERT_NE(ast, nullptr);
const auto &phrase = as_phrase(*ast);
EXPECT_TRUE(phrase.must);
EXPECT_FALSE(phrase.must_not);
}
TEST_F(FtsParserTest, PhraseWithMustNotModifier) {
auto ast = parse("-\"bad phrase\"");
ASSERT_NE(ast, nullptr);
const auto &phrase = as_phrase(*ast);
EXPECT_FALSE(phrase.must);
EXPECT_TRUE(phrase.must_not);
}
TEST_F(FtsParserTest, PhraseWithThreeWords) {
auto ast = parse("\"one two three\"");
ASSERT_NE(ast, nullptr);
const auto &phrase = as_phrase(*ast);
ASSERT_EQ(phrase.terms.size(), 3u);
EXPECT_EQ(phrase.terms[0], "one");
EXPECT_EQ(phrase.terms[1], "two");
EXPECT_EQ(phrase.terms[2], "three");
}
// ============================================================
// Explicit OR
// ============================================================
TEST_F(FtsParserTest, ExplicitOr) {
auto ast = parse("cat OR dog");
ASSERT_NE(ast, nullptr);
ASSERT_EQ(ast->type(), FtsNodeType::OR);
const auto &or_node = as_or(*ast);
ASSERT_EQ(or_node.children.size(), 2u);
EXPECT_EQ(as_term(*or_node.children[0]).term, "cat");
EXPECT_EQ(as_term(*or_node.children[1]).term, "dog");
}
TEST_F(FtsParserTest, MultipleOr) {
auto ast = parse("a OR b OR c");
ASSERT_NE(ast, nullptr);
const auto &or_node = as_or(*ast);
ASSERT_EQ(or_node.children.size(), 3u);
}
// ============================================================
// Explicit AND
// ============================================================
TEST_F(FtsParserTest, ExplicitAnd) {
auto ast = parse("cat AND dog");
ASSERT_NE(ast, nullptr);
ASSERT_EQ(ast->type(), FtsNodeType::AND);
const auto &and_node = as_and(*ast);
ASSERT_EQ(and_node.children.size(), 2u);
EXPECT_EQ(as_term(*and_node.children[0]).term, "cat");
EXPECT_EQ(as_term(*and_node.children[1]).term, "dog");
}
TEST_F(FtsParserTest, MultipleAnd) {
auto ast = parse("a AND b AND c");
ASSERT_NE(ast, nullptr);
const auto &and_node = as_and(*ast);
ASSERT_EQ(and_node.children.size(), 3u);
}
// ============================================================
// Operator precedence: AND binds tighter than OR
// ============================================================
TEST_F(FtsParserTest, AndBindsTighterThanOr) {
// "a OR b AND c" should parse as "a OR (b AND c)"
auto ast = parse("a OR b AND c");
ASSERT_NE(ast, nullptr);
const auto &or_node = as_or(*ast);
ASSERT_EQ(or_node.children.size(), 2u);
// Left child: term "a"
EXPECT_EQ(as_term(*or_node.children[0]).term, "a");
// Right child: AND(b, c)
const auto &and_node = as_and(*or_node.children[1]);
ASSERT_EQ(and_node.children.size(), 2u);
EXPECT_EQ(as_term(*and_node.children[0]).term, "b");
EXPECT_EQ(as_term(*and_node.children[1]).term, "c");
}
// ============================================================
// Implicit adjacency (seqExpr / default operator)
// ============================================================
TEST_F(FtsParserTest, ImplicitAdjacency) {
// Adjacent terms without explicit operator: "a b" -> seqExpr -> OR(a, b)
auto ast = parse("a b");
ASSERT_NE(ast, nullptr);
ASSERT_EQ(ast->type(), FtsNodeType::OR);
const auto &or_node = as_or(*ast);
ASSERT_EQ(or_node.children.size(), 2u);
EXPECT_EQ(as_term(*or_node.children[0]).term, "a");
EXPECT_EQ(as_term(*or_node.children[1]).term, "b");
}
TEST_F(FtsParserTest, ImplicitAdjacencyThreeTerms) {
auto ast = parse("a b c");
ASSERT_NE(ast, nullptr);
const auto &or_node = as_or(*ast);
ASSERT_EQ(or_node.children.size(), 3u);
}
TEST_F(FtsParserTest, ImplicitAdjacencyWithModifiers) {
// "+a - b" -> seqExpr -> OR(must:a, must_not:b)
// Note: "-b" (no space) is lexed as a single REGULAR_ID; use "- b" for
// must_not.
auto ast = parse("+a - b");
ASSERT_NE(ast, nullptr);
const auto &or_node = as_or(*ast);
ASSERT_EQ(or_node.children.size(), 2u);
EXPECT_TRUE(as_term(*or_node.children[0]).must);
EXPECT_TRUE(as_term(*or_node.children[1]).must_not);
}
// ============================================================
// Parentheses grouping
// ============================================================
TEST_F(FtsParserTest, Parentheses) {
// "(a OR b) AND c"
auto ast = parse("(a OR b) AND c");
ASSERT_NE(ast, nullptr);
const auto &and_node = as_and(*ast);
ASSERT_EQ(and_node.children.size(), 2u);
// Left: OR(a, b)
const auto &or_node = as_or(*and_node.children[0]);
ASSERT_EQ(or_node.children.size(), 2u);
// Right: term c
EXPECT_EQ(as_term(*and_node.children[1]).term, "c");
}
TEST_F(FtsParserTest, NestedParentheses) {
auto ast = parse("((a OR b) AND c) OR d");
ASSERT_NE(ast, nullptr);
const auto &outer_or = as_or(*ast);
ASSERT_EQ(outer_or.children.size(), 2u);
EXPECT_EQ(as_term(*outer_or.children[1]).term, "d");
}
// ============================================================
// Mixed complex queries
// ============================================================
TEST_F(FtsParserTest, MixedTermAndPhrase) {
// "+vector - slow \"exact phrase\""
// Note: use "- slow" (with space) so MINUS_SIGN is a separate token.
auto ast = parse("+vector - slow \"exact phrase\"");
ASSERT_NE(ast, nullptr);
// Four adjacent items -> seqExpr -> OR(must:vector, must_not:slow, phrase)
// Actually: +vector and - slow and phrase are three unary nodes in seqExpr
const auto &or_node = as_or(*ast);
ASSERT_EQ(or_node.children.size(), 3u);
EXPECT_TRUE(as_term(*or_node.children[0]).must);
EXPECT_EQ(as_term(*or_node.children[0]).term, "vector");
EXPECT_TRUE(as_term(*or_node.children[1]).must_not);
EXPECT_EQ(as_term(*or_node.children[1]).term, "slow");
EXPECT_EQ(or_node.children[2]->type(), FtsNodeType::PHRASE);
}
TEST_F(FtsParserTest, AndWithPhrase) {
auto ast = parse("\"machine learning\" AND model");
ASSERT_NE(ast, nullptr);
const auto &and_node = as_and(*ast);
ASSERT_EQ(and_node.children.size(), 2u);
EXPECT_EQ(and_node.children[0]->type(), FtsNodeType::PHRASE);
EXPECT_EQ(as_term(*and_node.children[1]).term, "model");
}
TEST_F(FtsParserTest, ComplexBooleanQuery) {
// "a AND b OR c AND d" -> (a AND b) OR (c AND d)
auto ast = parse("a AND b OR c AND d");
ASSERT_NE(ast, nullptr);
const auto &or_node = as_or(*ast);
ASSERT_EQ(or_node.children.size(), 2u);
const auto &left_and = as_and(*or_node.children[0]);
ASSERT_EQ(left_and.children.size(), 2u);
const auto &right_and = as_and(*or_node.children[1]);
ASSERT_EQ(right_and.children.size(), 2u);
}
// ============================================================
// Single-child simplification (no unnecessary wrapping)
// ============================================================
TEST_F(FtsParserTest, SingleChildNotWrapped) {
// A single term should not be wrapped in an AndNode/OrNode
auto ast = parse("hello");
ASSERT_NE(ast, nullptr);
EXPECT_EQ(ast->type(), FtsNodeType::TERM);
}
TEST_F(FtsParserTest, SinglePhraseNotWrapped) {
auto ast = parse("\"hello world\"");
ASSERT_NE(ast, nullptr);
EXPECT_EQ(ast->type(), FtsNodeType::PHRASE);
}
// ============================================================
// Error cases
// ============================================================
TEST_F(FtsParserTest, EmptyQueryReturnsNull) {
auto ast = parse("");
EXPECT_EQ(ast, nullptr);
}
TEST_F(FtsParserTest, OnlyParenthesesReturnsNull) {
auto ast = parse("()");
EXPECT_EQ(ast, nullptr);
}
TEST_F(FtsParserTest, UnclosedPhraseParsesAsTerm) {
// An unclosed double-quote causes the DQUOTA_STRING rule to fail. The
// remaining characters are absorbed by the TERM catch-all rule, so the
// query parses as a single term rather than returning nullptr.
auto ast = parse("\"unclosed phrase");
ASSERT_NE(ast, nullptr);
}
TEST_F(FtsParserTest, UnclosedParenReturnsNull) {
auto ast = parse("(a OR b");
EXPECT_EQ(ast, nullptr);
}
// ============================================================
// Empty-AST cases: grammar valid, analyzer drops every term → EmptyNode.
// ============================================================
TEST_F(FtsParserTest, PunctuationOnlyReturnsEmpty) {
auto ast = parse("!!!");
ASSERT_NE(ast, nullptr);
EXPECT_EQ(ast->type(), FtsNodeType::EMPTY);
EXPECT_TRUE(err_msg().empty());
}
TEST_F(FtsParserTest, MultiplePunctuationTermsReturnsEmpty) {
auto ast = parse("!!! ??? ...");
ASSERT_NE(ast, nullptr);
EXPECT_EQ(ast->type(), FtsNodeType::EMPTY);
EXPECT_TRUE(err_msg().empty());
}
// ============================================================
// NOT as a binary AND-NOT operator
// ============================================================
TEST_F(FtsParserTest, NotAsBinaryAndNot) {
// `foo NOT bar` <=> `foo AND NOT bar` -> And[foo, bar(must_not)]
auto ast = parse("foo NOT bar");
ASSERT_NE(ast, nullptr);
const auto &and_node = as_and(*ast);
ASSERT_EQ(and_node.children.size(), 2u);
EXPECT_EQ(as_term(*and_node.children[0]).term, "foo");
EXPECT_FALSE(and_node.children[0]->must_not);
EXPECT_EQ(as_term(*and_node.children[1]).term, "bar");
EXPECT_TRUE(and_node.children[1]->must_not);
}
TEST_F(FtsParserTest, AndAndNot) {
// `a AND NOT b` -> And[a, b(must_not)]
auto ast = parse("a AND NOT b");
ASSERT_NE(ast, nullptr);
const auto &and_node = as_and(*ast);
ASSERT_EQ(and_node.children.size(), 2u);
EXPECT_EQ(as_term(*and_node.children[0]).term, "a");
EXPECT_FALSE(and_node.children[0]->must_not);
EXPECT_EQ(as_term(*and_node.children[1]).term, "b");
EXPECT_TRUE(and_node.children[1]->must_not);
}
TEST_F(FtsParserTest, OrThenNot) {
// Precedence check: NOT shares AND's precedence (higher than OR).
// `a OR b NOT c` -> Or[a, And[b, c(must_not)]]
auto ast = parse("a OR b NOT c");
ASSERT_NE(ast, nullptr);
const auto &or_node = as_or(*ast);
ASSERT_EQ(or_node.children.size(), 2u);
EXPECT_EQ(as_term(*or_node.children[0]).term, "a");
const auto &right_and = as_and(*or_node.children[1]);
ASSERT_EQ(right_and.children.size(), 2u);
EXPECT_EQ(as_term(*right_and.children[0]).term, "b");
EXPECT_FALSE(right_and.children[0]->must_not);
EXPECT_EQ(as_term(*right_and.children[1]).term, "c");
EXPECT_TRUE(right_and.children[1]->must_not);
}
TEST_F(FtsParserTest, NotWithGroup) {
// `a NOT (b OR c)` -> And[a, Or[b, c](must_not)]
auto ast = parse("a NOT (b OR c)");
ASSERT_NE(ast, nullptr);
const auto &and_node = as_and(*ast);
ASSERT_EQ(and_node.children.size(), 2u);
EXPECT_EQ(as_term(*and_node.children[0]).term, "a");
EXPECT_FALSE(and_node.children[0]->must_not);
ASSERT_EQ(and_node.children[1]->type(), FtsNodeType::OR);
EXPECT_TRUE(and_node.children[1]->must_not);
const auto &grouped_or = as_or(*and_node.children[1]);
ASSERT_EQ(grouped_or.children.size(), 2u);
EXPECT_EQ(as_term(*grouped_or.children[0]).term, "b");
EXPECT_EQ(as_term(*grouped_or.children[1]).term, "c");
}
TEST_F(FtsParserTest, LeadingNotIsError) {
// Leading NOT has no left-hand operand and must fail to parse.
auto ast = parse("NOT a");
EXPECT_EQ(ast, nullptr);
EXPECT_FALSE(err_msg().empty());
}
TEST_F(FtsParserTest, MultipleNotsAndAnds) {
// `a AND b NOT c AND d NOT e` -> And[a, b, c(must_not), d, e(must_not)]
auto ast = parse("a AND b NOT c AND d NOT e");
ASSERT_NE(ast, nullptr);
const auto &and_node = as_and(*ast);
ASSERT_EQ(and_node.children.size(), 5u);
EXPECT_EQ(as_term(*and_node.children[0]).term, "a");
EXPECT_FALSE(and_node.children[0]->must_not);
EXPECT_EQ(as_term(*and_node.children[1]).term, "b");
EXPECT_FALSE(and_node.children[1]->must_not);
EXPECT_EQ(as_term(*and_node.children[2]).term, "c");
EXPECT_TRUE(and_node.children[2]->must_not);
EXPECT_EQ(as_term(*and_node.children[3]).term, "d");
EXPECT_FALSE(and_node.children[3]->must_not);
EXPECT_EQ(as_term(*and_node.children[4]).term, "e");
EXPECT_TRUE(and_node.children[4]->must_not);
}
// ============================================================
// +/- modifiers on parenthesised sub-expressions
// ============================================================
TEST_F(FtsParserTest, MustOnGroup) {
// `+(a OR b)` -> Or[a, b]{must=true}
auto ast = parse("+(a OR b)");
ASSERT_NE(ast, nullptr);
ASSERT_EQ(ast->type(), FtsNodeType::OR);
EXPECT_TRUE(ast->must);
EXPECT_FALSE(ast->must_not);
const auto &or_node = as_or(*ast);
ASSERT_EQ(or_node.children.size(), 2u);
EXPECT_EQ(as_term(*or_node.children[0]).term, "a");
EXPECT_EQ(as_term(*or_node.children[1]).term, "b");
}
TEST_F(FtsParserTest, MustNotOnGroup) {
// `-(a AND b)` -> And[a, b]{must_not=true}
auto ast = parse("-(a AND b)");
ASSERT_NE(ast, nullptr);
ASSERT_EQ(ast->type(), FtsNodeType::AND);
EXPECT_FALSE(ast->must);
EXPECT_TRUE(ast->must_not);
const auto &and_node = as_and(*ast);
ASSERT_EQ(and_node.children.size(), 2u);
EXPECT_EQ(as_term(*and_node.children[0]).term, "a");
EXPECT_EQ(as_term(*and_node.children[1]).term, "b");
}
TEST_F(FtsParserTest, MustGroupAndOther) {
// `+(a OR b) c` -> implicit-OR collapses three siblings into a single
// OrNode: Or[Or[a, b]{must=true}, c]
// (the inner OR keeps its must flag; implicit adjacency is still OR.)
auto ast = parse("+(a OR b) c");
ASSERT_NE(ast, nullptr);
ASSERT_EQ(ast->type(), FtsNodeType::OR);
const auto &outer_or = as_or(*ast);
ASSERT_EQ(outer_or.children.size(), 2u);
ASSERT_EQ(outer_or.children[0]->type(), FtsNodeType::OR);
EXPECT_TRUE(outer_or.children[0]->must);
const auto &inner_or = as_or(*outer_or.children[0]);
ASSERT_EQ(inner_or.children.size(), 2u);
EXPECT_EQ(as_term(*inner_or.children[0]).term, "a");
EXPECT_EQ(as_term(*inner_or.children[1]).term, "b");
EXPECT_EQ(as_term(*outer_or.children[1]).term, "c");
}
TEST_F(FtsParserTest, NestedGroupModifier) {
// `+((a AND b) OR c)` -> the must flag attaches to the outermost OrNode.
auto ast = parse("+((a AND b) OR c)");
ASSERT_NE(ast, nullptr);
ASSERT_EQ(ast->type(), FtsNodeType::OR);
EXPECT_TRUE(ast->must);
const auto &or_node = as_or(*ast);
ASSERT_EQ(or_node.children.size(), 2u);
ASSERT_EQ(or_node.children[0]->type(), FtsNodeType::AND);
EXPECT_FALSE(or_node.children[0]->must); // inner AND not affected
const auto &inner_and = as_and(*or_node.children[0]);
ASSERT_EQ(inner_and.children.size(), 2u);
EXPECT_EQ(as_term(*inner_and.children[0]).term, "a");
EXPECT_EQ(as_term(*inner_and.children[1]).term, "b");
EXPECT_EQ(as_term(*or_node.children[1]).term, "c");
}
// ============================================================
// Default operator (FtsDefaultOperator::OR / AND)
// Only adjacent bare terms (no explicit operator) are affected; explicit
// AND / OR / + / - usages keep their original semantics.
// ============================================================
TEST_F(FtsParserTest, DefaultOperatorOr_AdjacentBareTerms) {
// Backward-compat: omitting default_op or passing OR yields the original
// implicit-OR behaviour for adjacent bare terms.
auto ast = parse("vector database", FtsDefaultOperator::OR);
ASSERT_NE(ast, nullptr);
ASSERT_EQ(ast->type(), FtsNodeType::OR);
const auto &or_node = as_or(*ast);
ASSERT_EQ(or_node.children.size(), 2u);
EXPECT_EQ(as_term(*or_node.children[0]).term, "vector");
EXPECT_EQ(as_term(*or_node.children[1]).term, "database");
}
TEST_F(FtsParserTest, DefaultOperatorAnd_AdjacentBareTerms) {
// With AND default, two adjacent bare terms collapse into an AndNode.
auto ast = parse("vector database", FtsDefaultOperator::AND);
ASSERT_NE(ast, nullptr);
ASSERT_EQ(ast->type(), FtsNodeType::AND);
const auto &and_node = as_and(*ast);
ASSERT_EQ(and_node.children.size(), 2u);
EXPECT_EQ(as_term(*and_node.children[0]).term, "vector");
EXPECT_EQ(as_term(*and_node.children[1]).term, "database");
}
TEST_F(FtsParserTest, DefaultOperatorAnd_SingleTermUnchanged) {
// A single term should not be wrapped in an AndNode.
auto ast = parse("vector", FtsDefaultOperator::AND);
ASSERT_NE(ast, nullptr);
ASSERT_EQ(ast->type(), FtsNodeType::TERM);
EXPECT_EQ(as_term(*ast).term, "vector");
}
TEST_F(FtsParserTest, DefaultOperatorAnd_PropagatesIntoParens) {
// Parenthesised sub-expressions inherit the same default operator.
// `(a b) c` with AND default -> And[And[a, b], c].
auto ast = parse("(a b) c", FtsDefaultOperator::AND);
ASSERT_NE(ast, nullptr);
ASSERT_EQ(ast->type(), FtsNodeType::AND);
const auto &outer_and = as_and(*ast);
ASSERT_EQ(outer_and.children.size(), 2u);
ASSERT_EQ(outer_and.children[0]->type(), FtsNodeType::AND);
const auto &inner_and = as_and(*outer_and.children[0]);
ASSERT_EQ(inner_and.children.size(), 2u);
EXPECT_EQ(as_term(*inner_and.children[0]).term, "a");
EXPECT_EQ(as_term(*inner_and.children[1]).term, "b");
EXPECT_EQ(as_term(*outer_and.children[1]).term, "c");
}
TEST_F(FtsParserTest, DefaultOperatorAnd_DoesNotOverrideExplicitOr) {
// Explicit OR has higher-level structure; default_op only changes the
// implicit adjacency inside each seqExpr.
// `a OR b c` with AND default -> Or[a, And[b, c]].
auto ast = parse("a OR b c", FtsDefaultOperator::AND);
ASSERT_NE(ast, nullptr);
ASSERT_EQ(ast->type(), FtsNodeType::OR);
const auto &or_node = as_or(*ast);
ASSERT_EQ(or_node.children.size(), 2u);
EXPECT_EQ(as_term(*or_node.children[0]).term, "a");
ASSERT_EQ(or_node.children[1]->type(), FtsNodeType::AND);
const auto &inner_and = as_and(*or_node.children[1]);
ASSERT_EQ(inner_and.children.size(), 2u);
EXPECT_EQ(as_term(*inner_and.children[0]).term, "b");
EXPECT_EQ(as_term(*inner_and.children[1]).term, "c");
}
TEST_F(FtsParserTest, DefaultOperatorOr_DoesNotOverrideExplicitAnd) {
// Grammar: andExpr = seqExpr ((AND|NOT) seqExpr)*
// `a AND b c` parses as seqExpr("a") AND seqExpr("b c").
// With OR default, seqExpr("b c") -> Or[b, c].
// Result: And[a, Or[b, c]].
auto ast = parse("a AND b c", FtsDefaultOperator::OR);
ASSERT_NE(ast, nullptr);
ASSERT_EQ(ast->type(), FtsNodeType::AND);
const auto &and_node = as_and(*ast);
ASSERT_EQ(and_node.children.size(), 2u);
EXPECT_EQ(as_term(*and_node.children[0]).term, "a");
ASSERT_EQ(and_node.children[1]->type(), FtsNodeType::OR);
const auto &inner_or = as_or(*and_node.children[1]);
ASSERT_EQ(inner_or.children.size(), 2u);
EXPECT_EQ(as_term(*inner_or.children[0]).term, "b");
EXPECT_EQ(as_term(*inner_or.children[1]).term, "c");
}
TEST_F(FtsParserTest, DefaultOperatorAnd_PreservesPlusMinusModifiers) {
// `+a b -c` with AND default -> And[a{must}, b, c{must_not}].
// Modifiers on individual terms are independent of default_op.
auto ast = parse("+a b -c", FtsDefaultOperator::AND);
ASSERT_NE(ast, nullptr);
ASSERT_EQ(ast->type(), FtsNodeType::AND);
const auto &and_node = as_and(*ast);
ASSERT_EQ(and_node.children.size(), 3u);
const auto &t0 = as_term(*and_node.children[0]);
EXPECT_EQ(t0.term, "a");
EXPECT_TRUE(t0.must);
EXPECT_FALSE(t0.must_not);
const auto &t1 = as_term(*and_node.children[1]);
EXPECT_EQ(t1.term, "b");
EXPECT_FALSE(t1.must);
EXPECT_FALSE(t1.must_not);
const auto &t2 = as_term(*and_node.children[2]);
EXPECT_EQ(t2.term, "c");
EXPECT_FALSE(t2.must);
EXPECT_TRUE(t2.must_not);
}
// ============================================================
// Pipeline-aware tokenization (phrase / bare term split through pipeline)
// ============================================================
TEST_F(FtsParserTest, MultiTokenBareTermAndDefaultGroupsAsAnd) {
// `full-text` lexes as one REGULAR_ID, but standard splits it into
// ["full", "text"]. With AND default operator the two tokens combine into
// an AndNode rather than the OR returned by the OR-default test above.
auto ast = parse("full-text", FtsDefaultOperator::AND);
ASSERT_NE(ast, nullptr);
ASSERT_EQ(ast->type(), FtsNodeType::AND);
const auto &and_node = as_and(*ast);
ASSERT_EQ(and_node.children.size(), 2u);
EXPECT_EQ(as_term(*and_node.children[0]).term, "full");
EXPECT_EQ(as_term(*and_node.children[1]).term, "text");
}
TEST_F(FtsParserTest, MultiTokenBareTermPreservesMustModifier) {
// `+full-text` -> Or[full, text] with must=true on the composite root.
auto ast = parse("+full-text");
ASSERT_NE(ast, nullptr);
ASSERT_EQ(ast->type(), FtsNodeType::OR);
EXPECT_TRUE(ast->must);
EXPECT_FALSE(ast->must_not);
const auto &or_node = as_or(*ast);
ASSERT_EQ(or_node.children.size(), 2u);
EXPECT_EQ(as_term(*or_node.children[0]).term, "full");
EXPECT_EQ(as_term(*or_node.children[1]).term, "text");
}
TEST_F(FtsParserTest, PhraseTokensRunThroughPipeline) {
// The phrase body is tokenized exactly like document text. With the
// standard tokenizer, mixed delimiters between alnum runs collapse so
// "machine, learning!" becomes ["machine", "learning"].
auto ast = parse("\"machine, learning!\"");
ASSERT_NE(ast, nullptr);
ASSERT_EQ(ast->type(), FtsNodeType::PHRASE);
const auto &phrase = as_phrase(*ast);
ASSERT_EQ(phrase.terms.size(), 2u);
EXPECT_EQ(phrase.terms[0], "machine");
EXPECT_EQ(phrase.terms[1], "learning");
}
TEST_F(FtsParserTest, PhraseLowercaseFilterApplies) {
// The lowercase filter is part of the pipeline so phrase tokens come back
// lowercased even when the input mixed case.
auto ast = parse("\"Machine LEARNING\"");
ASSERT_NE(ast, nullptr);
ASSERT_EQ(ast->type(), FtsNodeType::PHRASE);
const auto &phrase = as_phrase(*ast);
ASSERT_EQ(phrase.terms.size(), 2u);
EXPECT_EQ(phrase.terms[0], "machine");
EXPECT_EQ(phrase.terms[1], "learning");
}
TEST_F(FtsParserTest, AllPunctuationPhraseYieldsEmptyTerms) {
// Pure non-alnum content is filtered out entirely. The phrase node still
// exists but carries zero terms; the search engine treats this as
// "match nothing" without crashing.
auto ast = parse("\"!!! ???\"");
ASSERT_NE(ast, nullptr);
ASSERT_EQ(ast->type(), FtsNodeType::PHRASE);
EXPECT_TRUE(as_phrase(*ast).terms.empty());
}
// ============================================================
// Unescape: backslash removal for TERM and PHRASE paths.
// Uses WhitespaceTokenizer (no filter) so that special characters are
// preserved in tokens — this lets us observe whether unescape() actually
// stripped the backslashes.
// ============================================================
class FtsParserUnescapeTest : public ::testing::Test {
protected:
void SetUp() override {
FtsIndexParams params;
params.tokenizer_name = "whitespace";
params.filters = {};
pipeline_ = TokenizerFactory::create(params);
ASSERT_NE(pipeline_, nullptr);
}
FtsAstNodePtr parse(const std::string &query) {
return parser_.parse(query, pipeline_);
}
static const TermNode &as_term(const FtsAstNode &node) {
EXPECT_EQ(node.type(), FtsNodeType::TERM);
return static_cast<const TermNode &>(node);
}
static const PhraseNode &as_phrase(const FtsAstNode &node) {
EXPECT_EQ(node.type(), FtsNodeType::PHRASE);
return static_cast<const PhraseNode &>(node);
}
private:
FtsQueryParser parser_;
TokenizerPipelinePtr pipeline_;
};
TEST_F(FtsParserUnescapeTest, TermEscapedPlusBecomesLiteralPlus) {
// Lexer token: C\+\+ (with backslashes). After unescape: C++.
// WhitespaceTokenizer preserves the '+' in the token text.
auto ast = parse(R"(C\+\+)");
ASSERT_NE(ast, nullptr);
ASSERT_EQ(ast->type(), FtsNodeType::TERM);
EXPECT_EQ(as_term(*ast).term, "C++");
}
TEST_F(FtsParserUnescapeTest, TermEscapedMinusBecomesLiteralMinus) {
// "a\-b" after unescape → "a-b" kept intact by whitespace tokenizer.
auto ast = parse(R"(a\-b)");
ASSERT_NE(ast, nullptr);
ASSERT_EQ(ast->type(), FtsNodeType::TERM);
EXPECT_EQ(as_term(*ast).term, "a-b");
}
TEST_F(FtsParserUnescapeTest, TermEscapedBackslashBecomesLiteralBackslash) {
// "path\\dir" — lexer sees ESCAPED_CHAR(\\), unescape yields "path\dir".
auto ast = parse(R"(path\\dir)");
ASSERT_NE(ast, nullptr);
ASSERT_EQ(ast->type(), FtsNodeType::TERM);
EXPECT_EQ(as_term(*ast).term, "path\\dir");
}
TEST_F(FtsParserUnescapeTest, PhraseEscapedQuoteBecomesLiteralQuote) {
// Phrase: "hello \"world\"" — after strip_quotes + unescape:
// 'hello "world"' — whitespace tokenizer splits on space to:
// ["hello", "\"world\""]
auto ast = parse(R"("hello \"world\"")");
ASSERT_NE(ast, nullptr);
ASSERT_EQ(ast->type(), FtsNodeType::PHRASE);
const auto &phrase = as_phrase(*ast);
ASSERT_EQ(phrase.terms.size(), 2u);
EXPECT_EQ(phrase.terms[0], "hello");
EXPECT_EQ(phrase.terms[1], "\"world\"");
}
TEST_F(FtsParserUnescapeTest, PhraseEscapedBackslashBecomesLiteral) {
// Phrase: "a\\b" — after strip+unescape: "a\b" (one backslash, no space),
// whitespace tokenizer keeps it as single token.
auto ast = parse(R"("a\\b")");
ASSERT_NE(ast, nullptr);
ASSERT_EQ(ast->type(), FtsNodeType::PHRASE);
const auto &phrase = as_phrase(*ast);
ASSERT_EQ(phrase.terms.size(), 1u);
EXPECT_EQ(phrase.terms[0], "a\\b");
}
} // namespace zvec::fts
+817
View File
@@ -0,0 +1,817 @@
// 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 <cstdint>
#include <memory>
#include <set>
#include <string>
#include <vector>
#include <gtest/gtest.h>
#include "db/common/file_helper.h"
#include "db/index/common/version_manager.h"
#include "db/index/segment/segment.h"
#include "db/sqlengine/sqlengine.h"
#include "zvec/db/doc.h"
#include "zvec/db/index_params.h"
#include "zvec/db/query_params.h"
#include "zvec/db/schema.h"
#include "zvec/db/type.h"
namespace zvec::sqlengine {
// ============================================================
// FTS Recall Test fixture (real Segment + SQLEngine::execute via SearchQuery)
// ============================================================
class FtsRecallTest : public ::testing::Test {
protected:
static void SetUpTestSuite() {
FileHelper::RemoveDirectory(seg_path_);
FileHelper::CreateDirectory(seg_path_);
build_schema();
auto segment = create_segment();
ASSERT_NE(segment, nullptr);
insert_docs(segment);
segments_.push_back(segment);
engine_ = SQLEngine::create(std::make_shared<Profiler>());
}
static void TearDownTestSuite() {
segments_.clear();
engine_.reset();
schema_.reset();
FileHelper::RemoveDirectory(seg_path_);
}
// Helper: execute FTS query_string search via SearchQuery
Result<DocPtrList> fts_search(const std::string &query_string,
int topk = 10) {
SearchQuery vq;
vq.topk_ = topk;
vq.target_.field_name_ = "content";
FtsClause fts;
fts.query_string_ = query_string;
vq.target_.clause_ = fts;
return engine_->execute(schema_, vq, segments_);
}
// Helper: execute FTS match_string search via SearchQuery
Result<DocPtrList> fts_match(const std::string &match_string,
const std::string &default_op = "",
int topk = 10) {
SearchQuery vq;
vq.topk_ = topk;
vq.target_.field_name_ = "content";
FtsClause fts;
fts.match_string_ = match_string;
vq.target_.clause_ = fts;
if (!default_op.empty()) {
auto fts_qp = std::make_shared<zvec::FtsQueryParams>();
fts_qp->set_default_operator(default_op);
vq.target_.query_params_ = fts_qp;
}
return engine_->execute(schema_, vq, segments_);
}
// Helper: execute FTS query_string with default_operator via SearchQuery
Result<DocPtrList> fts_query_with_op(const std::string &query_string,
const std::string &default_op,
int topk = 10) {
SearchQuery vq;
vq.topk_ = topk;
vq.target_.field_name_ = "content";
FtsClause fts;
fts.query_string_ = query_string;
vq.target_.clause_ = fts;
auto fts_qp = std::make_shared<zvec::FtsQueryParams>();
fts_qp->set_default_operator(default_op);
vq.target_.query_params_ = fts_qp;
return engine_->execute(schema_, vq, segments_);
}
// Helper: execute FTS query_string with WHERE filter via SearchQuery
Result<DocPtrList> fts_search_with_filter(const std::string &query_string,
const std::string &filter,
int topk = 10) {
SearchQuery vq;
vq.topk_ = topk;
vq.target_.field_name_ = "content";
vq.filter_ = filter;
FtsClause fts;
fts.query_string_ = query_string;
vq.target_.clause_ = fts;
return engine_->execute(schema_, vq, segments_);
}
private:
static void build_schema() {
auto fts_params = std::make_shared<FtsIndexParams>(
"whitespace", std::vector<std::string>{"lowercase"}, "");
auto invert_params = std::make_shared<InvertIndexParams>(true);
schema_ = std::make_shared<CollectionSchema>(
"fts_recall_test",
std::vector<FieldSchema::Ptr>{
std::make_shared<FieldSchema>("content", DataType::STRING, false,
fts_params),
std::make_shared<FieldSchema>("tag", DataType::INT32, false,
invert_params),
// Dummy vector field required for filter parsing path in
// execute
std::make_shared<FieldSchema>(
"vec", DataType::VECTOR_FP32, 4, false,
std::make_shared<FlatIndexParams>(MetricType::L2)),
});
}
static Segment::Ptr create_segment() {
auto segment_meta = std::make_shared<SegmentMeta>();
segment_meta->set_id(0);
auto id_map = IDMap::CreateAndOpen("fts_recall_test", seg_path_ + "/id_map",
true, false);
auto delete_store = std::make_shared<DeleteStore>("fts_recall_test");
Version v1;
v1.set_schema(*schema_);
std::string v_path = seg_path_ + "/manifest";
FileHelper::CreateDirectory(v_path);
auto vm = VersionManager::Create(v_path, v1);
if (!vm.has_value()) {
return nullptr;
}
BlockMeta mem_block;
mem_block.id_ = 0;
mem_block.type_ = BlockType::SCALAR;
mem_block.min_doc_id_ = 0;
mem_block.max_doc_id_ = 0;
mem_block.doc_count_ = 0;
segment_meta->set_writing_forward_block(mem_block);
SegmentOptions options;
options.read_only_ = false;
options.enable_mmap_ = true;
options.max_buffer_size_ = 256 * 1024;
auto result = Segment::CreateAndOpen(seg_path_, *schema_, 0, 0, id_map,
delete_store, vm.value(), options);
if (!result) {
return nullptr;
}
return result.value();
}
static void insert_docs(const Segment::Ptr &segment) {
// doc_id 0: "apple banana cherry" tag=1
// doc_id 1: "banana date elderberry" tag=2
// doc_id 2: "cherry fig grape" tag=1
// doc_id 3: "apple fig honeydew" tag=2
// doc_id 4: "date grape kiwi" tag=1
// doc_id 5: "apple apple apple" tag=2
// doc_id 6: "mango papaya starfruit" tag=1
// doc_id 7: "banana banana grape" tag=2
struct Entry {
std::string content;
int32_t tag;
};
std::vector<Entry> entries = {
{"apple banana cherry", 1}, {"banana date elderberry", 2},
{"cherry fig grape", 1}, {"apple fig honeydew", 2},
{"date grape kiwi", 1}, {"apple apple apple", 2},
{"mango papaya starfruit", 1}, {"banana banana grape", 2},
};
for (size_t i = 0; i < entries.size(); ++i) {
Doc doc;
doc.set_pk("pk_" + std::to_string(i));
doc.set_doc_id(i);
doc.set<std::string>("content", entries[i].content);
doc.set<int32_t>("tag", entries[i].tag);
auto status = segment->Insert(doc);
ASSERT_TRUE(status.ok())
<< "Insert doc " << i << " failed: " << status.c_str();
}
}
protected:
static inline std::string seg_path_ = "./fts_recall_test_collection";
static inline CollectionSchema::Ptr schema_;
static inline std::vector<Segment::Ptr> segments_;
static inline SQLEngine::Ptr engine_;
};
// ============================================================
// Basic FTS search tests
// ============================================================
// "apple" matches docs 0, 3, 5
TEST_F(FtsRecallTest, BasicSingleTerm) {
auto result = fts_search("apple");
ASSERT_TRUE(result.has_value()) << result.error().c_str();
EXPECT_EQ(result->size(), 3u);
}
// BM25 ordering: doc 5 ("apple apple apple") should have highest score
TEST_F(FtsRecallTest, BM25ScoreOrdering) {
auto result = fts_search("apple");
ASSERT_TRUE(result.has_value()) << result.error().c_str();
ASSERT_GE(result->size(), 2u);
// Results should be sorted by score descending
for (size_t i = 0; i + 1 < result->size(); ++i) {
EXPECT_GE((*result)[i]->score(), (*result)[i + 1]->score())
<< "Results not sorted descending at index " << i;
}
// Doc 5 has highest TF for "apple"
EXPECT_EQ((*result)[0]->pk(), "pk_5");
}
// "kiwi" only in doc 4
TEST_F(FtsRecallTest, SingleMatch) {
auto result = fts_search("kiwi");
ASSERT_TRUE(result.has_value()) << result.error().c_str();
ASSERT_EQ(result->size(), 1u);
EXPECT_EQ((*result)[0]->pk(), "pk_4");
}
// Nonexistent term
TEST_F(FtsRecallTest, NoMatch) {
auto result = fts_search("zzznomatch");
ASSERT_TRUE(result.has_value()) << result.error().c_str();
EXPECT_EQ(result->size(), 0u);
}
// Topk limit: "banana" in docs 0, 1, 7 (3 matches), topk=2
TEST_F(FtsRecallTest, TopkLimit) {
auto result = fts_search("banana", /*topk=*/2);
ASSERT_TRUE(result.has_value()) << result.error().c_str();
EXPECT_LE(result->size(), 2u);
}
// Multi-term implicit OR: "apple banana" matches union of {0,3,5} and {0,1,7}
TEST_F(FtsRecallTest, MultiTermImplicitOr) {
auto result = fts_search("apple banana");
ASSERT_TRUE(result.has_value()) << result.error().c_str();
// Union: {0,1,3,5,7} = 5 docs
EXPECT_EQ(result->size(), 5u);
}
// "starfruit" only in doc 6
TEST_F(FtsRecallTest, RareTerm) {
auto result = fts_search("starfruit");
ASSERT_TRUE(result.has_value()) << result.error().c_str();
ASSERT_EQ(result->size(), 1u);
EXPECT_EQ((*result)[0]->pk(), "pk_6");
}
// "grape" in docs 2, 4, 7
TEST_F(FtsRecallTest, CommonTerm) {
auto result = fts_search("grape");
ASSERT_TRUE(result.has_value()) << result.error().c_str();
EXPECT_EQ(result->size(), 3u);
}
// ============================================================
// Explicit AND
// ============================================================
// "apple AND banana" -> intersection of {0,3,5} and {0,1,7} = {0}
TEST_F(FtsRecallTest, ExplicitAnd) {
auto result = fts_search("apple AND banana");
ASSERT_TRUE(result.has_value()) << result.error().c_str();
EXPECT_EQ(result->size(), 1u);
EXPECT_EQ((*result)[0]->pk(), "pk_0");
}
// "cherry AND fig" -> {0,2} AND {2,3} = {2}
TEST_F(FtsRecallTest, ExplicitAnd2) {
auto result = fts_search("cherry AND fig");
ASSERT_TRUE(result.has_value()) << result.error().c_str();
EXPECT_EQ(result->size(), 1u);
EXPECT_EQ((*result)[0]->pk(), "pk_2");
}
// ============================================================
// Binary NOT (AND-NOT)
// ============================================================
// "apple NOT banana" -> {0,3,5} minus {0,1,7} = {3,5}
TEST_F(FtsRecallTest, BinaryNot) {
auto result = fts_search("apple NOT banana");
ASSERT_TRUE(result.has_value()) << result.error().c_str();
EXPECT_EQ(result->size(), 2u);
std::set<std::string> pks;
for (auto &doc : *result) {
pks.insert(doc->pk());
}
EXPECT_TRUE(pks.count("pk_3"));
EXPECT_TRUE(pks.count("pk_5"));
}
// "banana NOT grape" -> {0,1,7} minus {2,4,7} = {0,1}
TEST_F(FtsRecallTest, BinaryNot2) {
auto result = fts_search("banana NOT grape");
ASSERT_TRUE(result.has_value()) << result.error().c_str();
EXPECT_EQ(result->size(), 2u);
std::set<std::string> pks;
for (auto &doc : *result) {
pks.insert(doc->pk());
}
EXPECT_TRUE(pks.count("pk_0"));
EXPECT_TRUE(pks.count("pk_1"));
}
// ============================================================
// Error cases
// ============================================================
// Leading NOT should fail parse
TEST_F(FtsRecallTest, LeadingNotIsRejected) {
auto result = fts_search("NOT apple");
EXPECT_FALSE(result.has_value());
}
// Both query_string_ and match_string_ empty
TEST_F(FtsRecallTest, BothEmptyReturnsError) {
SearchQuery vq;
vq.topk_ = 10;
vq.target_.field_name_ = "content";
vq.target_.clause_ = FtsClause{}; // both fields empty
auto result = engine_->execute(schema_, vq, segments_);
EXPECT_FALSE(result.has_value());
}
// Both query_string_ and match_string_ set
TEST_F(FtsRecallTest, BothSetReturnsError) {
SearchQuery vq;
vq.topk_ = 10;
vq.target_.field_name_ = "content";
FtsClause fts;
fts.query_string_ = "apple";
fts.match_string_ = "banana";
vq.target_.clause_ = fts;
auto result = engine_->execute(schema_, vq, segments_);
EXPECT_FALSE(result.has_value());
}
// ============================================================
// match_string tests
// ============================================================
// match_string "starfruit" -> doc 6
TEST_F(FtsRecallTest, MatchStringRareTerm) {
auto result = fts_match("starfruit");
ASSERT_TRUE(result.has_value()) << result.error().c_str();
ASSERT_EQ(result->size(), 1u);
EXPECT_EQ((*result)[0]->pk(), "pk_6");
}
// match_string "grape" -> docs 2, 4, 7
TEST_F(FtsRecallTest, MatchStringCommonTerm) {
auto result = fts_match("grape");
ASSERT_TRUE(result.has_value()) << result.error().c_str();
EXPECT_EQ(result->size(), 3u);
}
// match_string "apple banana" -> OR -> union {0,1,3,5,7}
TEST_F(FtsRecallTest, MatchStringMultipleTokens) {
auto result = fts_match("apple banana");
ASSERT_TRUE(result.has_value()) << result.error().c_str();
EXPECT_EQ(result->size(), 5u);
}
// match_string analysing to zero tokens → empty result, not an error.
TEST_F(FtsRecallTest, MatchStringEmptyTokensReturnsNoResults) {
auto result = fts_match(" \t ");
ASSERT_TRUE(result.has_value()) << result.error().c_str();
EXPECT_TRUE(result->empty());
}
// ============================================================
// default_operator tests
// ============================================================
// AND default for match_string: "apple banana" -> intersection = {0}
TEST_F(FtsRecallTest, DefaultOperatorAnd_MatchString) {
auto result = fts_match("apple banana", "AND");
ASSERT_TRUE(result.has_value()) << result.error().c_str();
EXPECT_EQ(result->size(), 1u);
EXPECT_EQ((*result)[0]->pk(), "pk_0");
}
// OR default for match_string (backward compat)
TEST_F(FtsRecallTest, DefaultOperatorOr_MatchString) {
auto result = fts_match("apple banana", "OR");
ASSERT_TRUE(result.has_value()) << result.error().c_str();
EXPECT_EQ(result->size(), 5u);
}
// AND default for query_string: "apple banana" -> AND
TEST_F(FtsRecallTest, DefaultOperatorAnd_QueryString) {
auto result = fts_query_with_op("apple banana", "AND");
ASSERT_TRUE(result.has_value()) << result.error().c_str();
EXPECT_EQ(result->size(), 1u);
EXPECT_EQ((*result)[0]->pk(), "pk_0");
}
// Explicit OR in query not overridden by default_operator=AND
// "apple OR grape" with AND default -> OR still applies
TEST_F(FtsRecallTest, DefaultOperatorAnd_DoesNotOverrideExplicitOr) {
auto result = fts_query_with_op("apple OR grape", "AND");
ASSERT_TRUE(result.has_value()) << result.error().c_str();
// apple: {0,3,5}, grape: {2,4,7} -> union = 6
EXPECT_EQ(result->size(), 6u);
}
// Empty default_operator keeps historical OR for match_string
TEST_F(FtsRecallTest, DefaultOperatorEmpty_BackwardCompatibleOr) {
auto result = fts_match("apple banana"); // no default_op arg
ASSERT_TRUE(result.has_value()) << result.error().c_str();
// OR semantics: union of apple{0,3,5} and banana{0,1,7} = 5
EXPECT_EQ(result->size(), 5u);
}
// Lowercase "and" must be accepted
TEST_F(FtsRecallTest, DefaultOperatorAndLowercase_Accepted) {
auto result = fts_match("apple banana", "and");
ASSERT_TRUE(result.has_value()) << result.error().c_str();
EXPECT_EQ(result->size(), 1u);
}
// Mixed-case "And" / "oR" are accepted via case-insensitive normalisation.
TEST_F(FtsRecallTest, DefaultOperatorMixedCase_Accepted) {
{
// "And" -> AND semantics: intersection of apple{0,3,5} and banana{0,1,7}
auto result = fts_match("apple banana", "And");
ASSERT_TRUE(result.has_value()) << result.error().c_str();
EXPECT_EQ(result->size(), 1u);
}
{
// "oR" -> OR semantics: union = 5 docs
auto result = fts_match("apple banana", "oR");
ASSERT_TRUE(result.has_value()) << result.error().c_str();
EXPECT_EQ(result->size(), 5u);
}
}
// Invalid default_operator value should be rejected (was previously silently
// downgraded to OR).
TEST_F(FtsRecallTest, DefaultOperatorInvalid_Rejected) {
auto result = fts_match("apple banana", "xor");
EXPECT_FALSE(result.has_value());
}
// ============================================================
// Error cases (additional)
// ============================================================
// Empty field_name should fail
TEST_F(FtsRecallTest, EmptyFieldNameReturnsError) {
SearchQuery vq;
vq.topk_ = 10;
vq.target_.field_name_ = "";
FtsClause fts;
fts.query_string_ = "apple";
vq.target_.clause_ = fts;
auto result = engine_->execute(schema_, vq, segments_);
EXPECT_FALSE(result.has_value());
}
// Empty query_string (with field_name set) should fail
TEST_F(FtsRecallTest, EmptyQueryStringReturnsError) {
SearchQuery vq;
vq.topk_ = 10;
vq.target_.field_name_ = "content";
// Both query_string_ and match_string_ empty -> error
vq.target_.clause_ = FtsClause{};
auto result = engine_->execute(schema_, vq, segments_);
EXPECT_FALSE(result.has_value());
}
// ============================================================
// FTS search with WHERE filter
// ============================================================
// "apple" (docs 0,3,5) + tag = 1 (docs 0,2,4,6) -> intersection = {0}
TEST_F(FtsRecallTest, FtsSearchWithFilter_ScoreTag) {
auto result = fts_search_with_filter("apple", "tag = 1");
ASSERT_TRUE(result.has_value()) << result.error().c_str();
// Filter should reduce results to doc 0 only
EXPECT_LE(result->size(), 3u);
// Verify that at least doc 0 (which satisfies both FTS and filter) is present
bool found_pk0 = false;
for (auto &doc : *result) {
if (doc->pk() == "pk_0") {
found_pk0 = true;
}
}
EXPECT_TRUE(found_pk0);
}
// "banana" (docs 0,1,7) + tag = 2 (docs 1,3,5,7) + topk=1
TEST_F(FtsRecallTest, FtsSearchWithFilter_TopkRespected) {
auto result = fts_search_with_filter("banana", "tag = 2", /*topk=*/1);
ASSERT_TRUE(result.has_value()) << result.error().c_str();
EXPECT_LE(result->size(), 1u);
}
// An FTS field can only be used as a query target, not as a filter condition.
// Putting the FTS field ("content") in the WHERE filter must be rejected.
TEST_F(FtsRecallTest, FtsFieldNotAllowedInFilter) {
auto result = fts_search_with_filter("apple", "content = 'apple'");
ASSERT_FALSE(result.has_value());
}
// ============================================================
// Repeated-term linearity: the AST rewriter collapses a repeated term into a
// single TermNode whose boost equals the occurrence count. With linear boost
// the per-document score must be exactly N× the single-term score, matching
// the pre-rewrite "N independent scorers summed" semantics.
// ============================================================
TEST_F(FtsRecallTest, MatchStringRepeatedTermLinearBoost) {
auto baseline = fts_match("apple");
auto repeated = fts_match("apple apple");
ASSERT_TRUE(baseline.has_value()) << baseline.error().c_str();
ASSERT_TRUE(repeated.has_value()) << repeated.error().c_str();
ASSERT_EQ(baseline->size(), repeated->size());
// Same doc set, same ordering — only the absolute scores differ.
for (size_t i = 0; i < baseline->size(); ++i) {
EXPECT_EQ((*baseline)[i]->pk(), (*repeated)[i]->pk()) << "rank " << i;
EXPECT_FLOAT_EQ((*baseline)[i]->score() * 2.0f, (*repeated)[i]->score())
<< "rank " << i << " pk=" << (*repeated)[i]->pk();
}
}
// Unary `-` prefix inside an OR was previously executed via build_or_iterator
// wrapping the disjunction in a must_not Conjunction. After the rewriter
// canonicalizes OR-with-must_not into AND(positive..., -negative...), the
// must_not iterator path lives only in build_and_iterator. End-to-end the
// match set must be unchanged: apple{0,3,5} − banana{0,1,7} = {3, 5}.
TEST_F(FtsRecallTest, QueryStringUnaryMinusExcludesMatchingDocs) {
auto result = fts_search("apple -banana");
ASSERT_TRUE(result.has_value()) << result.error().c_str();
std::set<std::string> pks;
for (const auto &d : *result) {
pks.insert(d->pk());
}
EXPECT_EQ(pks, std::set<std::string>({"pk_3", "pk_5"}));
}
// `apple -apple` is a self-contradiction; the rewriter detects the must vs
// must_not conflict after canonicalization and rewrites the whole subtree
// to EmptyNode, so the query short-circuits to zero docs.
TEST_F(FtsRecallTest, QueryStringSelfContradictionReturnsNoResults) {
auto result = fts_search("apple -apple");
ASSERT_TRUE(result.has_value()) << result.error().c_str();
EXPECT_TRUE(result->empty());
}
TEST_F(FtsRecallTest, MatchStringRepeatedTermPreservesUnion) {
// "apple apple banana" — apple repeated, banana once. Doc set must equal
// "apple banana" (union), and apple-only docs should score 2× their
// single-term score plus zero for banana.
auto plain_union = fts_match("apple banana");
auto repeated_union = fts_match("apple apple banana");
ASSERT_TRUE(plain_union.has_value()) << plain_union.error().c_str();
ASSERT_TRUE(repeated_union.has_value()) << repeated_union.error().c_str();
EXPECT_EQ(plain_union->size(), repeated_union->size());
std::set<std::string> plain_pks;
std::set<std::string> repeated_pks;
for (const auto &d : *plain_union) {
plain_pks.insert(d->pk());
}
for (const auto &d : *repeated_union) {
repeated_pks.insert(d->pk());
}
EXPECT_EQ(plain_pks, repeated_pks);
}
// ============================================================
// FTS delete / upsert end-to-end tests (per-test fixture)
// ============================================================
class FtsRecallDeleteTest : public ::testing::Test {
protected:
void SetUp() override {
seg_path_ = "./fts_recall_delete_test_" +
std::to_string(reinterpret_cast<uintptr_t>(this));
FileHelper::RemoveDirectory(seg_path_);
FileHelper::CreateDirectory(seg_path_);
auto fts_params = std::make_shared<FtsIndexParams>(
"whitespace", std::vector<std::string>{"lowercase"}, "");
auto invert_params = std::make_shared<InvertIndexParams>(true);
schema_ = std::make_shared<CollectionSchema>(
"fts_delete_test",
std::vector<FieldSchema::Ptr>{
std::make_shared<FieldSchema>("content", DataType::STRING, false,
fts_params),
std::make_shared<FieldSchema>("tag", DataType::INT32, false,
invert_params),
std::make_shared<FieldSchema>(
"vec", DataType::VECTOR_FP32, 4, false,
std::make_shared<FlatIndexParams>(MetricType::L2)),
});
auto segment_meta = std::make_shared<SegmentMeta>();
segment_meta->set_id(0);
auto id_map = IDMap::CreateAndOpen("fts_delete_test", seg_path_ + "/id_map",
true, false);
auto delete_store = std::make_shared<DeleteStore>("fts_delete_test");
Version v1;
v1.set_schema(*schema_);
std::string v_path = seg_path_ + "/manifest";
FileHelper::CreateDirectory(v_path);
auto vm = VersionManager::Create(v_path, v1);
ASSERT_TRUE(vm.has_value());
BlockMeta mem_block;
mem_block.id_ = 0;
mem_block.type_ = BlockType::SCALAR;
mem_block.min_doc_id_ = 0;
mem_block.max_doc_id_ = 0;
mem_block.doc_count_ = 0;
segment_meta->set_writing_forward_block(mem_block);
SegmentOptions options;
options.read_only_ = false;
options.enable_mmap_ = true;
options.max_buffer_size_ = 256 * 1024;
auto result = Segment::CreateAndOpen(seg_path_, *schema_, 0, 0, id_map,
delete_store, vm.value(), options);
ASSERT_TRUE(result.has_value());
segment_ = result.value();
segments_.push_back(segment_);
engine_ = SQLEngine::create(std::make_shared<Profiler>());
insert_docs();
}
void TearDown() override {
segments_.clear();
segment_.reset();
engine_.reset();
schema_.reset();
FileHelper::RemoveDirectory(seg_path_);
}
void insert_docs() {
// doc_id 0: "apple banana cherry" tag=1
// doc_id 1: "banana date elderberry" tag=2
// doc_id 2: "cherry fig grape" tag=1
// doc_id 3: "apple fig honeydew" tag=2
// doc_id 4: "date grape kiwi" tag=1
struct Entry {
std::string content;
int32_t tag;
};
std::vector<Entry> entries = {
{"apple banana cherry", 1}, {"banana date elderberry", 2},
{"cherry fig grape", 1}, {"apple fig honeydew", 2},
{"date grape kiwi", 1},
};
for (size_t i = 0; i < entries.size(); ++i) {
Doc doc;
doc.set_pk("pk_" + std::to_string(i));
doc.set_doc_id(i);
doc.set<std::string>("content", entries[i].content);
doc.set<int32_t>("tag", entries[i].tag);
auto status = segment_->Insert(doc);
ASSERT_TRUE(status.ok())
<< "Insert doc " << i << " failed: " << status.c_str();
}
}
Result<DocPtrList> fts_search(const std::string &query_string,
int topk = 10) {
SearchQuery vq;
vq.topk_ = topk;
vq.target_.field_name_ = "content";
FtsClause fts;
fts.query_string_ = query_string;
vq.target_.clause_ = fts;
return engine_->execute(schema_, vq, segments_);
}
std::set<std::string> collect_pks(const DocPtrList &docs) {
std::set<std::string> pks;
for (const auto &d : docs) {
pks.insert(d->pk());
}
return pks;
}
std::string seg_path_;
CollectionSchema::Ptr schema_;
Segment::Ptr segment_;
std::vector<Segment::Ptr> segments_;
SQLEngine::Ptr engine_;
};
// Delete doc 0 ("apple banana cherry"), then search "apple":
// before: {0, 3}, after: {3} only.
TEST_F(FtsRecallDeleteTest, DeletedDocExcludedFromSearch) {
auto before = fts_search("apple");
ASSERT_TRUE(before.has_value()) << before.error().c_str();
EXPECT_TRUE(collect_pks(*before).count("pk_0"));
auto s = segment_->Delete("pk_0");
ASSERT_TRUE(s.ok()) << s.c_str();
auto after = fts_search("apple");
ASSERT_TRUE(after.has_value()) << after.error().c_str();
auto pks = collect_pks(*after);
EXPECT_FALSE(pks.count("pk_0"));
EXPECT_TRUE(pks.count("pk_3"));
}
// Delete all docs matching "banana" (0, 1), verify "banana" returns empty.
TEST_F(FtsRecallDeleteTest, DeleteAllMatchingDocsReturnsEmpty) {
auto s1 = segment_->Delete("pk_0");
ASSERT_TRUE(s1.ok()) << s1.c_str();
auto s2 = segment_->Delete("pk_1");
ASSERT_TRUE(s2.ok()) << s2.c_str();
auto result = fts_search("banana");
ASSERT_TRUE(result.has_value()) << result.error().c_str();
EXPECT_TRUE(result->empty());
}
// Upsert doc 0 with new content, verify old content no longer matches
// and new content is searchable.
TEST_F(FtsRecallDeleteTest, UpsertUpdatesSearchableContent) {
// Before: "apple" matches {0, 3}
auto before = fts_search("apple");
ASSERT_TRUE(before.has_value()) << before.error().c_str();
EXPECT_EQ(before->size(), 2u);
// Upsert pk_0 with completely different content
Doc updated;
updated.set_pk("pk_0");
updated.set<std::string>("content", "mango pineapple watermelon");
updated.set<int32_t>("tag", 1);
auto s = segment_->Upsert(updated);
ASSERT_TRUE(s.ok()) << s.c_str();
// "apple" should now only match doc 3
auto after_apple = fts_search("apple");
ASSERT_TRUE(after_apple.has_value()) << after_apple.error().c_str();
ASSERT_EQ(after_apple->size(), 1u);
EXPECT_EQ((*after_apple)[0]->pk(), "pk_3");
// "pineapple" should match the upserted doc
auto after_new = fts_search("pineapple");
ASSERT_TRUE(after_new.has_value()) << after_new.error().c_str();
ASSERT_EQ(after_new->size(), 1u);
EXPECT_EQ((*after_new)[0]->pk(), "pk_0");
}
// Delete a doc, then search with AND: "cherry AND fig" was {2},
// delete doc 2 → empty.
TEST_F(FtsRecallDeleteTest, DeleteAffectsConjunctionQuery) {
auto before = fts_search("cherry AND fig");
ASSERT_TRUE(before.has_value()) << before.error().c_str();
ASSERT_EQ(before->size(), 1u);
EXPECT_EQ((*before)[0]->pk(), "pk_2");
auto s = segment_->Delete("pk_2");
ASSERT_TRUE(s.ok()) << s.c_str();
auto after = fts_search("cherry AND fig");
ASSERT_TRUE(after.has_value()) << after.error().c_str();
EXPECT_TRUE(after->empty());
}
// Delete a doc, flush, then verify deleted doc stays excluded.
TEST_F(FtsRecallDeleteTest, DeletePersistsAcrossFlush) {
auto s = segment_->Delete("pk_4");
ASSERT_TRUE(s.ok()) << s.c_str();
auto flush_s = segment_->flush();
ASSERT_TRUE(flush_s.ok()) << flush_s.c_str();
auto result = fts_search("kiwi");
ASSERT_TRUE(result.has_value()) << result.error().c_str();
EXPECT_TRUE(result->empty());
}
} // namespace zvec::sqlengine
+11
View File
@@ -499,6 +499,17 @@ class MockSegment : public Segment {
return {};
}
fts::FtsColumnIndexerPtr get_fts_indexer(
const std::string &field_name) const override {
return nullptr;
}
Result<std::vector<fts::FtsResult>> fts_search(
const std::string &field_name, const fts::FtsAstNode &ast,
const fts::FtsQueryParams &params) override {
return std::vector<fts::FtsResult>{};
}
Status flush() override {
return Status::OK();
}