feat: migrate multi-vector query and reranker logic to C++ (#405)

* feat: migrate multi-vector query and reranker logic to C++

- Add Reranker base class with RrfReRanker and WeightedReRanker implementations
- Add Collection::MultiQuery interface for multi-vector queries with reranking
- Add MultiVectorQuery struct in doc.h with forward declaration for Reranker
- Add C API bindings for reranker and MultiQuery (zvec_reranker_*, zvec_multi_vector_query_*, zvec_collection_multi_query)
- Add Python binding for reranker classes with py::function bridge for callback
- Validate duplicate field names in multi-vector queries (C++ and Python consistent)
- Remove TODO comment about concurrent execution (SQLEngine is not thread-safe)
- Update collection.h MultiQuery doc comment from concurrently to sequentially
- Add C++ collection tests (6 MultiQuery test cases)
- Add C API tests (reranker functions + multi_vector_query end-to-end)
- Implement Python test cases (11 previously skipped tests now active)
- Simplify Python query_executor validation for unified duplicate field check

* style: format Python files with ruff

* fix: adapt to main branch API changes (VectorQuery->Query rename, validate_and_sanitize)

* fix: multi_vector tests now use multiple same-type vector fields (dense2, sparse2)

* fix: suppress RET501 for intentional default return None in RerankFunction._get_object

* style: ruff format test_collection.py

* refact multi vector query

* format code

* fix(multi-vector): expose SubVectorQuery in Python binding, fix tests

- Register _SubVectorQuery in pybind11 with from_vector_query() factory
- Convert _VectorQuery to _SubVectorQuery in MultiVectorQueryExecutor
- Relax RRF/Weighted score assertion tolerance from 1e-10 to 1e-6
- Fix WeightedReRanker test metric to IP (matching HnswIndexParam default)

* style: ruff format query_executor.py

* fix: define _USE_MATH_DEFINES for M_PI on Windows (MSVC)

* refactor: include reranker.h directly in query.h instead of forward declaration

* refactor(reranker): move topn from member variable to rerank() parameter

* refact code

* style(python): fix ruff UP035/UP037 in multi_vector_reranker

- import Callable from collections.abc instead of typing (UP035)
- remove redundant quotes around MetricType annotations (UP037)

* chore: trigger PR sync

* refact code

* fix(examples): restore CMakeLists.txt formatting broken by clang-format

* refactor(reranker): remove redundant metrics_ map by querying schema directly, and use insert return value to avoid duplicate set lookup

* refactor(reranker): defer schema binding to query time and remove C API callback reranker
This commit is contained in:
lichen2015
2026-05-29 10:10:41 +08:00
committed by GitHub
parent e0ba23179b
commit f539580138
30 changed files with 2740 additions and 115 deletions
+394
View File
@@ -27,12 +27,14 @@
#include <memory>
#include <mutex>
#include <string>
#include <unordered_map>
#include <vector>
#include <zvec/db/collection.h>
#include <zvec/db/config.h>
#include <zvec/db/doc.h>
#include <zvec/db/index_params.h>
#include <zvec/db/options.h>
#include <zvec/db/reranker.h>
#include <zvec/db/schema.h>
#include <zvec/db/stats.h>
@@ -5340,6 +5342,363 @@ zvec_error_code_t zvec_group_by_vector_query_set_flat_params(
return ZVEC_OK;
}
// =============================================================================
// Reranker Implementation
// =============================================================================
zvec_reranker_t *zvec_reranker_create_rrf(int rank_constant) {
ZVEC_TRY_RETURN_NULL("Failed to create RRF Reranker",
auto *reranker =
new zvec::Reranker::Ptr(
std::make_shared<zvec::RrfReranker>(
rank_constant));
return reinterpret_cast<zvec_reranker_t *>(reranker);)
return nullptr;
}
zvec_reranker_t *zvec_reranker_create_weighted(const char **fields,
const double *weights,
size_t field_count) {
if ((!fields || !weights) && field_count > 0) {
set_last_error(
"Fields and weights pointers cannot be null when field_count > 0");
return nullptr;
}
ZVEC_TRY_RETURN_NULL(
"Failed to create Weighted Reranker",
std::map<std::string, double> weight_map;
for (size_t i = 0; i < field_count; ++i) {
if (!fields[i]) {
set_last_error("Null field name at index " + std::to_string(i));
return nullptr;
}
weight_map[fields[i]] = weights[i];
}
auto *reranker = new zvec::Reranker::Ptr(
std::make_shared<zvec::WeightedReranker>(weight_map));
return reinterpret_cast<zvec_reranker_t *>(reranker);)
return nullptr;
}
void zvec_reranker_destroy(zvec_reranker_t *reranker) {
if (reranker) {
delete reinterpret_cast<zvec::Reranker::Ptr *>(reranker);
}
}
int zvec_reranker_get_rank_constant(const zvec_reranker_t *reranker) {
if (!reranker) return -1;
auto *ptr = reinterpret_cast<const zvec::Reranker::Ptr *>(reranker);
auto *rrf = dynamic_cast<const zvec::RrfReranker *>(ptr->get());
return rrf ? rrf->rank_constant() : -1;
}
// =============================================================================
// MultiVectorQuery Implementation
// =============================================================================
zvec_multi_query_t *zvec_multi_query_create(void) {
ZVEC_TRY_RETURN_NULL("Failed to create MultiVectorQuery",
auto *query = new zvec::MultiQuery();
return reinterpret_cast<zvec_multi_query_t *>(
query);)
return nullptr;
}
void zvec_multi_query_destroy(zvec_multi_query_t *query) {
if (query) {
delete reinterpret_cast<zvec::MultiQuery *>(query);
}
}
zvec_error_code_t zvec_multi_query_add_sub_query(
zvec_multi_query_t *query,
const zvec_sub_query_t *sub_query) {
if (!query || !sub_query) {
SET_LAST_ERROR(ZVEC_ERROR_INVALID_ARGUMENT,
"Query or sub_query pointer is null");
return ZVEC_ERROR_INVALID_ARGUMENT;
}
auto *mvq = reinterpret_cast<zvec::MultiQuery *>(query);
auto *sub = reinterpret_cast<const zvec::SubQuery *>(sub_query);
mvq->queries.push_back(*sub);
return ZVEC_OK;
}
size_t zvec_multi_query_get_sub_query_count(
const zvec_multi_query_t *query) {
if (!query) return 0;
auto *mvq = reinterpret_cast<const zvec::MultiQuery *>(query);
return mvq->queries.size();
}
zvec_error_code_t zvec_multi_query_set_topk(
zvec_multi_query_t *query, int topk) {
if (!query) {
SET_LAST_ERROR(ZVEC_ERROR_INVALID_ARGUMENT,
"Multi-vector query pointer is null");
return ZVEC_ERROR_INVALID_ARGUMENT;
}
auto *mvq = reinterpret_cast<zvec::MultiQuery *>(query);
mvq->topk = topk;
return ZVEC_OK;
}
int zvec_multi_query_get_topk(
const zvec_multi_query_t *query) {
if (!query) return 0;
auto *mvq = reinterpret_cast<const zvec::MultiQuery *>(query);
return mvq->topk;
}
zvec_error_code_t zvec_multi_query_set_filter(
zvec_multi_query_t *query, const char *filter) {
if (!query || !filter) {
SET_LAST_ERROR(ZVEC_ERROR_INVALID_ARGUMENT,
"Query or filter pointer is null");
return ZVEC_ERROR_INVALID_ARGUMENT;
}
auto *mvq = reinterpret_cast<zvec::MultiQuery *>(query);
mvq->filter = std::string(filter);
return ZVEC_OK;
}
const char *zvec_multi_query_get_filter(
const zvec_multi_query_t *query) {
if (!query) return nullptr;
auto *mvq = reinterpret_cast<const zvec::MultiQuery *>(query);
return mvq->filter.c_str();
}
zvec_error_code_t zvec_multi_query_set_include_vector(
zvec_multi_query_t *query, bool include) {
if (!query) {
SET_LAST_ERROR(ZVEC_ERROR_INVALID_ARGUMENT,
"Multi-vector query pointer is null");
return ZVEC_ERROR_INVALID_ARGUMENT;
}
auto *mvq = reinterpret_cast<zvec::MultiQuery *>(query);
mvq->include_vector = include;
return ZVEC_OK;
}
bool zvec_multi_query_get_include_vector(
const zvec_multi_query_t *query) {
if (!query) return false;
auto *mvq = reinterpret_cast<const zvec::MultiQuery *>(query);
return mvq->include_vector;
}
zvec_error_code_t zvec_multi_query_set_output_fields(
zvec_multi_query_t *query, const char **fields, size_t count) {
if (!query || (!fields && count > 0)) {
SET_LAST_ERROR(ZVEC_ERROR_INVALID_ARGUMENT,
"Query pointer is null or fields is null with count > 0");
return ZVEC_ERROR_INVALID_ARGUMENT;
}
auto *mvq = reinterpret_cast<zvec::MultiQuery *>(query);
std::vector<std::string> field_vec;
field_vec.reserve(count);
for (size_t i = 0; i < count; ++i) {
if (!fields[i]) {
SET_LAST_ERROR(ZVEC_ERROR_INVALID_ARGUMENT,
"Null field name at index " + std::to_string(i));
return ZVEC_ERROR_INVALID_ARGUMENT;
}
field_vec.emplace_back(fields[i]);
}
mvq->output_fields = std::move(field_vec);
return ZVEC_OK;
}
zvec_error_code_t zvec_multi_query_get_output_fields(
zvec_multi_query_t *query, const char ***fields, size_t *count) {
if (!query || !fields || !count) {
SET_LAST_ERROR(ZVEC_ERROR_INVALID_ARGUMENT,
"Query, fields or count pointer is null");
return ZVEC_ERROR_INVALID_ARGUMENT;
}
auto *mvq = reinterpret_cast<zvec::MultiQuery *>(query);
if (!mvq->output_fields.has_value() || mvq->output_fields->empty()) {
*fields = nullptr;
*count = 0;
return ZVEC_OK;
}
const auto &field_vec = mvq->output_fields.value();
*count = field_vec.size();
*fields = static_cast<const char **>(malloc(*count * sizeof(const char *)));
if (!*fields) {
SET_LAST_ERROR(ZVEC_ERROR_INTERNAL_ERROR, "Failed to allocate memory");
return ZVEC_ERROR_INTERNAL_ERROR;
}
for (size_t i = 0; i < *count; ++i) {
(*fields)[i] = field_vec[i].c_str();
}
return ZVEC_OK;
}
zvec_error_code_t zvec_multi_query_set_reranker(
zvec_multi_query_t *query, zvec_reranker_t *reranker) {
if (!query || !reranker) {
SET_LAST_ERROR(ZVEC_ERROR_INVALID_ARGUMENT,
"Query or reranker pointer is null");
return ZVEC_ERROR_INVALID_ARGUMENT;
}
auto *mvq = reinterpret_cast<zvec::MultiQuery *>(query);
auto *reranker_ptr =
reinterpret_cast<zvec::Reranker::Ptr *>(reranker);
mvq->reranker = *reranker_ptr;
return ZVEC_OK;
}
// =============================================================================
// SubVectorQuery Implementation
// =============================================================================
zvec_sub_query_t *zvec_sub_query_create(void) {
ZVEC_TRY_RETURN_NULL("Failed to create SubVectorQuery",
auto *query = new zvec::SubQuery();
query->num_candidates_ = 10;
return reinterpret_cast<zvec_sub_query_t *>(
query);)
return nullptr;
}
void zvec_sub_query_destroy(zvec_sub_query_t *query) {
if (query) {
delete reinterpret_cast<zvec::SubQuery *>(query);
}
}
zvec_error_code_t zvec_sub_query_set_num_candidates(
zvec_sub_query_t *query, int num_candidates) {
if (!query) {
SET_LAST_ERROR(ZVEC_ERROR_INVALID_ARGUMENT,
"Sub-vector query pointer is null");
return ZVEC_ERROR_INVALID_ARGUMENT;
}
auto *ptr = reinterpret_cast<zvec::SubQuery *>(query);
ptr->num_candidates_ = num_candidates;
return ZVEC_OK;
}
int zvec_sub_query_get_num_candidates(
const zvec_sub_query_t *query) {
if (!query) return 0;
auto *ptr = reinterpret_cast<const zvec::SubQuery *>(query);
return ptr->num_candidates_;
}
zvec_error_code_t zvec_sub_query_set_field_name(
zvec_sub_query_t *query, const char *field_name) {
if (!query || !field_name) {
SET_LAST_ERROR(ZVEC_ERROR_INVALID_ARGUMENT,
"Sub-vector query or field_name pointer is null");
return ZVEC_ERROR_INVALID_ARGUMENT;
}
auto *ptr = reinterpret_cast<zvec::SubQuery *>(query);
ptr->target_.field_name_ = std::string(field_name);
return ZVEC_OK;
}
const char *zvec_sub_query_get_field_name(
const zvec_sub_query_t *query) {
if (!query) return nullptr;
auto *ptr = reinterpret_cast<const zvec::SubQuery *>(query);
return ptr->target_.field_name_.c_str();
}
zvec_error_code_t zvec_sub_query_set_query_vector(
zvec_sub_query_t *query, const void *data, size_t size) {
if (!query || !data || size == 0) {
SET_LAST_ERROR(ZVEC_ERROR_INVALID_ARGUMENT,
"Sub-vector query pointer or data is null/empty");
return ZVEC_ERROR_INVALID_ARGUMENT;
}
auto *ptr = reinterpret_cast<zvec::SubQuery *>(query);
auto &payload = std::get<zvec::VectorClause>(ptr->target_.clause_);
payload.query_vector_.assign(static_cast<const char *>(data), size);
return ZVEC_OK;
}
zvec_error_code_t zvec_sub_query_set_sparse_indices(
zvec_sub_query_t *query, const uint32_t *indices, size_t count) {
if (!query || (!indices && count > 0)) {
SET_LAST_ERROR(ZVEC_ERROR_INVALID_ARGUMENT,
"Sub-vector query or indices pointer is null");
return ZVEC_ERROR_INVALID_ARGUMENT;
}
auto *ptr = reinterpret_cast<zvec::SubQuery *>(query);
auto &payload = std::get<zvec::VectorClause>(ptr->target_.clause_);
payload.sparse_indices_.assign(
reinterpret_cast<const char *>(indices), count * sizeof(uint32_t));
return ZVEC_OK;
}
zvec_error_code_t zvec_sub_query_set_sparse_values(
zvec_sub_query_t *query, const float *values, size_t count) {
if (!query || (!values && count > 0)) {
SET_LAST_ERROR(ZVEC_ERROR_INVALID_ARGUMENT,
"Sub-vector query or values pointer is null");
return ZVEC_ERROR_INVALID_ARGUMENT;
}
auto *ptr = reinterpret_cast<zvec::SubQuery *>(query);
auto &payload = std::get<zvec::VectorClause>(ptr->target_.clause_);
payload.sparse_values_.assign(
reinterpret_cast<const char *>(values), count * sizeof(float));
return ZVEC_OK;
}
zvec_error_code_t zvec_sub_query_set_hnsw_params(
zvec_sub_query_t *query, zvec_hnsw_query_params_t *hnsw_params) {
if (!query || !hnsw_params) {
SET_LAST_ERROR(ZVEC_ERROR_INVALID_ARGUMENT,
"Sub-vector query or HNSW params pointer is null");
return ZVEC_ERROR_INVALID_ARGUMENT;
}
auto *ptr = reinterpret_cast<zvec::SubQuery *>(query);
auto *params_ptr = reinterpret_cast<zvec::HnswQueryParams *>(hnsw_params);
ptr->target_.query_params_.reset(params_ptr);
return ZVEC_OK;
}
zvec_error_code_t zvec_sub_query_set_ivf_params(
zvec_sub_query_t *query, zvec_ivf_query_params_t *ivf_params) {
if (!query || !ivf_params) {
SET_LAST_ERROR(ZVEC_ERROR_INVALID_ARGUMENT,
"Sub-vector query or IVF params pointer is null");
return ZVEC_ERROR_INVALID_ARGUMENT;
}
auto *ptr = reinterpret_cast<zvec::SubQuery *>(query);
auto *params_ptr = reinterpret_cast<zvec::IVFQueryParams *>(ivf_params);
ptr->target_.query_params_.reset(params_ptr);
return ZVEC_OK;
}
zvec_error_code_t zvec_sub_query_set_flat_params(
zvec_sub_query_t *query, zvec_flat_query_params_t *flat_params) {
if (!query || !flat_params) {
SET_LAST_ERROR(ZVEC_ERROR_INVALID_ARGUMENT,
"Sub-vector query or Flat params pointer is null");
return ZVEC_ERROR_INVALID_ARGUMENT;
}
auto *ptr = reinterpret_cast<zvec::SubQuery *>(query);
auto *params_ptr = reinterpret_cast<zvec::FlatQueryParams *>(flat_params);
ptr->target_.query_params_.reset(params_ptr);
return ZVEC_OK;
}
// =============================================================================
// Index Interface Implementation
// =============================================================================
@@ -5998,6 +6357,41 @@ zvec_error_code_t zvec_collection_query(const zvec_collection_t *collection,
return error_code;)
}
zvec_error_code_t zvec_collection_multi_query(
const zvec_collection_t *collection,
const zvec_multi_query_t *query,
zvec_doc_t ***results, size_t *result_count) {
if (!collection || !query || !results || !result_count) {
set_last_error(
"Invalid arguments: collection, query, results and result_count "
"cannot be null");
return ZVEC_ERROR_INVALID_ARGUMENT;
}
ZVEC_TRY_RETURN_ERROR(
"Exception occurred",
auto coll_ptr =
reinterpret_cast<const std::shared_ptr<zvec::Collection> *>(
collection);
auto *internal_query =
reinterpret_cast<const zvec::MultiQuery *>(query);
auto result = (*coll_ptr)->Query(*internal_query);
zvec_error_code_t error_code = handle_expected_result(result);
if (error_code == ZVEC_OK) {
const auto &query_results = result.value();
error_code =
convert_document_results(query_results, results, result_count);
} else {
*results = nullptr;
*result_count = 0;
}
return error_code;)
}
zvec_error_code_t zvec_collection_fetch(zvec_collection_t *collection,
const char *const *pks, size_t pk_count,
const char *const *output_fields,
+1
View File
@@ -10,6 +10,7 @@ set(SRC_LISTS
binding.cc
model/python_collection.cc
model/python_doc.cc
model/python_reranker.cc
model/param/python_param.cc
model/schema/python_schema.cc
model/common/python_config.cc
+2
View File
@@ -16,6 +16,7 @@
#include "python_config.h"
#include "python_doc.h"
#include "python_param.h"
#include "python_reranker.h"
#include "python_schema.h"
#include "python_type.h"
@@ -26,6 +27,7 @@ PYBIND11_MODULE(_zvec, m) {
ZVecPyTyping::Initialize(m);
ZVecPyParams::Initialize(m);
ZVecPySchemas::Initialize(m);
ZVecPyReranker::Initialize(m);
ZVecPyConfig::Initialize(m);
ZVecPyDoc::Initialize(m);
ZVecPyCollection::Initialize(m);
@@ -0,0 +1,31 @@
// 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 <pybind11/pybind11.h>
#include <zvec/db/reranker.h>
namespace py = pybind11;
namespace zvec {
class ZVecPyReranker {
public:
ZVecPyReranker() = delete;
public:
static void Initialize(py::module_ &m);
};
} // namespace zvec
@@ -17,6 +17,7 @@
#include <pybind11/stl.h>
#include <zvec/core/interface/constants.h>
#include <zvec/db/index_params.h>
#include <zvec/db/query.h>
#include "python_doc.h"
namespace zvec {
@@ -1372,6 +1373,25 @@ Args:
}
void ZVecPyParams::bind_vector_query(py::module_ &m) {
// Bind SubQuery (used by MultiQuery)
py::class_<SubQuery>(m, "_SubQuery")
.def(py::init<>())
.def_readwrite("num_candidates", &SubQuery::num_candidates_)
.def_static(
"from_vector_query",
[](const VectorQuery &vq) {
SubQuery sub;
sub.num_candidates_ = vq.topk_;
sub.target_.field_name_ = vq.field_name_;
auto &clause = std::get<VectorClause>(sub.target_.clause_);
clause.query_vector_ = vq.query_vector_;
clause.sparse_indices_ = vq.query_sparse_indices_;
clause.sparse_values_ = vq.query_sparse_values_;
sub.target_.query_params_ = vq.query_params_;
return sub;
},
py::arg("vector_query"), "Create a SubQuery from a VectorQuery");
py::class_<VectorQuery>(m, "_VectorQuery")
.def(py::init<>())
// properties
@@ -261,6 +261,19 @@ void ZVecPyCollection::bind_dql_methods(
// return DocPtrList
return unwrap_expected(result);
})
// MultiQuery: multi query with reranker
.def(
"Query",
[](const Collection &self, const MultiQuery &query) {
Result<DocPtrList> result;
{
py::gil_scoped_release release;
result = self.Query(query);
}
// return DocPtrList
return unwrap_expected(result);
},
py::arg("query"), "Execute a multi query with re-ranking.")
.def("GroupByQuery",
[](const Collection &self, const GroupByVectorQuery &query) {
Result<GroupResults> result;
@@ -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.
#include "python_reranker.h"
#include <pybind11/functional.h>
#include <pybind11/stl.h>
#include <zvec/db/collection.h>
#include <zvec/db/type.h>
namespace zvec {
void ZVecPyReranker::Initialize(py::module_ &m) {
// Bind Reranker base class (abstract, cannot be instantiated directly)
py::class_<Reranker, Reranker::Ptr>(m, "_Reranker");
// Bind ScoreBasedReranker intermediate class
py::class_<ScoreBasedReranker, Reranker, std::shared_ptr<ScoreBasedReranker>>(
m, "_ScoreBasedReranker");
// Bind RrfReranker
py::class_<RrfReranker, ScoreBasedReranker, std::shared_ptr<RrfReranker>>(
m, "_RrfReranker")
.def(py::init<int>(), py::arg("rank_constant") = 60)
.def_property_readonly("rank_constant", &RrfReranker::rank_constant);
// Bind WeightedReranker
py::class_<WeightedReranker, ScoreBasedReranker,
std::shared_ptr<WeightedReranker>>(m, "_WeightedReranker")
.def(py::init<std::map<std::string, double>>(), py::arg("weights"))
.def_property_readonly("weights", &WeightedReranker::weights);
// Bind CallbackReranker
py::class_<CallbackReranker, Reranker, std::shared_ptr<CallbackReranker>>(
m, "_CallbackReranker")
.def(py::init<CallbackReranker::Callback>(), py::arg("callback"));
// Bind MultiQuery struct
py::class_<MultiQuery>(m, "_MultiQuery")
.def(py::init<>())
.def_readwrite("queries", &MultiQuery::queries)
.def_readwrite("topk", &MultiQuery::topk)
.def_readwrite("filter", &MultiQuery::filter)
.def_readwrite("include_vector", &MultiQuery::include_vector)
.def_readwrite("output_fields", &MultiQuery::output_fields)
.def_readwrite("reranker", &MultiQuery::reranker);
}
} // namespace zvec
+85
View File
@@ -15,8 +15,10 @@
#include <atomic>
#include <cstdint>
#include <filesystem>
#include <future>
#include <memory>
#include <mutex>
#include <set>
#include <shared_mutex>
#include <string>
#include <variant>
@@ -29,6 +31,7 @@
#include <zvec/db/collection.h>
#include <zvec/db/doc.h>
#include <zvec/db/options.h>
#include <zvec/db/reranker.h>
#include <zvec/db/schema.h>
#include <zvec/db/status.h>
#include "db/common/constants.h"
@@ -117,6 +120,8 @@ class CollectionImpl : public Collection {
Result<DocPtrList> Query(const VectorQuery &query) const override;
Result<DocPtrList> Query(const MultiQuery &query) const override;
Result<GroupResults> GroupByQuery(
const GroupByVectorQuery &query) const override;
@@ -1597,6 +1602,86 @@ Result<DocPtrList> CollectionImpl::Query(const VectorQuery &query) const {
return sql_engine_->execute(schema_, sanitized, segments);
}
Result<DocPtrList> CollectionImpl::Query(const MultiQuery &query) const {
std::shared_lock lock(schema_handle_mtx_);
CHECK_DESTROY_RETURN_STATUS_EXPECTED(destroyed_, false);
if (query.queries.size() < 2) {
return tl::make_unexpected(
Status::InvalidArgument("Query requires at least 2 sub-queries"));
}
if (!query.reranker) {
return tl::make_unexpected(
Status::InvalidArgument("Reranker is required for multi-vector query"));
}
auto segments = get_all_segments();
if (segments.empty()) {
return DocPtrList();
}
// Convert SubVectorQuery to VectorQuery and validate
std::set<std::string> seen_fields;
std::vector<VectorQuery> converted_queries;
converted_queries.reserve(query.queries.size());
for (const auto &sub : query.queries) {
const auto &target = sub.target_;
auto [_, inserted] = seen_fields.insert(target.field_name_);
if (!inserted) {
return tl::make_unexpected(Status::InvalidArgument(
"Duplicate field name in multi-vector query: ", target.field_name_));
}
auto *field_schema = schema_->get_vector_field(target.field_name_);
if (!field_schema) {
return tl::make_unexpected(Status::InvalidArgument(
"Vector field not found: ", target.field_name_));
}
VectorQuery vq;
vq.topk_ = sub.num_candidates_;
vq.field_name_ = target.field_name_;
const auto &vec_clause = std::get<VectorClause>(target.clause_);
vq.query_vector_ = vec_clause.query_vector_;
vq.query_sparse_indices_ = vec_clause.sparse_indices_;
vq.query_sparse_values_ = vec_clause.sparse_values_;
vq.query_params_ = target.query_params_;
vq.filter_ = query.filter;
vq.include_vector_ = query.include_vector;
vq.include_doc_id_ = query.include_doc_id_;
vq.output_fields_ = query.output_fields;
auto s = vq.validate_and_sanitize(field_schema);
CHECK_RETURN_STATUS_EXPECTED(s);
converted_queries.push_back(std::move(vq));
}
// Execute each VectorQuery concurrently and collect results per field
std::vector<std::future<Result<DocPtrList>>> futures;
futures.reserve(converted_queries.size());
for (const auto &vq : converted_queries) {
futures.push_back(std::async(std::launch::async, [&]() {
auto engine = sqlengine::SQLEngine::create(std::make_shared<Profiler>());
return engine->execute(schema_, vq, segments);
}));
}
std::map<std::string, DocPtrList> query_results;
for (size_t i = 0; i < converted_queries.size(); ++i) {
auto result = futures[i].get();
if (!result.has_value()) {
return tl::make_unexpected(result.error());
}
query_results[converted_queries[i].field_name_] = std::move(result.value());
}
// Merge and rerank results
query.reranker->bind_schema(schema_);
return query.reranker->rerank(query_results, query.topk);
}
Result<GroupResults> CollectionImpl::GroupByQuery(
const GroupByVectorQuery &query) const {
std::shared_lock lock(schema_handle_mtx_);
+1
View File
@@ -22,6 +22,7 @@
#include <stdexcept>
#include <zvec/ailego/internal/platform.h>
#include <zvec/db/doc.h>
#include <zvec/db/query.h>
#include "db/common/constants.h"
#include "db/index/common/type_helper.h"
+138
View File
@@ -0,0 +1,138 @@
// 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 <algorithm>
#include "zvec/db/status.h"
#define _USE_MATH_DEFINES
#include <cmath>
#include <queue>
#include <unordered_map>
#include <utility>
#include <zvec/ailego/logger/logger.h>
#include <zvec/db/index_params.h>
#include <zvec/db/reranker.h>
namespace zvec {
// ==================== ScoreBasedReranker ====================
Result<DocPtrList> ScoreBasedReranker::rerank(
const std::map<std::string, DocPtrList> &query_results, int topn) const {
std::unordered_map<std::string, double> scores;
std::unordered_map<std::string, Doc::Ptr> id_to_doc;
for (const auto &[field_name, docs] : query_results) {
for (size_t rank = 0; rank < docs.size(); ++rank) {
const auto &doc = docs[rank];
const std::string &doc_id = doc->pk();
auto rs = rescore(static_cast<double>(doc->score()),
static_cast<int>(rank), field_name);
if (!rs.has_value()) {
return tl::make_unexpected(rs.error());
}
scores[doc_id] += rs.value();
if (id_to_doc.find(doc_id) == id_to_doc.end()) {
id_to_doc[doc_id] = doc;
}
}
}
using ScorePair = std::pair<std::string, double>;
auto cmp = [](const ScorePair &a, const ScorePair &b) {
return a.second > b.second;
};
std::priority_queue<ScorePair, std::vector<ScorePair>, decltype(cmp)> pq(cmp);
for (const auto &[doc_id, score] : scores) {
if (static_cast<int>(pq.size()) < topn) {
pq.emplace(doc_id, score);
} else if (score > pq.top().second) {
pq.pop();
pq.emplace(doc_id, score);
}
}
DocPtrList results;
results.reserve(pq.size());
while (!pq.empty()) {
const auto &[doc_id, score] = pq.top();
auto doc = std::move(id_to_doc[doc_id]);
doc->set_score(static_cast<float>(score));
results.push_back(std::move(doc));
pq.pop();
}
std::reverse(results.begin(), results.end());
return results;
}
// ==================== RrfReranker ====================
Result<double> RrfReranker::rescore(double /*score*/, int rank,
const std::string & /*field_name*/) const {
return 1.0 / (static_cast<double>(rank_constant_) +
static_cast<double>(rank) + 1.0);
}
// ==================== WeightedReranker ====================
WeightedReranker::WeightedReranker(const std::map<std::string, double> &weights)
: weights_(weights) {}
void WeightedReranker::bind_schema(CollectionSchema::Ptr schema) {
schema_ = std::move(schema);
}
Result<double> WeightedReranker::normalize_score(double score,
const FieldSchema &field) {
auto *vip =
dynamic_cast<const VectorIndexParams *>(field.index_params().get());
if (!vip) {
return tl::make_unexpected(
Status::InvalidArgument("WeightedReranker: field '", field.name(),
"' has no vector index params"));
}
switch (vip->metric_type()) {
case MetricType::L2:
return 1.0 - 2.0 * std::atan(score) / M_PI;
case MetricType::IP:
return 0.5 + std::atan(score) / M_PI;
case MetricType::COSINE:
return 1.0 - score / 2.0;
default:
return tl::make_unexpected(Status::InvalidArgument(
"Unsupported metric type for normalization: ",
std::to_string(static_cast<int>(vip->metric_type()))));
}
}
Result<double> WeightedReranker::rescore(double score, int /*rank*/,
const std::string &field_name) const {
const auto *field = schema_->get_vector_field(field_name);
if (!field) {
return tl::make_unexpected(Status::InvalidArgument(
"WeightedReranker: vector field not found: '", field_name + "'"));
}
auto normalized = normalize_score(score, *field);
if (!normalized.has_value()) {
return tl::make_unexpected(normalized.error());
}
double weight = 1.0;
auto weight_it = weights_.find(field_name);
if (weight_it != weights_.end()) {
weight = weight_it->second;
}
return normalized.value() * weight;
}
} // namespace zvec
+1 -1
View File
@@ -14,7 +14,7 @@
#pragma once
#include <zvec/db/doc.h>
#include <zvec/db/query.h>
#include "db/sqlengine/common/group_by.h"
#include "db/sqlengine/parser/node.h"
#include "db/sqlengine/parser/sql_info.h"
+1 -1
View File
@@ -14,7 +14,7 @@
#pragma once
#include <zvec/db/doc.h>
#include <zvec/db/query.h>
#include <zvec/db/status.h>
#include "db/common/profiler.h"
#include "db/index/segment/segment.h"
+1 -1
View File
@@ -18,7 +18,7 @@
#include <memory>
#include <vector>
#include <arrow/api.h>
#include <zvec/db/doc.h>
#include <zvec/db/query.h>
#include <zvec/db/schema.h>
#include "analyzer/query_info.h"
#include "common/group_by.h"
+306 -17
View File
@@ -1032,6 +1032,37 @@ typedef struct zvec_vector_query_t zvec_vector_query_t;
*/
typedef struct zvec_group_by_vector_query_t zvec_group_by_vector_query_t;
/**
* @brief Document object (opaque pointer, forward declaration for reranker
* callback)
*/
typedef struct zvec_doc_t zvec_doc_t;
/**
* @brief Reranker structure (opaque pointer)
* Aligned with zvec::Reranker
* Use zvec_reranker_create_rrf() or zvec_reranker_create_weighted() to create
* and zvec_reranker_destroy() to destroy
*/
typedef struct zvec_reranker_t zvec_reranker_t;
typedef struct zvec_collection_schema_t zvec_collection_schema_t;
/**
* @brief Multi-query query structure (opaque pointer)
* Aligned with zvec::MultiQuery
* Use zvec_multi_query_create() to create and
* zvec_multi_query_destroy() to destroy
*/
typedef struct zvec_multi_query_t zvec_multi_query_t;
/**
* @brief Sub-query structure for multi-query (opaque pointer)
* Aligned with zvec::SubQuery
* Use zvec_sub_query_create() to create and
* zvec_sub_query_destroy() to destroy
*/
typedef struct zvec_sub_query_t zvec_sub_query_t;
// =============================================================================
// Query Parameters Management Functions
@@ -1704,6 +1735,268 @@ ZVEC_EXPORT zvec_error_code_t ZVEC_CALL
zvec_group_by_vector_query_set_flat_params(
zvec_group_by_vector_query_t *query, zvec_flat_query_params_t *flat_params);
// -----------------------------------------------------------------------------
// zvec_reranker_t (Reranker)
// -----------------------------------------------------------------------------
/**
* @brief Create an RRF (Reciprocal Rank Fusion) reranker
* @param rank_constant RRF rank constant (default: 60)
* @return zvec_reranker_t* Pointer to the newly created reranker
*/
ZVEC_EXPORT zvec_reranker_t *ZVEC_CALL
zvec_reranker_create_rrf(int rank_constant);
/**
* @brief Create a Weighted reranker
* @param fields Array of field names
* @param weights Array of weights corresponding to fields
* @param field_count Number of field/weight entries
* @return zvec_reranker_t* Pointer to the newly created reranker
*/
ZVEC_EXPORT zvec_reranker_t *ZVEC_CALL zvec_reranker_create_weighted(
const char **fields, const double *weights, size_t field_count);
/**
* @brief Destroy reranker
* @param reranker Reranker pointer
*/
ZVEC_EXPORT void ZVEC_CALL zvec_reranker_destroy(zvec_reranker_t *reranker);
/**
* @brief Get RRF rank constant (only valid for RRF reranker)
* @param reranker Reranker pointer
* @return int Rank constant, or -1 if not an RRF reranker
*/
ZVEC_EXPORT int ZVEC_CALL
zvec_reranker_get_rank_constant(const zvec_reranker_t *reranker);
// -----------------------------------------------------------------------------
// zvec_multi_query_t (Multi Query)
// -----------------------------------------------------------------------------
/**
* @brief Create multi-query query
* @return zvec_multi_query_t* Pointer to the newly created multi query
*/
ZVEC_EXPORT zvec_multi_query_t *ZVEC_CALL zvec_multi_query_create(void);
/**
* @brief Destroy multi-query query
* @param query Multi query pointer
*/
ZVEC_EXPORT void ZVEC_CALL zvec_multi_query_destroy(zvec_multi_query_t *query);
/**
* @brief Add a sub-query to the multi-query query
* @param query Multi query pointer
* @param sub_query Sub-query to add (copied, caller retains ownership)
* @return zvec_error_code_t Error code
*/
ZVEC_EXPORT zvec_error_code_t ZVEC_CALL zvec_multi_query_add_sub_query(
zvec_multi_query_t *query, const zvec_sub_query_t *sub_query);
/**
* @brief Get number of sub-queries
* @param query Multi query pointer
* @return size_t Number of sub-queries
*/
ZVEC_EXPORT size_t ZVEC_CALL
zvec_multi_query_get_sub_query_count(const zvec_multi_query_t *query);
/**
* @brief Set topk
* @param query Multi-vector query pointer
* @param topk Number of results
* @return zvec_error_code_t Error code
*/
ZVEC_EXPORT zvec_error_code_t ZVEC_CALL
zvec_multi_query_set_topk(zvec_multi_query_t *query, int topk);
/**
* @brief Get topk
* @param query Multi-vector query pointer
* @return int Number of results
*/
ZVEC_EXPORT int ZVEC_CALL
zvec_multi_query_get_topk(const zvec_multi_query_t *query);
/**
* @brief Set filter expression
* @param query Multi-vector query pointer
* @param filter Filter expression string
* @return zvec_error_code_t Error code
*/
ZVEC_EXPORT zvec_error_code_t ZVEC_CALL
zvec_multi_query_set_filter(zvec_multi_query_t *query, const char *filter);
/**
* @brief Get filter expression
* @param query Multi-vector query pointer
* @return const char* Filter expression (owned by query, do not free)
*/
ZVEC_EXPORT const char *ZVEC_CALL
zvec_multi_query_get_filter(const zvec_multi_query_t *query);
/**
* @brief Set whether to include vector data in results
* @param query Multi-vector query pointer
* @param include Whether to include vectors
* @return zvec_error_code_t Error code
*/
ZVEC_EXPORT zvec_error_code_t ZVEC_CALL
zvec_multi_query_set_include_vector(zvec_multi_query_t *query, bool include);
/**
* @brief Get whether to include vector data in results
* @param query Multi-vector query pointer
* @return bool Whether to include vectors
*/
ZVEC_EXPORT bool ZVEC_CALL
zvec_multi_query_get_include_vector(const zvec_multi_query_t *query);
/**
* @brief Set output fields
* @param query Multi-vector query pointer
* @param fields Array of field names
* @param count Number of fields
* @return zvec_error_code_t Error code
*/
ZVEC_EXPORT zvec_error_code_t ZVEC_CALL zvec_multi_query_set_output_fields(
zvec_multi_query_t *query, const char **fields, size_t count);
/**
* @brief Get output fields
* @param query Multi-vector query pointer
* @param[out] fields Output array of field names (allocated by library)
* @param[out] count Number of fields
* @return zvec_error_code_t Error code
*
* @note The returned array is allocated by the library and should be freed
* using zvec_free() when no longer needed. The individual string pointers
* are owned by the query and must NOT be freed.
*/
ZVEC_EXPORT zvec_error_code_t ZVEC_CALL zvec_multi_query_get_output_fields(
zvec_multi_query_t *query, const char ***fields, size_t *count);
/**
* @brief Set reranker (copies shared pointer, caller must still destroy
* reranker)
* @param query Multi-vector query pointer
* @param reranker Reranker pointer (remains valid, caller must call
* zvec_reranker_destroy after use)
* @return zvec_error_code_t Error code
*/
ZVEC_EXPORT zvec_error_code_t ZVEC_CALL zvec_multi_query_set_reranker(
zvec_multi_query_t *query, zvec_reranker_t *reranker);
// -----------------------------------------------------------------------------
// zvec_sub_query_t (Sub-Query for Multi Query)
// -----------------------------------------------------------------------------
/**
* @brief Create sub-query
* @return zvec_sub_query_t* Pointer to the newly created
* sub-query
*/
ZVEC_EXPORT zvec_sub_query_t *ZVEC_CALL zvec_sub_query_create(void);
/**
* @brief Destroy sub-query
* @param query Sub-query pointer
*/
ZVEC_EXPORT void ZVEC_CALL zvec_sub_query_destroy(zvec_sub_query_t *query);
/**
* @brief Set number of candidates to retrieve per field
* @param query Sub-query pointer
* @param num_candidates Number of candidates
* @return zvec_error_code_t Error code
*/
ZVEC_EXPORT zvec_error_code_t ZVEC_CALL
zvec_sub_query_set_num_candidates(zvec_sub_query_t *query, int num_candidates);
/**
* @brief Get number of candidates
* @param query Sub-query pointer
* @return int Number of candidates
*/
ZVEC_EXPORT int ZVEC_CALL
zvec_sub_query_get_num_candidates(const zvec_sub_query_t *query);
/**
* @brief Set field name
* @param query Sub-query pointer
* @param field_name Field name
* @return zvec_error_code_t Error code
*/
ZVEC_EXPORT zvec_error_code_t ZVEC_CALL
zvec_sub_query_set_field_name(zvec_sub_query_t *query, const char *field_name);
/**
* @brief Get field name
* @param query Sub-query pointer
* @return const char* Field name (owned by query, do not free)
*/
ZVEC_EXPORT const char *ZVEC_CALL
zvec_sub_query_get_field_name(const zvec_sub_query_t *query);
/**
* @brief Set query vector data
* @param query Sub-query pointer
* @param data Vector data pointer
* @param size Data size in bytes
* @return zvec_error_code_t Error code
*/
ZVEC_EXPORT zvec_error_code_t ZVEC_CALL zvec_sub_query_set_query_vector(
zvec_sub_query_t *query, const void *data, size_t size);
/**
* @brief Set sparse vector indices
* @param query Sub-query pointer
* @param indices Array of uint32_t indices
* @param count Number of indices
* @return zvec_error_code_t Error code
*/
ZVEC_EXPORT zvec_error_code_t ZVEC_CALL zvec_sub_query_set_sparse_indices(
zvec_sub_query_t *query, const uint32_t *indices, size_t count);
/**
* @brief Set sparse vector values
* @param query Sub-query pointer
* @param values Array of float values
* @param count Number of values
* @return zvec_error_code_t Error code
*/
ZVEC_EXPORT zvec_error_code_t ZVEC_CALL zvec_sub_query_set_sparse_values(
zvec_sub_query_t *query, const float *values, size_t count);
/**
* @brief Set HNSW query parameters (takes ownership)
* @param query Sub-query pointer
* @param hnsw_params HNSW query parameters pointer
* @return zvec_error_code_t Error code
*/
ZVEC_EXPORT zvec_error_code_t ZVEC_CALL zvec_sub_query_set_hnsw_params(
zvec_sub_query_t *query, zvec_hnsw_query_params_t *hnsw_params);
/**
* @brief Set IVF query parameters (takes ownership)
* @param query Sub-query pointer
* @param ivf_params IVF query parameters pointer
* @return zvec_error_code_t Error code
*/
ZVEC_EXPORT zvec_error_code_t ZVEC_CALL zvec_sub_query_set_ivf_params(
zvec_sub_query_t *query, zvec_ivf_query_params_t *ivf_params);
/**
* @brief Set Flat query parameters (takes ownership)
* @param query Sub-query pointer
* @param flat_params Flat query parameters pointer
* @return zvec_error_code_t Error code
*/
ZVEC_EXPORT zvec_error_code_t ZVEC_CALL zvec_sub_query_set_flat_params(
zvec_sub_query_t *query, zvec_flat_query_params_t *flat_params);
// =============================================================================
// Collection Options and Statistics (Opaque Pointer Pattern)
// =============================================================================
@@ -2024,16 +2317,6 @@ ZVEC_EXPORT zvec_error_code_t ZVEC_CALL zvec_field_schema_validate(
// Collection Schema Structures (Opaque Pointer Pattern)
// =============================================================================
/**
* @brief Collection schema handle (opaque pointer)
*
* Internally maps to zvec::CollectionSchema* (raw pointer).
* Created by zvec_collection_schema_create() and destroyed by
* zvec_collection_schema_destroy(). Caller owns the pointer and must explicitly
* destroy it.
*/
typedef struct zvec_collection_schema_t zvec_collection_schema_t;
/**
* @brief Create collection schema
* @param name Collection name
@@ -2476,13 +2759,6 @@ ZVEC_EXPORT zvec_error_code_t ZVEC_CALL zvec_collection_alter_column(
zvec_collection_t *collection, const char *column_name,
const char *new_name, const zvec_field_schema_t *new_schema);
/**
* @brief Document structure (opaque pointer mode)
* Internal implementation details are not visible to the outside, and
* operations are performed through API functions
*/
typedef struct zvec_doc_t zvec_doc_t;
/**
* @brief Per-document status returned by detailed DML APIs.
* @note Uses ordered style: result index corresponds to input document index.
@@ -2645,6 +2921,19 @@ ZVEC_EXPORT zvec_error_code_t ZVEC_CALL zvec_collection_query(
const zvec_collection_t *collection, const zvec_vector_query_t *query,
zvec_doc_t ***results, size_t *result_count);
/**
* @brief Multi-query with multiple sub-queries and re-ranking
* @param collection Collection handle
* @param query Multi-query query parameters pointer
* @param[out] results Returned document array (needs to be freed by calling
* zvec_docs_free)
* @param[out] result_count Number of returned results
* @return zvec_error_code_t Error code
*/
ZVEC_EXPORT zvec_error_code_t ZVEC_CALL zvec_collection_multi_query(
const zvec_collection_t *collection, const zvec_multi_query_t *query,
zvec_doc_t ***results, size_t *result_count);
/**
* @brief Fetch documents by primary keys
* @param collection Collection handle
+3 -1
View File
@@ -17,8 +17,8 @@
#include <optional>
#include <string>
#include <vector>
#include <zvec/db/doc.h>
#include <zvec/db/options.h>
#include <zvec/db/query.h>
#include <zvec/db/stats.h>
#include <zvec/db/status.h>
@@ -99,6 +99,8 @@ class Collection {
virtual Result<DocPtrList> Query(const VectorQuery &query) const = 0;
virtual Result<DocPtrList> Query(const MultiQuery &query) const = 0;
virtual Result<GroupResults> GroupByQuery(
const GroupByVectorQuery &query) const = 0;
-41
View File
@@ -20,7 +20,6 @@
#include <unordered_map>
#include <variant>
#include <zvec/ailego/utility/float_helper.h>
#include <zvec/db/query_params.h>
#include <zvec/db/schema.h>
#include <zvec/db/status.h>
#include <zvec/db/type.h>
@@ -364,44 +363,4 @@ using DocPtrMap = std::unordered_map<std::string, Doc::Ptr>;
using WriteResults = std::vector<Status>;
struct VectorQuery {
int topk_;
std::string field_name_;
std::string query_vector_; // fp16, void *
std::string query_sparse_indices_;
std::string query_sparse_values_;
std::string filter_;
bool include_vector_{false};
bool include_doc_id_{false};
// select * by default, select no field if output_fields_ is empty, select
// specific fields if output_fields_ is not empty
std::optional<std::vector<std::string>> output_fields_;
QueryParams::Ptr query_params_;
Status validate_and_sanitize(const FieldSchema *schema);
};
struct GroupByVectorQuery {
std::string field_name_;
std::string query_vector_;
std::string query_sparse_indices_;
std::string query_sparse_values_;
std::string filter_;
bool include_vector_;
// select * by default, select no field if output_fields_ is empty, select
// specific fields if output_fields_ is not empty
std::optional<std::vector<std::string>> output_fields_;
std::string group_by_field_name_;
uint32_t group_count_ = 2;
uint32_t group_topk_ = 3;
QueryParams::Ptr query_params_;
};
struct GroupResult {
std::string group_by_value_;
std::vector<Doc> docs_;
};
using GroupResults = std::vector<GroupResult>;
} // namespace zvec
+102
View File
@@ -0,0 +1,102 @@
// 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 <optional>
#include <string>
#include <variant>
#include <vector>
#include <zvec/db/doc.h>
#include <zvec/db/query_params.h>
#include <zvec/db/reranker.h>
namespace zvec {
struct VectorQuery {
int topk_;
std::string field_name_;
std::string query_vector_; // fp16, void *
std::string query_sparse_indices_;
std::string query_sparse_values_;
std::string filter_;
bool include_vector_{false};
bool include_doc_id_{false};
// select * by default, select no field if output_fields_ is empty, select
// specific fields if output_fields_ is not empty
std::optional<std::vector<std::string>> output_fields_;
QueryParams::Ptr query_params_;
Status validate_and_sanitize(const FieldSchema *schema);
};
struct GroupByVectorQuery {
std::string field_name_;
std::string query_vector_;
std::string query_sparse_indices_;
std::string query_sparse_values_;
std::string filter_;
bool include_vector_;
// select * by default, select no field if output_fields_ is empty, select
// specific fields if output_fields_ is not empty
std::optional<std::vector<std::string>> output_fields_;
std::string group_by_field_name_;
uint32_t group_count_ = 2;
uint32_t group_topk_ = 3;
QueryParams::Ptr query_params_;
};
//! Multi query structure for combining multiple sub-queries
//! (vector, full-text, etc.) with optional re-ranking of results.
struct VectorClause {
std::string query_vector_;
std::string sparse_indices_;
std::string sparse_values_;
};
struct FtsClause {
std::string query_string_;
std::string match_string_;
};
struct QueryTarget {
std::string field_name_;
std::variant<VectorClause, FtsClause> clause_;
QueryParams::Ptr query_params_;
};
struct SubQuery {
QueryTarget target_;
int num_candidates_{10};
};
struct MultiQuery {
std::vector<SubQuery> queries;
int topk{10};
std::string filter;
bool include_vector{false};
bool include_doc_id_{false};
std::optional<std::vector<std::string>> output_fields;
std::shared_ptr<Reranker> reranker{nullptr};
};
struct GroupResult {
std::string group_by_value_;
std::vector<Doc> docs_;
};
using GroupResults = std::vector<GroupResult>;
} // namespace zvec
+135
View File
@@ -0,0 +1,135 @@
// 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 <functional>
#include <map>
#include <memory>
#include <string>
#include <zvec/db/doc.h>
#include <zvec/db/schema.h>
#include <zvec/db/type.h>
#include "zvec/db/status.h"
namespace zvec {
//! Reranker abstract base class for re-ranking search results
class Reranker {
public:
using Ptr = std::shared_ptr<Reranker>;
Reranker() = default;
virtual ~Reranker() = default;
virtual void bind_schema(CollectionSchema::Ptr) {}
//! Re-rank documents from one or more vector queries.
//! \param query_results Mapping from vector field name to list of retrieved
//! documents (sorted by relevance).
//! \param topn Maximum number of documents to return.
//! \return Re-ranked list of documents (length <= topn), with updated scores.
virtual Result<DocPtrList> rerank(
const std::map<std::string, DocPtrList> &query_results,
int topn = 10) const = 0;
};
//! Intermediate base for rerankers that compute per-document scores.
//!
//! Implements the common rerank() logic: iterate docs, call rescore() for each,
//! accumulate scores by doc_id, and return topn results in descending order.
//! Subclasses only need to implement rescore().
class ScoreBasedReranker : public Reranker {
public:
//! Compute the contribution score for a single document.
//! \param score The document's raw relevance score from the vector field.
//! \param rank The document's position (0-based) in the per-field result
//! list. \param field_name The name of the vector field this result came
//! from. \return The score contribution to be accumulated for this document.
virtual Result<double> rescore(double score, int rank,
const std::string &field_name) const = 0;
Result<DocPtrList> rerank(
const std::map<std::string, DocPtrList> &query_results,
int topn = 10) const override;
};
//! Re-ranker using Reciprocal Rank Fusion (RRF) for multi-vector search.
//!
//! RRF combines results from multiple vector queries without requiring
//! relevance scores. The RRF score for a document at rank r is:
//! score = 1 / (k + r + 1)
//! where k is the rank constant.
class RrfReranker : public ScoreBasedReranker {
public:
explicit RrfReranker(int rank_constant = 60)
: rank_constant_(rank_constant) {}
int rank_constant() const {
return rank_constant_;
}
Result<double> rescore(double score, int rank,
const std::string &field_name) const override;
private:
int rank_constant_;
};
//! Re-ranker that combines scores from multiple vector fields using weights.
//!
//! Each vector field's relevance score is normalized based on its own metric
//! type, then scaled by a user-provided weight. Final scores are summed across
//! fields. Supported metrics: L2, IP, COSINE.
class WeightedReranker : public ScoreBasedReranker {
public:
explicit WeightedReranker(const std::map<std::string, double> &weights = {});
void bind_schema(CollectionSchema::Ptr schema) override;
const std::map<std::string, double> &weights() const {
return weights_;
}
Result<double> rescore(double score, int rank,
const std::string &field_name) const override;
private:
static Result<double> normalize_score(double score, const FieldSchema &field);
CollectionSchema::Ptr schema_;
std::map<std::string, double> weights_;
};
//! Callback-based re-ranker for cross-language bridging.
//!
//! Wraps a user-provided callback (e.g., a Python callable) as a Reranker.
//! When the callback is a Python function, GIL must be managed by the caller.
class CallbackReranker : public Reranker {
public:
using Callback =
std::function<DocPtrList(const std::map<std::string, DocPtrList> &, int)>;
explicit CallbackReranker(Callback fn) : callback_(std::move(fn)) {}
Result<DocPtrList> rerank(
const std::map<std::string, DocPtrList> &query_results,
int topn = 10) const override {
return callback_(query_results, topn);
}
private:
Callback callback_;
};
} // namespace zvec