feat(python): expose group-by search to Python API (#561)
Co-authored-by: jiliang.ljl <jiliang.ljl@alibaba-inc.com>
This commit is contained in:
co-authored by
jiliang.ljl
parent
2d00cb718b
commit
1afdea8dc5
@@ -5771,7 +5771,7 @@ zvec_group_by_vector_query_t *zvec_group_by_vector_query_create(void) {
|
||||
ZVEC_TRY_RETURN_NULL(
|
||||
"Failed to create GroupByVectorQuery",
|
||||
auto *query = new zvec::GroupByVectorQuery();
|
||||
query->group_count_ = 2; query->group_topk_ = 3;
|
||||
query->group_count_ = 2; query->topk_per_group_ = 3;
|
||||
return reinterpret_cast<zvec_group_by_vector_query_t *>(query);)
|
||||
return nullptr;
|
||||
}
|
||||
@@ -5841,23 +5841,23 @@ uint32_t zvec_group_by_vector_query_get_group_count(
|
||||
return ptr->group_count_;
|
||||
}
|
||||
|
||||
zvec_error_code_t zvec_group_by_vector_query_set_group_topk(
|
||||
zvec_group_by_vector_query_t *query, uint32_t topk) {
|
||||
zvec_error_code_t zvec_group_by_vector_query_set_topk_per_group(
|
||||
zvec_group_by_vector_query_t *query, uint32_t topk_per_group) {
|
||||
if (!query) {
|
||||
SET_LAST_ERROR(ZVEC_ERROR_INVALID_ARGUMENT,
|
||||
"GroupByVectorQuery pointer is null");
|
||||
return ZVEC_ERROR_INVALID_ARGUMENT;
|
||||
}
|
||||
auto *ptr = reinterpret_cast<zvec::GroupByVectorQuery *>(query);
|
||||
ptr->group_topk_ = topk;
|
||||
ptr->topk_per_group_ = topk_per_group;
|
||||
return ZVEC_OK;
|
||||
}
|
||||
|
||||
uint32_t zvec_group_by_vector_query_get_group_topk(
|
||||
uint32_t zvec_group_by_vector_query_get_topk_per_group(
|
||||
const zvec_group_by_vector_query_t *query) {
|
||||
if (!query) return 3;
|
||||
auto *ptr = reinterpret_cast<const zvec::GroupByVectorQuery *>(query);
|
||||
return ptr->group_topk_;
|
||||
return ptr->topk_per_group_;
|
||||
}
|
||||
|
||||
zvec_error_code_t zvec_group_by_vector_query_set_query_vector(
|
||||
|
||||
@@ -1952,6 +1952,71 @@ Args:
|
||||
}));
|
||||
}
|
||||
|
||||
void set_query_vector(QueryTarget &target, const FieldSchema &field_schema,
|
||||
const py::object &obj) {
|
||||
const DataType data_type = field_schema.data_type();
|
||||
|
||||
// Dense vector data is referenced by the query object. Callers
|
||||
// must not modify the source data until the query returns.
|
||||
if (FieldSchema::is_dense_vector_field(data_type)) {
|
||||
if (!py::isinstance<py::array>(obj)) {
|
||||
throw py::type_error("Dense vector[" + field_schema.name() +
|
||||
"] expects a ndarray, got " +
|
||||
std::string(py::str(py::type::of(obj))));
|
||||
}
|
||||
const auto arr = obj.cast<py::array>();
|
||||
if (arr.ndim() != 1) {
|
||||
throw py::type_error("Dense vector expects 1D array, got " +
|
||||
std::to_string(arr.ndim()) + "D");
|
||||
}
|
||||
const auto buf = arr.request();
|
||||
target.clause_ = VectorViewClause{
|
||||
std::string_view(static_cast<const char *>(buf.ptr),
|
||||
static_cast<size_t>(buf.size) * buf.itemsize),
|
||||
{},
|
||||
{}};
|
||||
return;
|
||||
}
|
||||
// sparse vector
|
||||
if (FieldSchema::is_sparse_vector_field(data_type)) {
|
||||
if (!py::isinstance<py::dict>(obj)) {
|
||||
throw py::type_error("Sparse vector[" + field_schema.name() +
|
||||
"] expects a Python dict, got " +
|
||||
std::string(py::str(py::type::of(obj))));
|
||||
}
|
||||
const auto sparse = obj.cast<py::dict>();
|
||||
|
||||
switch (data_type) {
|
||||
case DataType::SPARSE_VECTOR_FP16: {
|
||||
auto [indices, values] = serialize_sparse_vector<ailego::Float16>(
|
||||
sparse, [](const py::handle &h, size_t idx) {
|
||||
float f = checked_cast<float>(
|
||||
h, "Sparse value[" + std::to_string(idx) + "]", "FLOAT");
|
||||
return ailego::Float16(f);
|
||||
});
|
||||
target.set_sparse_vector(std::move(indices), std::move(values));
|
||||
break;
|
||||
}
|
||||
case DataType::SPARSE_VECTOR_FP32: {
|
||||
auto [indices, values] = serialize_sparse_vector<float>(
|
||||
sparse, [](const py::handle &h, size_t idx) {
|
||||
return checked_cast<float>(
|
||||
h, "Sparse value[" + std::to_string(idx) + "]", "FLOAT");
|
||||
});
|
||||
target.set_sparse_vector(std::move(indices), std::move(values));
|
||||
break;
|
||||
}
|
||||
default:
|
||||
throw py::type_error("Unsupported sparse vector type: " +
|
||||
std::to_string(static_cast<int>(data_type)));
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
throw py::type_error("Unsupported vector field type for field: " +
|
||||
field_schema.name());
|
||||
}
|
||||
|
||||
void ZVecPyParams::bind_vector_query(py::module_ &m) {
|
||||
// bind Fts
|
||||
py::class_<FtsClause>(m, "_Fts")
|
||||
@@ -2038,74 +2103,7 @@ void ZVecPyParams::bind_vector_query(py::module_ &m) {
|
||||
"set_vector",
|
||||
[](SearchQuery &self, const FieldSchema &field_schema,
|
||||
const py::object &obj) {
|
||||
const DataType data_type = field_schema.data_type();
|
||||
|
||||
// Dense vector data is referenced by the query object. Callers
|
||||
// must not modify the source data until the query returns.
|
||||
if (FieldSchema::is_dense_vector_field(data_type)) {
|
||||
if (!py::isinstance<py::array>(obj)) {
|
||||
throw py::type_error("Dense vector[" + field_schema.name() +
|
||||
"] expects a ndarray, got " +
|
||||
std::string(py::str(py::type::of(obj))));
|
||||
}
|
||||
const auto arr = obj.cast<py::array>();
|
||||
if (arr.ndim() != 1) {
|
||||
throw py::type_error("Dense vector expects 1D array, got " +
|
||||
std::to_string(arr.ndim()) + "D");
|
||||
}
|
||||
const auto buf = arr.request();
|
||||
self.target_.clause_ = VectorViewClause{
|
||||
std::string_view(
|
||||
static_cast<const char *>(buf.ptr),
|
||||
static_cast<size_t>(buf.size) * buf.itemsize),
|
||||
{},
|
||||
{}};
|
||||
return;
|
||||
}
|
||||
// sparse vector
|
||||
if (FieldSchema::is_sparse_vector_field(data_type)) {
|
||||
if (!py::isinstance<py::dict>(obj)) {
|
||||
throw py::type_error("Sparse vector[" + field_schema.name() +
|
||||
"] expects a Python dict, got " +
|
||||
std::string(py::str(py::type::of(obj))));
|
||||
}
|
||||
const auto sparse = obj.cast<py::dict>();
|
||||
|
||||
switch (data_type) {
|
||||
case DataType::SPARSE_VECTOR_FP16: {
|
||||
auto [indices, values] =
|
||||
serialize_sparse_vector<ailego::Float16>(
|
||||
sparse, [](const py::handle &h, size_t idx) {
|
||||
float f = checked_cast<float>(
|
||||
h, "Sparse value[" + std::to_string(idx) + "]",
|
||||
"FLOAT");
|
||||
return ailego::Float16(f);
|
||||
});
|
||||
self.target_.set_sparse_vector(std::move(indices),
|
||||
std::move(values));
|
||||
break;
|
||||
}
|
||||
case DataType::SPARSE_VECTOR_FP32: {
|
||||
auto [indices, values] = serialize_sparse_vector<float>(
|
||||
sparse, [](const py::handle &h, size_t idx) {
|
||||
return checked_cast<float>(
|
||||
h, "Sparse value[" + std::to_string(idx) + "]",
|
||||
"FLOAT");
|
||||
});
|
||||
self.target_.set_sparse_vector(std::move(indices),
|
||||
std::move(values));
|
||||
break;
|
||||
}
|
||||
default:
|
||||
throw py::type_error(
|
||||
"Unsupported sparse vector type: " +
|
||||
std::to_string(static_cast<int>(data_type)));
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
throw py::type_error("Unsupported vector field type for field: " +
|
||||
field_schema.name());
|
||||
set_query_vector(self.target_, field_schema, obj);
|
||||
},
|
||||
py::arg("field_schema"), py::arg("obj"), py::keep_alive<1, 3>(),
|
||||
"Set query vector. Dense vector source data must not be modified "
|
||||
@@ -2265,5 +2263,37 @@ void ZVecPyParams::bind_vector_query(py::module_ &m) {
|
||||
}
|
||||
return obj;
|
||||
}));
|
||||
|
||||
// _GroupByVectorQuery
|
||||
py::class_<GroupByVectorQuery>(m, "_GroupByVectorQuery")
|
||||
.def(py::init<>())
|
||||
.def_property(
|
||||
"field_name",
|
||||
[](const GroupByVectorQuery &q) { return q.target_.field_name_; },
|
||||
[](GroupByVectorQuery &q, std::string v) {
|
||||
q.target_.field_name_ = std::move(v);
|
||||
})
|
||||
.def_readwrite("filter", &GroupByVectorQuery::filter_)
|
||||
.def_readwrite("include_vector", &GroupByVectorQuery::include_vector_)
|
||||
.def_readwrite("output_fields", &GroupByVectorQuery::output_fields_)
|
||||
.def_readwrite("group_by_field_name",
|
||||
&GroupByVectorQuery::group_by_field_name_)
|
||||
.def_readwrite("group_count", &GroupByVectorQuery::group_count_)
|
||||
.def_readwrite("topk_per_group", &GroupByVectorQuery::topk_per_group_)
|
||||
.def_property(
|
||||
"query_params",
|
||||
[](const GroupByVectorQuery &q) { return q.target_.query_params_; },
|
||||
[](GroupByVectorQuery &q, QueryParams::Ptr p) {
|
||||
q.target_.query_params_ = std::move(p);
|
||||
})
|
||||
.def(
|
||||
"set_vector",
|
||||
[](GroupByVectorQuery &self, const FieldSchema &field_schema,
|
||||
const py::object &obj) {
|
||||
set_query_vector(self.target_, field_schema, obj);
|
||||
},
|
||||
py::arg("field_schema"), py::arg("obj"), py::keep_alive<1, 3>(),
|
||||
"Set query vector. Dense vector source data must not be modified "
|
||||
"until the query finishes.");
|
||||
}
|
||||
} // namespace zvec
|
||||
|
||||
@@ -48,6 +48,10 @@ T unwrap_expected(const tl::expected<T, Status> &exp) {
|
||||
}
|
||||
|
||||
void ZVecPyCollection::Initialize(pybind11::module_ &m) {
|
||||
py::class_<GroupResult>(m, "_GroupResult")
|
||||
.def_readonly("group_by_value", &GroupResult::group_by_value_)
|
||||
.def_readonly("docs", &GroupResult::docs_);
|
||||
|
||||
py::class_<Collection, Collection::Ptr> collection(m, "_Collection");
|
||||
bind_db_methods(collection);
|
||||
bind_ddl_methods(collection);
|
||||
@@ -281,7 +285,6 @@ void ZVecPyCollection::bind_dql_methods(
|
||||
py::gil_scoped_release release;
|
||||
result = self.GroupByQuery(query);
|
||||
}
|
||||
// return GroupResults
|
||||
return unwrap_expected(result);
|
||||
})
|
||||
.def(
|
||||
@@ -313,4 +316,4 @@ void ZVecPyCollection::bind_dql_methods(
|
||||
"for introspection and testing only; not part of the stable API.");
|
||||
}
|
||||
|
||||
} // namespace zvec
|
||||
} // namespace zvec
|
||||
|
||||
@@ -50,8 +50,8 @@ class HnswContext : public IndexContext {
|
||||
public:
|
||||
//! Set topk of search result
|
||||
void set_topk(uint32_t val) override {
|
||||
topk_ = val;
|
||||
topk_heap_.limit(std::max(val, ef_));
|
||||
topk_ = group_by_search() ? group_topk_ * group_num_ : val;
|
||||
topk_heap_.limit(std::max(topk_, ef_));
|
||||
}
|
||||
|
||||
//! Retrieve search result
|
||||
@@ -530,12 +530,9 @@ class HnswContext : public IndexContext {
|
||||
void set_group_params(uint32_t group_num, uint32_t group_topk) override {
|
||||
group_num_ = group_num;
|
||||
group_topk_ = group_topk;
|
||||
|
||||
topk_ = group_topk_ * group_num_;
|
||||
|
||||
topk_heap_.limit(std::max(topk_, ef_));
|
||||
|
||||
group_topk_heaps_.clear();
|
||||
|
||||
set_topk(group_topk_ * group_num_);
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
@@ -49,8 +49,8 @@ class HnswRabitqContext : public IndexContext {
|
||||
public:
|
||||
//! Set topk of search result
|
||||
void set_topk(uint32_t val) override {
|
||||
topk_ = val;
|
||||
topk_heap_.limit(std::max(val, ef_));
|
||||
topk_ = group_by_search() ? group_topk_ * group_num_ : val;
|
||||
topk_heap_.limit(std::max(topk_, ef_));
|
||||
}
|
||||
|
||||
//! Retrieve search result
|
||||
@@ -470,12 +470,9 @@ class HnswRabitqContext : public IndexContext {
|
||||
void set_group_params(uint32_t group_num, uint32_t group_topk) override {
|
||||
group_num_ = group_num;
|
||||
group_topk_ = group_topk;
|
||||
|
||||
topk_ = group_topk_ * group_num_;
|
||||
|
||||
topk_heap_.limit(std::max(topk_, ef_));
|
||||
|
||||
group_topk_heaps_.clear();
|
||||
|
||||
set_topk(group_topk_ * group_num_);
|
||||
}
|
||||
|
||||
void set_provider(IndexProvider::Pointer provider) {
|
||||
|
||||
@@ -43,8 +43,8 @@ class HnswSparseContext : public IndexContext {
|
||||
public:
|
||||
//! Set topk of search result
|
||||
void set_topk(uint32_t val) override {
|
||||
topk_ = val;
|
||||
topk_heap_.limit(std::max(val, ef_));
|
||||
topk_ = group_by_search() ? group_topk_ * group_num_ : val;
|
||||
topk_heap_.limit(std::max(topk_, ef_));
|
||||
}
|
||||
|
||||
//! Retrieve search result
|
||||
@@ -481,12 +481,9 @@ class HnswSparseContext : public IndexContext {
|
||||
void set_group_params(uint32_t group_num, uint32_t group_topk) override {
|
||||
group_num_ = group_num;
|
||||
group_topk_ = group_topk;
|
||||
|
||||
topk_ = group_topk_ * group_num_;
|
||||
|
||||
topk_heap_.limit(std::max(topk_, ef_));
|
||||
|
||||
group_topk_heaps_.clear();
|
||||
|
||||
set_topk(group_topk_ * group_num_);
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
@@ -1030,6 +1030,11 @@ int Index::_get_coarse_search_topk(
|
||||
return floor(search_param->topk * scale_factor);
|
||||
}
|
||||
|
||||
// Set or clear group-by state on a pooled context before each search.
|
||||
//
|
||||
// Set group-by state before topk so contexts can derive the effective candidate
|
||||
// count from the active group parameters. This order also ensures pooled
|
||||
// contexts restore the ordinary topk after stale group-by state is cleared.
|
||||
void Index::_set_group_by_on_context(
|
||||
const BaseIndexQueryParam::Pointer &search_param,
|
||||
core::IndexContext::Pointer &context) {
|
||||
@@ -1037,6 +1042,9 @@ void Index::_set_group_by_on_context(
|
||||
context->set_group_by(search_param->group_by_param->group_by);
|
||||
context->set_group_params(search_param->group_by_param->group_count,
|
||||
search_param->group_by_param->group_topk);
|
||||
} else {
|
||||
context->set_group_params(0, 0);
|
||||
context->reset_group_by();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -149,6 +149,9 @@ int HNSWIndex::_prepare_for_search(
|
||||
return core::IndexError_Runtime;
|
||||
}
|
||||
|
||||
// Set group state first so set_topk() derives the effective candidate count.
|
||||
_set_group_by_on_context(search_param, context);
|
||||
|
||||
context->set_topk(hnsw_search_param->topk);
|
||||
context->set_fetch_vector(hnsw_search_param->fetch_vector);
|
||||
if (hnsw_search_param->filter) {
|
||||
@@ -168,7 +171,7 @@ int HNSWIndex::_prepare_for_search(
|
||||
std::min(256u, hnsw_search_param->prefetch_lines);
|
||||
params.set(core::PARAM_HNSW_STREAMER_PL, real_search_pl);
|
||||
context->update(params);
|
||||
_set_group_by_on_context(search_param, context);
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -182,4 +185,4 @@ int HNSWIndex::_get_coarse_search_topk(
|
||||
return ret;
|
||||
}
|
||||
|
||||
} // namespace zvec::core_interface
|
||||
} // namespace zvec::core_interface
|
||||
|
||||
@@ -108,6 +108,9 @@ int HNSWRabitqIndex::_prepare_for_search(
|
||||
return core::IndexError_Runtime;
|
||||
}
|
||||
|
||||
// Set group state first so set_topk() derives the effective candidate count.
|
||||
_set_group_by_on_context(search_param, context);
|
||||
|
||||
context->set_topk(hnsw_search_param->topk);
|
||||
context->set_fetch_vector(hnsw_search_param->fetch_vector);
|
||||
if (hnsw_search_param->filter) {
|
||||
@@ -121,7 +124,7 @@ int HNSWRabitqIndex::_prepare_for_search(
|
||||
std::max(1u, std::min(2048u, hnsw_search_param->ef_search));
|
||||
params.set(core::PARAM_HNSW_RABITQ_STREAMER_EF, real_search_ef);
|
||||
context->update(params);
|
||||
_set_group_by_on_context(search_param, context);
|
||||
|
||||
return 0;
|
||||
#endif // RABITQ_SUPPORTED
|
||||
}
|
||||
|
||||
@@ -121,7 +121,7 @@ Result<GroupResults> SQLEngineImpl::execute_group_by(
|
||||
auto first_query_info = build_query_info(
|
||||
collection, query,
|
||||
std::make_shared<GroupBy>(group_by_query.group_by_field_name_,
|
||||
group_by_query.group_topk_,
|
||||
group_by_query.topk_per_group_,
|
||||
group_by_query.group_count_));
|
||||
if (!first_query_info) {
|
||||
return tl::make_unexpected(first_query_info.error());
|
||||
@@ -144,7 +144,7 @@ Result<GroupResults> SQLEngineImpl::execute_group_by(
|
||||
auto query_info = build_query_info(
|
||||
collection, query,
|
||||
std::make_shared<GroupBy>(group_by_query.group_by_field_name_,
|
||||
group_by_query.group_topk_,
|
||||
group_by_query.topk_per_group_,
|
||||
group_by_query.group_count_));
|
||||
if (!query_info) {
|
||||
return tl::make_unexpected(query_info.error());
|
||||
|
||||
@@ -2149,21 +2149,21 @@ ZVEC_EXPORT uint32_t ZVEC_CALL zvec_group_by_vector_query_get_group_count(
|
||||
const zvec_group_by_vector_query_t *query);
|
||||
|
||||
/**
|
||||
* @brief Set group topk
|
||||
* @brief Set the maximum number of results per group
|
||||
* @param query Group by vector query pointer
|
||||
* @param topk Number of results per group
|
||||
* @param topk_per_group Number of results per group
|
||||
* @return zvec_error_code_t Error code
|
||||
*/
|
||||
ZVEC_EXPORT zvec_error_code_t ZVEC_CALL
|
||||
zvec_group_by_vector_query_set_group_topk(zvec_group_by_vector_query_t *query,
|
||||
uint32_t topk);
|
||||
zvec_group_by_vector_query_set_topk_per_group(
|
||||
zvec_group_by_vector_query_t *query, uint32_t topk_per_group);
|
||||
|
||||
/**
|
||||
* @brief Get group topk
|
||||
* @brief Get the maximum number of results per group
|
||||
* @param query Group by vector query pointer
|
||||
* @return uint32_t Number of results per group
|
||||
*/
|
||||
ZVEC_EXPORT uint32_t ZVEC_CALL zvec_group_by_vector_query_get_group_topk(
|
||||
ZVEC_EXPORT uint32_t ZVEC_CALL zvec_group_by_vector_query_get_topk_per_group(
|
||||
const zvec_group_by_vector_query_t *query);
|
||||
|
||||
/**
|
||||
|
||||
@@ -19,7 +19,7 @@
|
||||
#include <zvec/core/framework/index_document.h>
|
||||
#include <zvec/core/framework/index_error.h>
|
||||
#include <zvec/core/framework/index_filter.h>
|
||||
#include <zvec/core/framework/index_groupby.h>
|
||||
#include <zvec/core/framework/index_group_by.h>
|
||||
#include <zvec/core/framework/index_metric.h>
|
||||
#include <zvec/core/framework/index_stats.h>
|
||||
|
||||
|
||||
@@ -205,7 +205,8 @@ class Index {
|
||||
const BaseIndexQueryParam::Pointer &search_param);
|
||||
|
||||
//! Helper: set group_by on context from the query param (common for all
|
||||
//! index types). Call this at the end of _prepare_for_search.
|
||||
//! index types). Call this before set_topk() when topk depends on group
|
||||
//! state.
|
||||
static void _set_group_by_on_context(
|
||||
const BaseIndexQueryParam::Pointer &search_param,
|
||||
core::IndexContext::Pointer &context);
|
||||
|
||||
@@ -171,7 +171,7 @@ struct GroupByVectorQuery {
|
||||
std::optional<std::vector<std::string>> output_fields_;
|
||||
std::string group_by_field_name_;
|
||||
uint32_t group_count_{2};
|
||||
uint32_t group_topk_{3};
|
||||
uint32_t topk_per_group_{3};
|
||||
};
|
||||
|
||||
struct GroupResult {
|
||||
|
||||
Reference in New Issue
Block a user