feat: add c language support (#167)
* init branch Add GitHub Actions release workflow for C API add release linux-arm64 remove c api version refact some code add api reference * feat(c-api): add nullable/doc-result APIs for agency migration (#234) * Flattened index parameters structure * refact c api code * remove RAII guard * refact use opaque pointer pattern * refact version info * refact use pure opaque pointers * use typedef instead of enum * fix set_last_error * fix build yml * fix doc.h * remove wheel exclude * fix c msvc link * remove release yml * fix c link libstdc++ * fix c link libgcc --------- Co-authored-by: Donny/강동윤 <kdy.1997.dev@gmail.com>
This commit is contained in:
@@ -125,3 +125,17 @@ jobs:
|
||||
./core-example
|
||||
./ailego-example
|
||||
shell: bash
|
||||
|
||||
- name: Run C Examples
|
||||
run: |
|
||||
cd "$GITHUB_WORKSPACE/examples/c"
|
||||
mkdir build && cd build
|
||||
cmake .. -DCMAKE_BUILD_TYPE=Release
|
||||
make -j $NPROC
|
||||
./c_api_basic_example
|
||||
./c_api_collection_schema_example
|
||||
./c_api_doc_example
|
||||
./c_api_field_schema_example
|
||||
./c_api_index_example
|
||||
./c_api_optimized_example
|
||||
shell: bash
|
||||
@@ -59,6 +59,9 @@ include_directories(${PROJECT_ROOT_DIR})
|
||||
option(BUILD_PYTHON_BINDINGS "Build Python bindings using pybind11" OFF)
|
||||
message(STATUS "BUILD_PYTHON_BINDINGS:${BUILD_PYTHON_BINDINGS}")
|
||||
|
||||
option(BUILD_C_BINDINGS "Build C bindings" ON)
|
||||
message(STATUS "BUILD_C_BINDINGS:${BUILD_C_BINDINGS}")
|
||||
|
||||
option(BUILD_TOOLS "Build tools" ON)
|
||||
message(STATUS "BUILD_TOOLS:${BUILD_TOOLS}")
|
||||
|
||||
|
||||
@@ -0,0 +1,209 @@
|
||||
# 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.
|
||||
|
||||
cmake_minimum_required(VERSION 3.13)
|
||||
cmake_policy(SET CMP0077 NEW)
|
||||
project(zvec-example-c)
|
||||
set(CMAKE_C_STANDARD 99)
|
||||
set(CMAKE_C_STANDARD_REQUIRED ON)
|
||||
|
||||
# Enable compile_commands.json
|
||||
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
|
||||
|
||||
# --- Paths to Zvec and dependencies ---
|
||||
# Allow custom host build directory, default to "build"
|
||||
if(NOT DEFINED HOST_BUILD_DIR)
|
||||
set(HOST_BUILD_DIR "build")
|
||||
endif()
|
||||
|
||||
set(ZVEC_INCLUDE_DIR ${CMAKE_BINARY_DIR}/../../../src/include)
|
||||
set(ZVEC_GENERATED_INCLUDE_DIR ${CMAKE_BINARY_DIR}/../../../${HOST_BUILD_DIR}/src/generated)
|
||||
|
||||
# On Windows, libraries are in Debug/Release subdirectories
|
||||
if(WIN32)
|
||||
set(ZVEC_LIB_DIR ${CMAKE_BINARY_DIR}/../../../${HOST_BUILD_DIR}/lib/$<CONFIG>)
|
||||
set(ZVEC_DEPENDENCY_LIB_DIR ${CMAKE_BINARY_DIR}/../../../${HOST_BUILD_DIR}/external/usr/local/lib/$<CONFIG>)
|
||||
else()
|
||||
set(ZVEC_LIB_DIR ${CMAKE_BINARY_DIR}/../../../${HOST_BUILD_DIR}/lib)
|
||||
set(ZVEC_DEPENDENCY_LIB_DIR ${CMAKE_BINARY_DIR}/../../../${HOST_BUILD_DIR}/external/usr/local/lib)
|
||||
endif()
|
||||
|
||||
# Add include and library search paths
|
||||
include_directories(${ZVEC_INCLUDE_DIR} ${ZVEC_GENERATED_INCLUDE_DIR})
|
||||
link_directories(${ZVEC_LIB_DIR} ${ZVEC_DEPENDENCY_LIB_DIR})
|
||||
|
||||
# Find required packages
|
||||
find_package(Threads REQUIRED)
|
||||
|
||||
# --- Determine debug/release library names ---
|
||||
if(CMAKE_BUILD_TYPE STREQUAL "Debug")
|
||||
set(GLOG_LIB glogd)
|
||||
set(GFLAGS_LIB gflags_nothreads_debug)
|
||||
set(PROTOBUF_LIB protobufd)
|
||||
else()
|
||||
set(GLOG_LIB glog)
|
||||
set(GFLAGS_LIB gflags_nothreads)
|
||||
set(PROTOBUF_LIB protobuf)
|
||||
endif()
|
||||
|
||||
# --- Dependency groups ---
|
||||
if(NOT WIN32)
|
||||
set(zvec_c_api_deps
|
||||
roaring
|
||||
rocksdb
|
||||
arrow
|
||||
arrow_acero
|
||||
arrow_bundled_dependencies
|
||||
arrow_compute
|
||||
arrow_dataset
|
||||
parquet
|
||||
antlr4-runtime
|
||||
${GLOG_LIB}
|
||||
${GFLAGS_LIB}
|
||||
${PROTOBUF_LIB}
|
||||
lz4
|
||||
${CMAKE_THREAD_LIBS_INIT}
|
||||
${CMAKE_DL_LIBS}
|
||||
)
|
||||
else()
|
||||
# Windows static libraries use different naming conventions
|
||||
set(PROTOBUF_LIB libprotobuf)
|
||||
set(zvec_c_api_deps
|
||||
roaring
|
||||
rocksdb
|
||||
arrow_static
|
||||
arrow_acero_static
|
||||
arrow_bundled_dependencies
|
||||
arrow_compute_static
|
||||
arrow_dataset_static
|
||||
parquet_static
|
||||
antlr4-runtime-static
|
||||
${GLOG_LIB}
|
||||
${GFLAGS_LIB}
|
||||
${PROTOBUF_LIB}
|
||||
lz4
|
||||
${CMAKE_THREAD_LIBS_INIT}
|
||||
rpcrt4
|
||||
shlwapi
|
||||
)
|
||||
endif()
|
||||
|
||||
# Create INTERFACE target for zvec_c_api with platform-specific linking
|
||||
add_library(zvec-c-api INTERFACE)
|
||||
if(CMAKE_SYSTEM_NAME STREQUAL "Linux")
|
||||
target_link_libraries(zvec-c-api INTERFACE
|
||||
-Wl,--whole-archive
|
||||
-lzvec_c_api
|
||||
-Wl,--no-whole-archive
|
||||
-Wl,--start-group
|
||||
${zvec_c_api_deps}
|
||||
-Wl,--end-group
|
||||
)
|
||||
elseif(APPLE)
|
||||
# On macOS, use -Wl,-force_load with full path to ensure all symbols are loaded
|
||||
target_link_libraries(zvec-c-api INTERFACE
|
||||
-Wl,-force_load
|
||||
${ZVEC_LIB_DIR}/libzvec_c_api.dylib
|
||||
${zvec_c_api_deps}
|
||||
)
|
||||
# Set rpath so the executable can find the dylib at runtime
|
||||
target_link_options(zvec-c-api INTERFACE
|
||||
-Wl,-rpath,${ZVEC_LIB_DIR}
|
||||
)
|
||||
elseif(ANDROID)
|
||||
target_link_libraries(zvec-c-api INTERFACE
|
||||
-Wl,--whole-archive
|
||||
-lzvec_c_api
|
||||
-Wl,--no-whole-archive
|
||||
-Wl,--start-group
|
||||
${zvec_c_api_deps}
|
||||
-Wl,--end-group
|
||||
)
|
||||
elseif(WIN32)
|
||||
target_link_libraries(zvec-c-api INTERFACE
|
||||
zvec_c_api
|
||||
${zvec_c_api_deps}
|
||||
)
|
||||
target_link_options(zvec-c-api INTERFACE "/WHOLEARCHIVE:zvec_c_api")
|
||||
else()
|
||||
message(FATAL_ERROR "Unsupported platform: ${CMAKE_SYSTEM_NAME}")
|
||||
endif()
|
||||
|
||||
# Basic example
|
||||
add_executable(c_api_basic_example basic_example.c)
|
||||
target_link_libraries(c_api_basic_example PRIVATE
|
||||
zvec-c-api
|
||||
)
|
||||
|
||||
# Schema example
|
||||
add_executable(c_api_collection_schema_example collection_schema_example.c)
|
||||
target_link_libraries(c_api_collection_schema_example PRIVATE
|
||||
zvec-c-api
|
||||
)
|
||||
|
||||
# Struct document example
|
||||
add_executable(c_api_doc_example doc_example.c)
|
||||
target_link_libraries(c_api_doc_example PRIVATE
|
||||
zvec-c-api
|
||||
)
|
||||
|
||||
# Index example
|
||||
add_executable(c_api_index_example index_example.c)
|
||||
target_link_libraries(c_api_index_example PRIVATE
|
||||
zvec-c-api
|
||||
)
|
||||
|
||||
# Field schema example
|
||||
add_executable(c_api_field_schema_example field_schema_example.c)
|
||||
target_link_libraries(c_api_field_schema_example PRIVATE
|
||||
zvec-c-api
|
||||
)
|
||||
|
||||
# Optimized example
|
||||
add_executable(c_api_optimized_example optimized_example.c)
|
||||
target_link_libraries(c_api_optimized_example PRIVATE
|
||||
zvec-c-api
|
||||
)
|
||||
|
||||
# Strip symbols to reduce executable size
|
||||
if(CMAKE_BUILD_TYPE STREQUAL "Release" AND (ANDROID OR (CMAKE_SYSTEM_NAME STREQUAL "Linux")))
|
||||
add_custom_command(TARGET c_api_basic_example POST_BUILD
|
||||
COMMAND ${CMAKE_STRIP} "$<TARGET_FILE:c_api_basic_example>"
|
||||
COMMENT "Stripping symbols from c_api_basic_example")
|
||||
add_custom_command(TARGET c_api_collection_schema_example POST_BUILD
|
||||
COMMAND ${CMAKE_STRIP} "$<TARGET_FILE:c_api_collection_schema_example>"
|
||||
COMMENT "Stripping symbols from c_api_collection_schema_example")
|
||||
add_custom_command(TARGET c_api_doc_example POST_BUILD
|
||||
COMMAND ${CMAKE_STRIP} "$<TARGET_FILE:c_api_doc_example>"
|
||||
COMMENT "Stripping symbols from c_api_doc_example")
|
||||
add_custom_command(TARGET c_api_index_example POST_BUILD
|
||||
COMMAND ${CMAKE_STRIP} "$<TARGET_FILE:c_api_index_example>"
|
||||
COMMENT "Stripping symbols from c_api_index_example")
|
||||
add_custom_command(TARGET c_api_field_schema_example POST_BUILD
|
||||
COMMAND ${CMAKE_STRIP} "$<TARGET_FILE:c_api_field_schema_example>"
|
||||
COMMENT "Stripping symbols from c_api_field_schema_example")
|
||||
add_custom_command(TARGET c_api_optimized_example POST_BUILD
|
||||
COMMAND ${CMAKE_STRIP} "$<TARGET_FILE:c_api_optimized_example>"
|
||||
COMMENT "Stripping symbols from c_api_optimized_example")
|
||||
endif()
|
||||
|
||||
# Optimize for size
|
||||
if(CMAKE_BUILD_TYPE STREQUAL "Release" AND ANDROID)
|
||||
set_property(TARGET c_api_basic_example c_api_collection_schema_example c_api_doc_example
|
||||
c_api_index_example c_api_field_schema_example c_api_optimized_example
|
||||
PROPERTY COMPILE_FLAGS "-Os")
|
||||
set_property(TARGET c_api_basic_example c_api_collection_schema_example c_api_doc_example
|
||||
c_api_index_example c_api_field_schema_example c_api_optimized_example
|
||||
PROPERTY INTERPROCEDURAL_OPTIMIZATION TRUE)
|
||||
endif()
|
||||
@@ -0,0 +1,265 @@
|
||||
// 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 <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include "zvec/c_api.h"
|
||||
|
||||
/**
|
||||
* @brief Print error message and return error code
|
||||
*/
|
||||
static ZVecErrorCode handle_error(ZVecErrorCode error, const char *context) {
|
||||
if (error != ZVEC_OK) {
|
||||
char *error_msg = NULL;
|
||||
zvec_get_last_error(&error_msg);
|
||||
fprintf(stderr, "Error in %s: %d - %s\n", context, error,
|
||||
error_msg ? error_msg : "Unknown error");
|
||||
zvec_free(error_msg);
|
||||
}
|
||||
return error;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Create a simple test collection using CollectionSchema
|
||||
*/
|
||||
static ZVecErrorCode create_simple_test_collection(
|
||||
ZVecCollection **collection) {
|
||||
// Create collection schema using C API
|
||||
ZVecCollectionSchema *schema =
|
||||
zvec_collection_schema_create("test_collection");
|
||||
if (!schema) {
|
||||
return ZVEC_ERROR_INTERNAL_ERROR;
|
||||
}
|
||||
|
||||
ZVecErrorCode error = ZVEC_OK;
|
||||
|
||||
// Create index parameters using new API
|
||||
ZVecIndexParams *invert_params =
|
||||
zvec_index_params_create(ZVEC_INDEX_TYPE_INVERT);
|
||||
if (!invert_params) {
|
||||
zvec_collection_schema_destroy(schema);
|
||||
return ZVEC_ERROR_RESOURCE_EXHAUSTED;
|
||||
}
|
||||
zvec_index_params_set_invert_params(invert_params, true, false);
|
||||
|
||||
ZVecIndexParams *hnsw_params = zvec_index_params_create(ZVEC_INDEX_TYPE_HNSW);
|
||||
if (!hnsw_params) {
|
||||
zvec_index_params_destroy(invert_params);
|
||||
zvec_collection_schema_destroy(schema);
|
||||
return ZVEC_ERROR_RESOURCE_EXHAUSTED;
|
||||
}
|
||||
zvec_index_params_set_metric_type(hnsw_params, ZVEC_METRIC_TYPE_COSINE);
|
||||
zvec_index_params_set_hnsw_params(hnsw_params, 16, 200);
|
||||
|
||||
// Create and add ID field (primary key)
|
||||
ZVecFieldSchema *id_field =
|
||||
zvec_field_schema_create("id", ZVEC_DATA_TYPE_STRING, false, 0);
|
||||
zvec_field_schema_set_index_params(id_field, invert_params);
|
||||
error = zvec_collection_schema_add_field(schema, id_field);
|
||||
if (error != ZVEC_OK) {
|
||||
zvec_index_params_destroy(invert_params);
|
||||
zvec_index_params_destroy(hnsw_params);
|
||||
zvec_collection_schema_destroy(schema);
|
||||
return error;
|
||||
}
|
||||
|
||||
// Create text field (inverted index)
|
||||
ZVecFieldSchema *text_field =
|
||||
zvec_field_schema_create("text", ZVEC_DATA_TYPE_STRING, true, 0);
|
||||
zvec_field_schema_set_index_params(text_field, invert_params);
|
||||
error = zvec_collection_schema_add_field(schema, text_field);
|
||||
if (error != ZVEC_OK) {
|
||||
zvec_index_params_destroy(invert_params);
|
||||
zvec_index_params_destroy(hnsw_params);
|
||||
zvec_collection_schema_destroy(schema);
|
||||
return error;
|
||||
}
|
||||
|
||||
// Create embedding field (HNSW index)
|
||||
ZVecFieldSchema *embedding_field = zvec_field_schema_create(
|
||||
"embedding", ZVEC_DATA_TYPE_VECTOR_FP32, false, 3);
|
||||
zvec_field_schema_set_index_params(embedding_field, hnsw_params);
|
||||
error = zvec_collection_schema_add_field(schema, embedding_field);
|
||||
if (error != ZVEC_OK) {
|
||||
zvec_index_params_destroy(invert_params);
|
||||
zvec_index_params_destroy(hnsw_params);
|
||||
zvec_collection_schema_destroy(schema);
|
||||
return error;
|
||||
}
|
||||
|
||||
// Cleanup index parameters (they have been copied to the field schemas)
|
||||
zvec_index_params_destroy(invert_params);
|
||||
zvec_index_params_destroy(hnsw_params);
|
||||
|
||||
// Use default options
|
||||
ZVecCollectionOptions *options = zvec_collection_options_create();
|
||||
if (!options) {
|
||||
zvec_collection_schema_destroy(schema);
|
||||
return ZVEC_ERROR_RESOURCE_EXHAUSTED;
|
||||
}
|
||||
|
||||
// Create collection using the new API
|
||||
error = zvec_collection_create_and_open("./test_collection", schema, options,
|
||||
collection);
|
||||
|
||||
// Cleanup resources
|
||||
zvec_collection_options_destroy(options);
|
||||
zvec_collection_schema_destroy(schema);
|
||||
|
||||
return error;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Basic C API usage example
|
||||
*/
|
||||
int main() {
|
||||
printf("=== ZVec C API Basic Example ===\n\n");
|
||||
|
||||
ZVecErrorCode error;
|
||||
|
||||
// Create collection using simplified function
|
||||
ZVecCollection *collection = NULL;
|
||||
error = create_simple_test_collection(&collection);
|
||||
if (handle_error(error, "creating collection") != ZVEC_OK) {
|
||||
return 1;
|
||||
}
|
||||
printf("✓ Collection created successfully\n");
|
||||
|
||||
// Prepare test data
|
||||
float vector1[] = {0.1f, 0.2f, 0.3f};
|
||||
float vector2[] = {0.4f, 0.5f, 0.6f};
|
||||
|
||||
ZVecDoc *docs[2];
|
||||
for (int i = 0; i < 2; ++i) {
|
||||
docs[i] = zvec_doc_create();
|
||||
if (!docs[i]) {
|
||||
fprintf(stderr, "Failed to create document %d\n", i);
|
||||
// Cleanup allocated resources
|
||||
for (int j = 0; j < i; ++j) {
|
||||
zvec_doc_destroy(docs[j]);
|
||||
}
|
||||
return ZVEC_ERROR_INTERNAL_ERROR;
|
||||
}
|
||||
}
|
||||
|
||||
// Manually add fields to document 1
|
||||
zvec_doc_set_pk(docs[0], "doc1");
|
||||
zvec_doc_add_field_by_value(docs[0], "id", ZVEC_DATA_TYPE_STRING, "doc1",
|
||||
strlen("doc1"));
|
||||
zvec_doc_add_field_by_value(docs[0], "text", ZVEC_DATA_TYPE_STRING,
|
||||
"First document", strlen("First document"));
|
||||
zvec_doc_add_field_by_value(docs[0], "embedding", ZVEC_DATA_TYPE_VECTOR_FP32,
|
||||
vector1, 3 * sizeof(float));
|
||||
|
||||
// Manually add fields to document 2
|
||||
zvec_doc_set_pk(docs[1], "doc2");
|
||||
zvec_doc_add_field_by_value(docs[1], "id", ZVEC_DATA_TYPE_STRING, "doc2",
|
||||
strlen("doc2"));
|
||||
zvec_doc_add_field_by_value(docs[1], "text", ZVEC_DATA_TYPE_STRING,
|
||||
"Second document", strlen("Second document"));
|
||||
zvec_doc_add_field_by_value(docs[1], "embedding", ZVEC_DATA_TYPE_VECTOR_FP32,
|
||||
vector2, 3 * sizeof(float));
|
||||
|
||||
// Insert documents
|
||||
size_t success_count = 0;
|
||||
size_t error_count = 0;
|
||||
error = zvec_collection_insert(collection, (const ZVecDoc **)docs, 2,
|
||||
&success_count, &error_count);
|
||||
if (handle_error(error, "inserting documents") != ZVEC_OK) {
|
||||
zvec_collection_destroy(collection);
|
||||
return 1;
|
||||
}
|
||||
printf("✓ Documents inserted - Success: %zu, Failed: %zu\n", success_count,
|
||||
error_count);
|
||||
for (int i = 0; i < 2; ++i) {
|
||||
zvec_doc_destroy(docs[i]);
|
||||
}
|
||||
|
||||
// Flush collection
|
||||
error = zvec_collection_flush(collection);
|
||||
if (handle_error(error, "flushing collection") != ZVEC_OK) {
|
||||
printf("Collection flush failed\n");
|
||||
} else {
|
||||
printf("✓ Collection flushed successfully\n");
|
||||
}
|
||||
|
||||
// Get collection statistics
|
||||
ZVecCollectionStats *stats = NULL;
|
||||
error = zvec_collection_get_stats(collection, &stats);
|
||||
if (handle_error(error, "getting collection stats") == ZVEC_OK) {
|
||||
printf("✓ Collection stats - Document count: %llu\n",
|
||||
(unsigned long long)zvec_collection_stats_get_doc_count(stats));
|
||||
// Free statistics memory
|
||||
zvec_collection_stats_destroy(stats);
|
||||
}
|
||||
|
||||
printf("Testing vector query...\n");
|
||||
// Query documents
|
||||
ZVecVectorQuery *query = zvec_vector_query_create();
|
||||
if (!query) {
|
||||
fprintf(stderr, "Failed to create vector query\n");
|
||||
zvec_collection_destroy(collection);
|
||||
return 1;
|
||||
}
|
||||
|
||||
zvec_vector_query_set_field_name(query, "embedding");
|
||||
zvec_vector_query_set_query_vector(query, vector1, 3 * sizeof(float));
|
||||
zvec_vector_query_set_topk(query, 10);
|
||||
zvec_vector_query_set_filter(query, "");
|
||||
zvec_vector_query_set_include_vector(query, true);
|
||||
zvec_vector_query_set_include_doc_id(query, true);
|
||||
|
||||
ZVecDoc **results = NULL;
|
||||
size_t result_count = 0;
|
||||
error = zvec_collection_query(collection, (const ZVecVectorQuery *)query,
|
||||
&results, &result_count);
|
||||
|
||||
if (error != ZVEC_OK) {
|
||||
char *error_msg = NULL;
|
||||
zvec_get_last_error(&error_msg);
|
||||
printf("[ERROR] Query failed: %s\n",
|
||||
error_msg ? error_msg : "Unknown error");
|
||||
zvec_free(error_msg);
|
||||
zvec_vector_query_destroy(query);
|
||||
goto cleanup;
|
||||
}
|
||||
|
||||
zvec_vector_query_destroy(query);
|
||||
|
||||
printf("✓ Query successful - Returned %zu results\n", result_count);
|
||||
|
||||
// Process query results
|
||||
for (size_t i = 0; i < result_count && i < 5; ++i) {
|
||||
const ZVecDoc *doc = results[i];
|
||||
const char *pk = zvec_doc_get_pk_copy(doc);
|
||||
|
||||
printf(" Result %zu: PK=%s, DocID=%llu, Score=%.4f\n", i + 1,
|
||||
pk ? pk : "NULL", (unsigned long long)zvec_doc_get_doc_id(doc),
|
||||
zvec_doc_get_score(doc));
|
||||
|
||||
if (pk) {
|
||||
zvec_free((void *)pk);
|
||||
}
|
||||
}
|
||||
|
||||
// Free query results memory
|
||||
zvec_docs_free(results, result_count);
|
||||
|
||||
cleanup:
|
||||
// Cleanup resources
|
||||
zvec_collection_destroy(collection);
|
||||
printf("✓ Example completed\n");
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,253 @@
|
||||
// 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 <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include "zvec/c_api.h"
|
||||
|
||||
/**
|
||||
* @brief Print error message and return error code
|
||||
*/
|
||||
static ZVecErrorCode handle_error(ZVecErrorCode error, const char *context) {
|
||||
if (error != ZVEC_OK) {
|
||||
char *error_msg = NULL;
|
||||
zvec_get_last_error(&error_msg);
|
||||
fprintf(stderr, "Error in %s: %d - %s\n", context, error,
|
||||
error_msg ? error_msg : "Unknown error");
|
||||
zvec_free(error_msg);
|
||||
}
|
||||
return error;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Collection schema creation and management example
|
||||
*/
|
||||
int main() {
|
||||
printf("=== ZVec Collection Schema Example ===\n\n");
|
||||
|
||||
ZVecErrorCode error;
|
||||
|
||||
// 1. Create collection schema
|
||||
ZVecCollectionSchema *schema =
|
||||
zvec_collection_schema_create("schema_example_collection");
|
||||
if (!schema) {
|
||||
fprintf(stderr, "Failed to create collection schema\n");
|
||||
return 1;
|
||||
}
|
||||
printf("✓ Collection schema created successfully\n");
|
||||
|
||||
// 2. Set schema properties
|
||||
zvec_collection_schema_set_max_doc_count_per_segment(schema, 1000000);
|
||||
printf("✓ Set max documents per segment: %llu\n",
|
||||
(unsigned long long)
|
||||
zvec_collection_schema_get_max_doc_count_per_segment(schema));
|
||||
|
||||
// 3. Create index parameters
|
||||
ZVecIndexParams *invert_params =
|
||||
zvec_index_params_create(ZVEC_INDEX_TYPE_INVERT);
|
||||
if (!invert_params) {
|
||||
fprintf(stderr, "Failed to create invert index parameters\n");
|
||||
zvec_collection_schema_destroy(schema);
|
||||
return 1;
|
||||
}
|
||||
zvec_index_params_set_invert_params(invert_params, true, false);
|
||||
|
||||
ZVecIndexParams *hnsw_params = zvec_index_params_create(ZVEC_INDEX_TYPE_HNSW);
|
||||
if (!hnsw_params) {
|
||||
fprintf(stderr, "Failed to create HNSW index parameters\n");
|
||||
zvec_index_params_destroy(invert_params);
|
||||
zvec_collection_schema_destroy(schema);
|
||||
return 1;
|
||||
}
|
||||
zvec_index_params_set_metric_type(hnsw_params, ZVEC_METRIC_TYPE_L2);
|
||||
zvec_index_params_set_hnsw_params(hnsw_params, 16, 200);
|
||||
|
||||
// 4. Create and add ID field (primary key)
|
||||
ZVecFieldSchema *id_field =
|
||||
zvec_field_schema_create("id", ZVEC_DATA_TYPE_STRING, false, 0);
|
||||
if (!id_field) {
|
||||
fprintf(stderr, "Failed to create ID field\n");
|
||||
zvec_collection_schema_destroy(schema);
|
||||
return 1;
|
||||
}
|
||||
|
||||
error = zvec_collection_schema_add_field(schema, id_field);
|
||||
if (handle_error(error, "adding ID field") != ZVEC_OK) {
|
||||
zvec_collection_schema_destroy(schema);
|
||||
return 1;
|
||||
}
|
||||
printf("✓ ID field added successfully\n");
|
||||
|
||||
// 5. Create and add text field with inverted index
|
||||
ZVecFieldSchema *text_field =
|
||||
zvec_field_schema_create("content", ZVEC_DATA_TYPE_STRING, true, 0);
|
||||
if (!text_field) {
|
||||
fprintf(stderr, "Failed to create text field\n");
|
||||
zvec_collection_schema_destroy(schema);
|
||||
return 1;
|
||||
}
|
||||
|
||||
zvec_field_schema_set_index_params(text_field, invert_params);
|
||||
error = zvec_collection_schema_add_field(schema, text_field);
|
||||
if (handle_error(error, "adding text field") != ZVEC_OK) {
|
||||
zvec_collection_schema_destroy(schema);
|
||||
return 1;
|
||||
}
|
||||
printf("✓ Text field with inverted index added successfully\n");
|
||||
|
||||
// 6. Create and add vector field with HNSW index
|
||||
ZVecFieldSchema *vector_field = zvec_field_schema_create(
|
||||
"embedding", ZVEC_DATA_TYPE_VECTOR_FP32, false, 128);
|
||||
if (!vector_field) {
|
||||
fprintf(stderr, "Failed to create vector field\n");
|
||||
zvec_collection_schema_destroy(schema);
|
||||
return 1;
|
||||
}
|
||||
|
||||
zvec_field_schema_set_index_params(vector_field, hnsw_params);
|
||||
error = zvec_collection_schema_add_field(schema, vector_field);
|
||||
if (handle_error(error, "adding vector field") != ZVEC_OK) {
|
||||
zvec_collection_schema_destroy(schema);
|
||||
return 1;
|
||||
}
|
||||
printf("✓ Vector field with HNSW index added successfully\n");
|
||||
|
||||
// 7. Check field count
|
||||
// Note: This function may not exist in current API, commenting out for now
|
||||
// size_t field_count = zvec_collection_schema_get_field_count(schema);
|
||||
// printf("✓ Total field count: %zu\n", field_count);
|
||||
|
||||
// 8. Create collection with schema
|
||||
ZVecCollectionOptions *options = zvec_collection_options_create();
|
||||
if (!options) {
|
||||
fprintf(stderr, "Failed to create collection options\n");
|
||||
zvec_collection_schema_destroy(schema);
|
||||
return 1;
|
||||
}
|
||||
ZVecCollection *collection = NULL;
|
||||
|
||||
error = zvec_collection_create_and_open("./schema_example_collection", schema,
|
||||
options, &collection);
|
||||
if (handle_error(error, "creating collection with schema") != ZVEC_OK) {
|
||||
zvec_collection_options_destroy(options);
|
||||
zvec_collection_schema_destroy(schema);
|
||||
return 1;
|
||||
}
|
||||
zvec_collection_options_destroy(options);
|
||||
printf("✓ Collection created successfully with schema\n");
|
||||
|
||||
// 9. Prepare test data
|
||||
float vector1[128];
|
||||
float vector2[128];
|
||||
for (int i = 0; i < 128; i++) {
|
||||
vector1[i] = (float)(i + 1) / 128.0f;
|
||||
vector2[i] = (float)(i + 2) / 128.0f;
|
||||
}
|
||||
|
||||
// 10. Create documents
|
||||
ZVecDoc *docs[2];
|
||||
for (int i = 0; i < 2; i++) {
|
||||
docs[i] = zvec_doc_create();
|
||||
if (!docs[i]) {
|
||||
fprintf(stderr, "Failed to create document %d\n", i);
|
||||
// Cleanup
|
||||
for (int j = 0; j < i; j++) {
|
||||
zvec_doc_destroy(docs[j]);
|
||||
}
|
||||
zvec_collection_destroy(collection);
|
||||
zvec_collection_schema_destroy(schema);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
// Add fields to document 1
|
||||
zvec_doc_set_pk(docs[0], "doc1");
|
||||
zvec_doc_add_field_by_value(docs[0], "id", ZVEC_DATA_TYPE_STRING, "doc1",
|
||||
strlen("doc1"));
|
||||
zvec_doc_add_field_by_value(docs[0], "content", ZVEC_DATA_TYPE_STRING,
|
||||
"First test document",
|
||||
strlen("First test document"));
|
||||
zvec_doc_add_field_by_value(docs[0], "embedding", ZVEC_DATA_TYPE_VECTOR_FP32,
|
||||
vector1, 128 * sizeof(float));
|
||||
|
||||
// Add fields to document 2
|
||||
zvec_doc_set_pk(docs[1], "doc2");
|
||||
zvec_doc_add_field_by_value(docs[1], "id", ZVEC_DATA_TYPE_STRING, "doc2",
|
||||
strlen("doc2"));
|
||||
zvec_doc_add_field_by_value(docs[1], "content", ZVEC_DATA_TYPE_STRING,
|
||||
"Second test document",
|
||||
strlen("Second test document"));
|
||||
zvec_doc_add_field_by_value(docs[1], "embedding", ZVEC_DATA_TYPE_VECTOR_FP32,
|
||||
vector2, 128 * sizeof(float));
|
||||
|
||||
// 11. Insert documents
|
||||
size_t success_count = 0, error_count = 0;
|
||||
error = zvec_collection_insert(collection, (const ZVecDoc **)docs, 2,
|
||||
&success_count, &error_count);
|
||||
if (handle_error(error, "inserting documents") != ZVEC_OK) {
|
||||
// Cleanup
|
||||
for (int i = 0; i < 2; i++) {
|
||||
zvec_doc_destroy(docs[i]);
|
||||
}
|
||||
zvec_collection_destroy(collection);
|
||||
zvec_collection_schema_destroy(schema);
|
||||
return 1;
|
||||
}
|
||||
printf("✓ Documents inserted - Success: %zu, Failed: %zu\n", success_count,
|
||||
error_count);
|
||||
|
||||
// Cleanup documents
|
||||
for (int i = 0; i < 2; i++) {
|
||||
zvec_doc_destroy(docs[i]);
|
||||
}
|
||||
|
||||
// 12. Flush collection
|
||||
error = zvec_collection_flush(collection);
|
||||
if (handle_error(error, "flushing collection") == ZVEC_OK) {
|
||||
printf("✓ Collection flushed successfully\n");
|
||||
}
|
||||
|
||||
// 13. Query test
|
||||
ZVecVectorQuery *query = zvec_vector_query_create();
|
||||
if (!query) {
|
||||
fprintf(stderr, "Failed to create vector query\n");
|
||||
zvec_collection_destroy(collection);
|
||||
zvec_collection_schema_destroy(schema);
|
||||
return 1;
|
||||
}
|
||||
zvec_vector_query_set_field_name(query, "embedding");
|
||||
zvec_vector_query_set_query_vector(query, vector1, 128 * sizeof(float));
|
||||
zvec_vector_query_set_topk(query, 5);
|
||||
zvec_vector_query_set_filter(query, "");
|
||||
zvec_vector_query_set_include_vector(query, true);
|
||||
zvec_vector_query_set_include_doc_id(query, true);
|
||||
|
||||
ZVecDoc **results = NULL;
|
||||
size_t result_count = 0;
|
||||
error = zvec_collection_query(collection, (const ZVecVectorQuery *)query,
|
||||
&results, &result_count);
|
||||
if (error == ZVEC_OK) {
|
||||
printf("✓ Vector query successful - Returned %zu results\n", result_count);
|
||||
zvec_docs_free(results, result_count);
|
||||
}
|
||||
zvec_vector_query_destroy(query);
|
||||
|
||||
// 14. Cleanup resources
|
||||
zvec_collection_destroy(collection);
|
||||
zvec_collection_schema_destroy(schema);
|
||||
printf("✓ Schema example completed\n");
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,536 @@
|
||||
// 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 <math.h>
|
||||
#include <stdbool.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include "zvec/c_api.h"
|
||||
|
||||
/**
|
||||
* @brief Print error message and return error code
|
||||
*/
|
||||
static ZVecErrorCode handle_error(ZVecErrorCode error, const char *context) {
|
||||
if (error != ZVEC_OK) {
|
||||
char *error_msg = NULL;
|
||||
zvec_get_last_error(&error_msg);
|
||||
fprintf(stderr, "Error in %s: %d - %s\n", context, error,
|
||||
error_msg ? error_msg : "Unknown error");
|
||||
zvec_free(error_msg);
|
||||
}
|
||||
return error;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Create a test document with all data types
|
||||
* @param doc_index Document index for generating unique data
|
||||
* @return ZVecDoc* Created document pointer
|
||||
*/
|
||||
static ZVecDoc *create_full_type_test_doc(int doc_index) {
|
||||
ZVecDoc *doc = zvec_doc_create();
|
||||
if (!doc) {
|
||||
fprintf(stderr, "Failed to create document\n");
|
||||
return NULL;
|
||||
}
|
||||
|
||||
// Set primary key
|
||||
char pk_buffer[32];
|
||||
snprintf(pk_buffer, sizeof(pk_buffer), "doc_%d", doc_index);
|
||||
zvec_doc_set_pk(doc, pk_buffer);
|
||||
|
||||
// Add Id field with inverted index
|
||||
char id_buffer[32];
|
||||
snprintf(id_buffer, sizeof(id_buffer), "id_%d", doc_index);
|
||||
zvec_doc_add_field_by_value(doc, "id", ZVEC_DATA_TYPE_STRING, id_buffer,
|
||||
strlen(id_buffer));
|
||||
|
||||
// Add scalar fields with different data types
|
||||
// String field
|
||||
char string_value[64];
|
||||
snprintf(string_value, sizeof(string_value), "test_string_%d", doc_index);
|
||||
zvec_doc_add_field_by_value(doc, "string_field", ZVEC_DATA_TYPE_STRING,
|
||||
string_value, strlen(string_value));
|
||||
|
||||
// Boolean field
|
||||
bool bool_value = (doc_index % 2 == 0);
|
||||
zvec_doc_add_field_by_value(doc, "bool_field", ZVEC_DATA_TYPE_BOOL,
|
||||
&bool_value, sizeof(bool_value));
|
||||
|
||||
// Integer fields
|
||||
int32_t int32_value = doc_index * 1000;
|
||||
zvec_doc_add_field_by_value(doc, "int32_field", ZVEC_DATA_TYPE_INT32,
|
||||
&int32_value, sizeof(int32_value));
|
||||
|
||||
int64_t int64_value = (int64_t)doc_index * 1000000LL;
|
||||
zvec_doc_add_field_by_value(doc, "int64_field", ZVEC_DATA_TYPE_INT64,
|
||||
&int64_value, sizeof(int64_value));
|
||||
|
||||
// Floating point fields
|
||||
float float_value = (float)doc_index * 1.5f;
|
||||
zvec_doc_add_field_by_value(doc, "float_field", ZVEC_DATA_TYPE_FLOAT,
|
||||
&float_value, sizeof(float_value));
|
||||
|
||||
double double_value = (double)doc_index * 2.718281828;
|
||||
zvec_doc_add_field_by_value(doc, "double_field", ZVEC_DATA_TYPE_DOUBLE,
|
||||
&double_value, sizeof(double_value));
|
||||
|
||||
// Vector fields with different dimensions
|
||||
// FP32 vector (3D)
|
||||
float fp32_vector[3] = {(float)doc_index, (float)doc_index * 2.0f,
|
||||
(float)doc_index * 3.0f};
|
||||
zvec_doc_add_field_by_value(doc, "vector_fp32", ZVEC_DATA_TYPE_VECTOR_FP32,
|
||||
fp32_vector, 3 * sizeof(float));
|
||||
|
||||
// Larger FP32 vector (16D)
|
||||
float large_vector[16];
|
||||
for (int i = 0; i < 16; i++) {
|
||||
large_vector[i] = (float)(doc_index * 16 + i) / 256.0f;
|
||||
}
|
||||
zvec_doc_add_field_by_value(doc, "large_vector", ZVEC_DATA_TYPE_VECTOR_FP32,
|
||||
large_vector, 16 * sizeof(float));
|
||||
|
||||
return doc;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Compare two documents for equality
|
||||
*/
|
||||
static bool compare_documents(const ZVecDoc *doc1, const ZVecDoc *doc2) {
|
||||
if (!doc1 || !doc2) return false;
|
||||
|
||||
// Compare primary keys
|
||||
const char *pk1 = zvec_doc_get_pk_pointer(doc1);
|
||||
const char *pk2 = zvec_doc_get_pk_pointer(doc2);
|
||||
|
||||
if (!pk1 || !pk2 || strcmp(pk1, pk2) != 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// TODO: Compare other fields and values
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Print document fields and their values
|
||||
* @param doc The document to print
|
||||
* @param doc_index Document index for identification
|
||||
*/
|
||||
static void print_doc(const ZVecDoc *doc, int doc_index) {
|
||||
if (!doc) {
|
||||
printf("Document %d: NULL document\n", doc_index);
|
||||
return;
|
||||
}
|
||||
|
||||
printf("\n=== Document %d ===\n", doc_index);
|
||||
|
||||
// Print primary key
|
||||
const char *pk = zvec_doc_get_pk_pointer(doc);
|
||||
printf("Primary Key: %s\n", pk ? pk : "NULL");
|
||||
|
||||
// Print document ID
|
||||
uint64_t doc_id = zvec_doc_get_doc_id(doc);
|
||||
printf("Document ID: %llu\n", (unsigned long long)doc_id);
|
||||
|
||||
// Print score
|
||||
float score = zvec_doc_get_score(doc);
|
||||
printf("Score: %.6f\n", score);
|
||||
|
||||
// Print scalar fields
|
||||
printf("\nScalar Fields:\n");
|
||||
|
||||
// ID field (using pointer function for strings)
|
||||
const void *id_value = NULL;
|
||||
size_t id_size = 0;
|
||||
ZVecErrorCode error = zvec_doc_get_field_value_pointer(
|
||||
doc, "id", ZVEC_DATA_TYPE_STRING, &id_value, &id_size);
|
||||
if (error == ZVEC_OK && id_value) {
|
||||
printf(" id: %.*s\n", (int)id_size, (const char *)id_value);
|
||||
}
|
||||
|
||||
// String field (using pointer function for strings)
|
||||
const void *string_value = NULL;
|
||||
size_t string_size = 0;
|
||||
error = zvec_doc_get_field_value_pointer(
|
||||
doc, "string_field", ZVEC_DATA_TYPE_STRING, &string_value, &string_size);
|
||||
if (error == ZVEC_OK && string_value) {
|
||||
printf(" string_field: %.*s\n", (int)string_size,
|
||||
(const char *)string_value);
|
||||
}
|
||||
|
||||
// Boolean field
|
||||
bool bool_value;
|
||||
error = zvec_doc_get_field_value_basic(doc, "bool_field", ZVEC_DATA_TYPE_BOOL,
|
||||
&bool_value, sizeof(bool_value));
|
||||
if (error == ZVEC_OK) {
|
||||
printf(" bool_field: %s\n", bool_value ? "true" : "false");
|
||||
}
|
||||
|
||||
// Int32 field
|
||||
int32_t int32_value;
|
||||
error =
|
||||
zvec_doc_get_field_value_basic(doc, "int32_field", ZVEC_DATA_TYPE_INT32,
|
||||
&int32_value, sizeof(int32_value));
|
||||
if (error == ZVEC_OK) {
|
||||
printf(" int32_field: %d\n", int32_value);
|
||||
}
|
||||
|
||||
// Int64 field
|
||||
int64_t int64_value;
|
||||
error =
|
||||
zvec_doc_get_field_value_basic(doc, "int64_field", ZVEC_DATA_TYPE_INT64,
|
||||
&int64_value, sizeof(int64_value));
|
||||
if (error == ZVEC_OK) {
|
||||
printf(" int64_field: %lld\n", (long long)int64_value);
|
||||
}
|
||||
|
||||
// Float field
|
||||
float float_value;
|
||||
error =
|
||||
zvec_doc_get_field_value_basic(doc, "float_field", ZVEC_DATA_TYPE_FLOAT,
|
||||
&float_value, sizeof(float_value));
|
||||
if (error == ZVEC_OK) {
|
||||
printf(" float_field: %.6f\n", float_value);
|
||||
}
|
||||
|
||||
// Double field
|
||||
double double_value;
|
||||
error =
|
||||
zvec_doc_get_field_value_basic(doc, "double_field", ZVEC_DATA_TYPE_DOUBLE,
|
||||
&double_value, sizeof(double_value));
|
||||
if (error == ZVEC_OK) {
|
||||
printf(" double_field: %.6f\n", double_value);
|
||||
}
|
||||
|
||||
// Print vector fields (using copy function for complex types)
|
||||
printf("\nVector Fields:\n");
|
||||
|
||||
// FP32 vector (3D)
|
||||
void *fp32_vector = NULL;
|
||||
size_t fp32_size = 0;
|
||||
error = zvec_doc_get_field_value_copy(
|
||||
doc, "vector_fp32", ZVEC_DATA_TYPE_VECTOR_FP32, &fp32_vector, &fp32_size);
|
||||
if (error == ZVEC_OK && fp32_vector) {
|
||||
const float *vec = (const float *)fp32_vector;
|
||||
size_t dim = fp32_size / sizeof(float);
|
||||
printf(" vector_fp32 (%zuD): [", dim);
|
||||
for (size_t i = 0; i < dim && i < 10; i++) { // Limit to first 10 elements
|
||||
printf("%.3f", vec[i]);
|
||||
if (i < dim - 1 && i < 9) printf(", ");
|
||||
}
|
||||
if (dim > 10) printf(", ...");
|
||||
printf("]\n");
|
||||
zvec_free(fp32_vector); // Free the allocated memory
|
||||
}
|
||||
|
||||
// Large vector (16D)
|
||||
void *large_vector = NULL;
|
||||
size_t large_size = 0;
|
||||
error = zvec_doc_get_field_value_copy(doc, "large_vector",
|
||||
ZVEC_DATA_TYPE_VECTOR_FP32,
|
||||
&large_vector, &large_size);
|
||||
if (error == ZVEC_OK && large_vector) {
|
||||
const float *vec = (const float *)large_vector;
|
||||
size_t dim = large_size / sizeof(float);
|
||||
printf(" large_vector (%zuD): [", dim);
|
||||
for (size_t i = 0; i < dim && i < 10; i++) { // Limit to first 10 elements
|
||||
printf("%.3f", vec[i]);
|
||||
if (i < dim - 1 && i < 9) printf(", ");
|
||||
}
|
||||
if (dim > 10) printf(", ...");
|
||||
printf("]\n");
|
||||
zvec_free(large_vector); // Free the allocated memory
|
||||
}
|
||||
|
||||
printf("==================\n\n");
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Document creation, manipulation, and query example
|
||||
*/
|
||||
int main() {
|
||||
printf("=== ZVec Document Example ===\n\n");
|
||||
|
||||
ZVecErrorCode error;
|
||||
|
||||
// 1. Create collection schema for document testing
|
||||
ZVecCollectionSchema *schema =
|
||||
zvec_collection_schema_create("doc_example_collection");
|
||||
if (!schema) {
|
||||
fprintf(stderr, "Failed to create collection schema\n");
|
||||
return -1;
|
||||
}
|
||||
printf("✓ Collection schema created\n");
|
||||
|
||||
// 2. Create index parameters
|
||||
ZVecIndexParams *invert_params =
|
||||
zvec_index_params_create(ZVEC_INDEX_TYPE_INVERT);
|
||||
if (!invert_params) {
|
||||
fprintf(stderr, "Failed to create invert index parameters\n");
|
||||
zvec_collection_schema_destroy(schema);
|
||||
return -1;
|
||||
}
|
||||
zvec_index_params_set_invert_params(invert_params, true, false);
|
||||
|
||||
ZVecIndexParams *hnsw_params = zvec_index_params_create(ZVEC_INDEX_TYPE_HNSW);
|
||||
if (!hnsw_params) {
|
||||
fprintf(stderr, "Failed to create HNSW index parameters\n");
|
||||
zvec_index_params_destroy(invert_params);
|
||||
zvec_collection_schema_destroy(schema);
|
||||
return -1;
|
||||
}
|
||||
zvec_index_params_set_metric_type(hnsw_params, ZVEC_METRIC_TYPE_L2);
|
||||
zvec_index_params_set_hnsw_params(hnsw_params, 16, 200);
|
||||
|
||||
// 3. Create fields for all data types
|
||||
printf("Creating fields for all data types...\n");
|
||||
|
||||
// Id field with inverted index
|
||||
ZVecFieldSchema *id_field =
|
||||
zvec_field_schema_create("id", ZVEC_DATA_TYPE_STRING, false, 0);
|
||||
if (id_field) {
|
||||
zvec_field_schema_set_index_params(id_field, invert_params);
|
||||
error = zvec_collection_schema_add_field(schema, id_field);
|
||||
if (handle_error(error, "adding ID field") == ZVEC_OK) {
|
||||
printf("✓ ID field with inverted index added\n");
|
||||
}
|
||||
}
|
||||
|
||||
// Scalar fields
|
||||
ZVecFieldSchema *string_field =
|
||||
zvec_field_schema_create("string_field", ZVEC_DATA_TYPE_STRING, true, 0);
|
||||
ZVecFieldSchema *bool_field =
|
||||
zvec_field_schema_create("bool_field", ZVEC_DATA_TYPE_BOOL, true, 0);
|
||||
ZVecFieldSchema *int32_field =
|
||||
zvec_field_schema_create("int32_field", ZVEC_DATA_TYPE_INT32, true, 0);
|
||||
ZVecFieldSchema *int64_field =
|
||||
zvec_field_schema_create("int64_field", ZVEC_DATA_TYPE_INT64, true, 0);
|
||||
ZVecFieldSchema *float_field =
|
||||
zvec_field_schema_create("float_field", ZVEC_DATA_TYPE_FLOAT, true, 0);
|
||||
ZVecFieldSchema *double_field =
|
||||
zvec_field_schema_create("double_field", ZVEC_DATA_TYPE_DOUBLE, true, 0);
|
||||
|
||||
if (string_field) zvec_collection_schema_add_field(schema, string_field);
|
||||
if (bool_field) zvec_collection_schema_add_field(schema, bool_field);
|
||||
if (int32_field) zvec_collection_schema_add_field(schema, int32_field);
|
||||
if (int64_field) zvec_collection_schema_add_field(schema, int64_field);
|
||||
if (float_field) zvec_collection_schema_add_field(schema, float_field);
|
||||
if (double_field) zvec_collection_schema_add_field(schema, double_field);
|
||||
|
||||
// Vector fields
|
||||
ZVecFieldSchema *vector_fp32_field = zvec_field_schema_create(
|
||||
"vector_fp32", ZVEC_DATA_TYPE_VECTOR_FP32, false, 3);
|
||||
ZVecFieldSchema *large_vector_field = zvec_field_schema_create(
|
||||
"large_vector", ZVEC_DATA_TYPE_VECTOR_FP32, false, 16);
|
||||
|
||||
if (vector_fp32_field) {
|
||||
zvec_field_schema_set_index_params(vector_fp32_field, hnsw_params);
|
||||
error = zvec_collection_schema_add_field(schema, vector_fp32_field);
|
||||
if (handle_error(error, "adding vector FP32 field") == ZVEC_OK) {
|
||||
printf("✓ Vector FP32 field with HNSW index added\n");
|
||||
}
|
||||
}
|
||||
|
||||
if (large_vector_field) {
|
||||
zvec_field_schema_set_index_params(large_vector_field, hnsw_params);
|
||||
error = zvec_collection_schema_add_field(schema, large_vector_field);
|
||||
if (handle_error(error, "adding large vector field") == ZVEC_OK) {
|
||||
printf("✓ Large vector field with HNSW index added\n");
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Create collection
|
||||
ZVecCollectionOptions *options = zvec_collection_options_create();
|
||||
if (!options) {
|
||||
fprintf(stderr, "Failed to create collection options\n");
|
||||
zvec_collection_schema_destroy(schema);
|
||||
return -1;
|
||||
}
|
||||
ZVecCollection *collection = NULL;
|
||||
|
||||
error = zvec_collection_create_and_open("./doc_example_collection", schema,
|
||||
options, &collection);
|
||||
zvec_collection_options_destroy(options);
|
||||
if (handle_error(error, "creating collection") != ZVEC_OK) {
|
||||
zvec_collection_schema_destroy(schema);
|
||||
return -1;
|
||||
}
|
||||
printf("✓ Collection created successfully\n");
|
||||
|
||||
// 5. Create and insert multiple test documents
|
||||
printf("Creating and inserting test documents...\n");
|
||||
|
||||
#define DOC_COUNT 5
|
||||
// Use dynamic allocation for MSVC compatibility (no VLA support)
|
||||
ZVecDoc **test_docs = (ZVecDoc **)malloc(DOC_COUNT * sizeof(ZVecDoc *));
|
||||
if (!test_docs) {
|
||||
fprintf(stderr, "Failed to allocate test documents\n");
|
||||
goto cleanup;
|
||||
}
|
||||
|
||||
for (int i = 0; i < DOC_COUNT; i++) {
|
||||
test_docs[i] = create_full_type_test_doc(i);
|
||||
if (!test_docs[i]) {
|
||||
fprintf(stderr, "Failed to create document %d\n", i);
|
||||
// Cleanup
|
||||
for (int j = 0; j < i; j++) {
|
||||
zvec_doc_destroy(test_docs[j]);
|
||||
}
|
||||
goto cleanup;
|
||||
}
|
||||
printf("✓ Created document %d with PK: %s\n", i,
|
||||
zvec_doc_get_pk_pointer(test_docs[i]));
|
||||
}
|
||||
|
||||
// Print all documents before insertion
|
||||
printf("\nDocuments before insertion:\n");
|
||||
for (int i = 0; i < DOC_COUNT; i++) {
|
||||
print_doc(test_docs[i], i);
|
||||
}
|
||||
|
||||
// Insert documents
|
||||
size_t success_count = 0, error_count = 0;
|
||||
error = zvec_collection_insert(collection, (const ZVecDoc **)test_docs,
|
||||
DOC_COUNT, &success_count, &error_count);
|
||||
if (handle_error(error, "inserting documents") == ZVEC_OK) {
|
||||
printf("✓ Documents inserted - Success: %zu, Failed: %zu\n", success_count,
|
||||
error_count);
|
||||
}
|
||||
|
||||
// 6. Flush collection
|
||||
error = zvec_collection_flush(collection);
|
||||
if (handle_error(error, "flushing collection") != ZVEC_OK) {
|
||||
printf("Warning: Collection flush failed\n");
|
||||
} else {
|
||||
printf("✓ Collection flushed successfully\n");
|
||||
}
|
||||
|
||||
// Use the first document's vector for querying
|
||||
float query_vector[] = {0.0f, 0.0f, 0.0f};
|
||||
ZVecVectorQuery *query = zvec_vector_query_create();
|
||||
if (!query) {
|
||||
fprintf(stderr, "Failed to create vector query\n");
|
||||
zvec_collection_destroy(collection);
|
||||
zvec_collection_schema_destroy(schema);
|
||||
return -1;
|
||||
}
|
||||
zvec_vector_query_set_field_name(query, "vector_fp32");
|
||||
zvec_vector_query_set_query_vector(query, query_vector, 3 * sizeof(float));
|
||||
zvec_vector_query_set_topk(query, 5);
|
||||
zvec_vector_query_set_filter(query, "");
|
||||
zvec_vector_query_set_include_vector(query, true);
|
||||
zvec_vector_query_set_include_doc_id(query, true);
|
||||
|
||||
ZVecDoc **query_results = NULL;
|
||||
size_t result_count = 0;
|
||||
|
||||
error = zvec_collection_query(collection, (const ZVecVectorQuery *)query,
|
||||
&query_results, &result_count);
|
||||
if (handle_error(error, "querying documents") != ZVEC_OK) {
|
||||
query_results = NULL;
|
||||
result_count = 0;
|
||||
}
|
||||
|
||||
printf("Query returned %zu results\n", result_count);
|
||||
|
||||
// Print query results
|
||||
printf("\nQuery Results:\n");
|
||||
for (size_t i = 0; i < result_count; i++) {
|
||||
print_doc(query_results[i], i);
|
||||
}
|
||||
|
||||
// Compare query results
|
||||
for (size_t i = 0; i < result_count && i < DOC_COUNT; i++) {
|
||||
const char *result_pk = zvec_doc_get_pk_pointer(query_results[i]);
|
||||
printf("Comparing query result[%zu]: %s\n", i, result_pk);
|
||||
|
||||
// Find matching original document
|
||||
bool found = false;
|
||||
for (int j = 0; j < DOC_COUNT; j++) {
|
||||
const char *original_pk = zvec_doc_get_pk_pointer(test_docs[j]);
|
||||
if (strcmp(result_pk, original_pk) == 0) {
|
||||
if (compare_documents(test_docs[j], query_results[i])) {
|
||||
printf("✓ Query result %s matches original document\n", result_pk);
|
||||
} else {
|
||||
printf("✗ Query result %s does not match original document\n",
|
||||
result_pk);
|
||||
}
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!found) {
|
||||
printf("⚠ Original document not found for: %s\n", result_pk);
|
||||
}
|
||||
}
|
||||
|
||||
// 7. Filter query test
|
||||
printf("\n=== Filter Query Test ===\n");
|
||||
|
||||
// Create filtered query
|
||||
zvec_vector_query_set_filter(query, "string_field = 'string_field_0'");
|
||||
|
||||
ZVecDoc **filtered_results = NULL;
|
||||
size_t filtered_count = 0;
|
||||
|
||||
error = zvec_collection_query(collection, (const ZVecVectorQuery *)query,
|
||||
&filtered_results, &filtered_count);
|
||||
if (handle_error(error, "filtered querying") == ZVEC_OK) {
|
||||
printf("Filtered query returned %zu results\n", filtered_count);
|
||||
|
||||
// Verify filter results
|
||||
bool filter_correct = true;
|
||||
for (size_t i = 0; i < filtered_count; i++) {
|
||||
// Note: Field value access may require different API
|
||||
// For now, we'll just check that we got results
|
||||
const char *pk = zvec_doc_get_pk_pointer(filtered_results[i]);
|
||||
if (strstr(pk, "doc_") == NULL) {
|
||||
filter_correct = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (filter_correct) {
|
||||
printf("✓ Filter query results are correct\n");
|
||||
} else {
|
||||
printf("✗ Filter query results are incorrect\n");
|
||||
}
|
||||
|
||||
if (filtered_results) {
|
||||
zvec_docs_free(filtered_results, filtered_count);
|
||||
}
|
||||
}
|
||||
|
||||
// 8. Cleanup query results
|
||||
if (query_results) {
|
||||
zvec_docs_free(query_results, result_count);
|
||||
}
|
||||
|
||||
// 9. Cleanup documents
|
||||
for (int i = 0; i < DOC_COUNT; i++) {
|
||||
zvec_doc_destroy(test_docs[i]);
|
||||
}
|
||||
free(test_docs); // Free the array itself
|
||||
|
||||
// 10. Final cleanup
|
||||
cleanup:
|
||||
zvec_collection_destroy(collection);
|
||||
zvec_collection_schema_destroy(schema);
|
||||
|
||||
printf("✓ Document example completed\n");
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,309 @@
|
||||
// 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 <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include "zvec/c_api.h"
|
||||
|
||||
/**
|
||||
* @brief Print error message and return error code
|
||||
*/
|
||||
static ZVecErrorCode handle_error(ZVecErrorCode error, const char *context) {
|
||||
if (error != ZVEC_OK) {
|
||||
char *error_msg = NULL;
|
||||
zvec_get_last_error(&error_msg);
|
||||
fprintf(stderr, "Error in %s: %d - %s\n", context, error,
|
||||
error_msg ? error_msg : "Unknown error");
|
||||
zvec_free(error_msg);
|
||||
}
|
||||
return error;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Field schema creation and management example
|
||||
*/
|
||||
int main() {
|
||||
printf("=== ZVec Field Schema Example ===\n\n");
|
||||
|
||||
ZVecErrorCode error;
|
||||
|
||||
// 1. Create collection schema
|
||||
ZVecCollectionSchema *schema =
|
||||
zvec_collection_schema_create("field_example_collection");
|
||||
if (!schema) {
|
||||
fprintf(stderr, "Failed to create collection schema\n");
|
||||
return -1;
|
||||
}
|
||||
printf("✓ Collection schema created successfully\n");
|
||||
|
||||
// 2. Create different types of index parameters
|
||||
ZVecIndexParams *invert_params =
|
||||
zvec_index_params_create(ZVEC_INDEX_TYPE_INVERT);
|
||||
if (!invert_params) {
|
||||
fprintf(stderr, "Failed to create invert index parameters\n");
|
||||
zvec_collection_schema_destroy(schema);
|
||||
return -1;
|
||||
}
|
||||
zvec_index_params_set_invert_params(invert_params, true, false);
|
||||
|
||||
ZVecIndexParams *hnsw_params = zvec_index_params_create(ZVEC_INDEX_TYPE_HNSW);
|
||||
if (!hnsw_params) {
|
||||
fprintf(stderr, "Failed to create HNSW index parameters\n");
|
||||
zvec_index_params_destroy(invert_params);
|
||||
zvec_collection_schema_destroy(schema);
|
||||
return -1;
|
||||
}
|
||||
zvec_index_params_set_metric_type(hnsw_params, ZVEC_METRIC_TYPE_COSINE);
|
||||
zvec_index_params_set_hnsw_params(hnsw_params, 16, 200);
|
||||
|
||||
ZVecIndexParams *flat_params = zvec_index_params_create(ZVEC_INDEX_TYPE_FLAT);
|
||||
if (!flat_params) {
|
||||
fprintf(stderr, "Failed to create Flat index parameters\n");
|
||||
zvec_index_params_destroy(invert_params);
|
||||
zvec_index_params_destroy(hnsw_params);
|
||||
zvec_collection_schema_destroy(schema);
|
||||
return -1;
|
||||
}
|
||||
zvec_index_params_set_metric_type(flat_params, ZVEC_METRIC_TYPE_L2);
|
||||
|
||||
if (!invert_params || !hnsw_params || !flat_params) {
|
||||
fprintf(stderr, "Failed to create index parameters\n");
|
||||
zvec_index_params_destroy(invert_params);
|
||||
zvec_index_params_destroy(hnsw_params);
|
||||
zvec_index_params_destroy(flat_params);
|
||||
zvec_collection_schema_destroy(schema);
|
||||
return -1;
|
||||
}
|
||||
|
||||
// 3. Create scalar fields with different data types
|
||||
printf("Creating scalar fields...\n");
|
||||
|
||||
// String field with inverted index
|
||||
ZVecFieldSchema *name_field =
|
||||
zvec_field_schema_create("name", ZVEC_DATA_TYPE_STRING, false, 0);
|
||||
if (name_field) {
|
||||
zvec_field_schema_set_index_params(name_field, invert_params);
|
||||
error = zvec_collection_schema_add_field(schema, name_field);
|
||||
if (handle_error(error, "adding name field") == ZVEC_OK) {
|
||||
printf("✓ String field 'name' with inverted index added\n");
|
||||
}
|
||||
}
|
||||
|
||||
// Integer field
|
||||
ZVecFieldSchema *age_field =
|
||||
zvec_field_schema_create("age", ZVEC_DATA_TYPE_INT32, true, 0);
|
||||
if (age_field) {
|
||||
error = zvec_collection_schema_add_field(schema, age_field);
|
||||
if (handle_error(error, "adding age field") == ZVEC_OK) {
|
||||
printf("✓ Integer field 'age' added\n");
|
||||
}
|
||||
}
|
||||
|
||||
// Float field
|
||||
ZVecFieldSchema *score_field =
|
||||
zvec_field_schema_create("score", ZVEC_DATA_TYPE_FLOAT, true, 0);
|
||||
if (score_field) {
|
||||
error = zvec_collection_schema_add_field(schema, score_field);
|
||||
if (handle_error(error, "adding score field") == ZVEC_OK) {
|
||||
printf("✓ Float field 'score' added\n");
|
||||
}
|
||||
}
|
||||
|
||||
// Boolean field
|
||||
ZVecFieldSchema *active_field =
|
||||
zvec_field_schema_create("active", ZVEC_DATA_TYPE_BOOL, false, 0);
|
||||
if (active_field) {
|
||||
error = zvec_collection_schema_add_field(schema, active_field);
|
||||
if (handle_error(error, "adding active field") == ZVEC_OK) {
|
||||
printf("✓ Boolean field 'active' added\n");
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Create vector fields with different dimensions and indexes
|
||||
printf("Creating vector fields...\n");
|
||||
|
||||
// Small dimension vector with HNSW index
|
||||
ZVecFieldSchema *small_vector_field = zvec_field_schema_create(
|
||||
"small_vector", ZVEC_DATA_TYPE_VECTOR_FP32, false, 32);
|
||||
if (small_vector_field) {
|
||||
zvec_field_schema_set_index_params(small_vector_field, hnsw_params);
|
||||
error = zvec_collection_schema_add_field(schema, small_vector_field);
|
||||
if (handle_error(error, "adding small vector field") == ZVEC_OK) {
|
||||
printf(
|
||||
"✓ Small vector field 'small_vector' (32D) with HNSW index added\n");
|
||||
}
|
||||
}
|
||||
|
||||
// Medium dimension vector with Flat index
|
||||
ZVecFieldSchema *medium_vector_field = zvec_field_schema_create(
|
||||
"medium_vector", ZVEC_DATA_TYPE_VECTOR_FP32, false, 128);
|
||||
if (medium_vector_field) {
|
||||
zvec_field_schema_set_index_params(medium_vector_field, flat_params);
|
||||
error = zvec_collection_schema_add_field(schema, medium_vector_field);
|
||||
if (handle_error(error, "adding medium vector field") == ZVEC_OK) {
|
||||
printf(
|
||||
"✓ Medium vector field 'medium_vector' (128D) with Flat index "
|
||||
"added\n");
|
||||
}
|
||||
}
|
||||
|
||||
// Large dimension vector with HNSW index
|
||||
ZVecFieldSchema *large_vector_field = zvec_field_schema_create(
|
||||
"large_vector", ZVEC_DATA_TYPE_VECTOR_FP32, false, 512);
|
||||
if (large_vector_field) {
|
||||
zvec_field_schema_set_index_params(large_vector_field, hnsw_params);
|
||||
error = zvec_collection_schema_add_field(schema, large_vector_field);
|
||||
if (handle_error(error, "adding large vector field") == ZVEC_OK) {
|
||||
printf(
|
||||
"✓ Large vector field 'large_vector' (512D) with HNSW index added\n");
|
||||
}
|
||||
}
|
||||
|
||||
// 5. Create collection with the schema
|
||||
ZVecCollectionOptions *options = zvec_collection_options_create();
|
||||
if (!options) {
|
||||
fprintf(stderr, "Failed to create collection options\n");
|
||||
zvec_collection_schema_destroy(schema);
|
||||
return -1;
|
||||
}
|
||||
ZVecCollection *collection = NULL;
|
||||
|
||||
error = zvec_collection_create_and_open("./field_example_collection", schema,
|
||||
options, &collection);
|
||||
zvec_collection_options_destroy(options);
|
||||
if (handle_error(error, "creating collection") != ZVEC_OK) {
|
||||
zvec_collection_schema_destroy(schema);
|
||||
return -1;
|
||||
}
|
||||
printf("✓ Collection created successfully\n");
|
||||
|
||||
// 6. Create test documents with various field types
|
||||
printf("Creating test documents...\n");
|
||||
|
||||
ZVecDoc *doc1 = zvec_doc_create();
|
||||
ZVecDoc *doc2 = zvec_doc_create();
|
||||
|
||||
if (!doc1 || !doc2) {
|
||||
fprintf(stderr, "Failed to create documents\n");
|
||||
goto cleanup;
|
||||
}
|
||||
|
||||
// Document 1
|
||||
zvec_doc_set_pk(doc1, "user1");
|
||||
zvec_doc_add_field_by_value(doc1, "name", ZVEC_DATA_TYPE_STRING,
|
||||
"Alice Johnson", strlen("Alice Johnson"));
|
||||
int32_t age1 = 28;
|
||||
zvec_doc_add_field_by_value(doc1, "age", ZVEC_DATA_TYPE_INT32, &age1,
|
||||
sizeof(age1));
|
||||
float score1 = 87.5f;
|
||||
zvec_doc_add_field_by_value(doc1, "score", ZVEC_DATA_TYPE_FLOAT, &score1,
|
||||
sizeof(score1));
|
||||
bool active1 = true;
|
||||
zvec_doc_add_field_by_value(doc1, "active", ZVEC_DATA_TYPE_BOOL, &active1,
|
||||
sizeof(active1));
|
||||
|
||||
// Add vector data
|
||||
float small_vec1[32];
|
||||
float medium_vec1[128];
|
||||
float large_vec1[512];
|
||||
|
||||
for (int i = 0; i < 32; i++) small_vec1[i] = (float)i / 32.0f;
|
||||
for (int i = 0; i < 128; i++) medium_vec1[i] = (float)i / 128.0f;
|
||||
for (int i = 0; i < 512; i++) large_vec1[i] = (float)i / 512.0f;
|
||||
|
||||
zvec_doc_add_field_by_value(doc1, "small_vector", ZVEC_DATA_TYPE_VECTOR_FP32,
|
||||
small_vec1, 32 * sizeof(float));
|
||||
zvec_doc_add_field_by_value(doc1, "medium_vector", ZVEC_DATA_TYPE_VECTOR_FP32,
|
||||
medium_vec1, 128 * sizeof(float));
|
||||
zvec_doc_add_field_by_value(doc1, "large_vector", ZVEC_DATA_TYPE_VECTOR_FP32,
|
||||
large_vec1, 512 * sizeof(float));
|
||||
|
||||
// Document 2
|
||||
zvec_doc_set_pk(doc2, "user2");
|
||||
zvec_doc_add_field_by_value(doc2, "name", ZVEC_DATA_TYPE_STRING, "Bob Smith",
|
||||
strlen("Bob Smith"));
|
||||
int32_t age2 = 35;
|
||||
zvec_doc_add_field_by_value(doc2, "age", ZVEC_DATA_TYPE_INT32, &age2,
|
||||
sizeof(age2));
|
||||
float score2 = 92.0f;
|
||||
zvec_doc_add_field_by_value(doc2, "score", ZVEC_DATA_TYPE_FLOAT, &score2,
|
||||
sizeof(score2));
|
||||
bool active2 = false;
|
||||
zvec_doc_add_field_by_value(doc2, "active", ZVEC_DATA_TYPE_BOOL, &active2,
|
||||
sizeof(active2));
|
||||
|
||||
// Add vector data
|
||||
float small_vec2[32];
|
||||
float medium_vec2[128];
|
||||
float large_vec2[512];
|
||||
|
||||
for (int i = 0; i < 32; i++) small_vec2[i] = (float)(32 - i) / 32.0f;
|
||||
for (int i = 0; i < 128; i++) medium_vec2[i] = (float)(128 - i) / 128.0f;
|
||||
for (int i = 0; i < 512; i++) large_vec2[i] = (float)(512 - i) / 512.0f;
|
||||
|
||||
zvec_doc_add_field_by_value(doc2, "small_vector", ZVEC_DATA_TYPE_VECTOR_FP32,
|
||||
small_vec2, 32 * sizeof(float));
|
||||
zvec_doc_add_field_by_value(doc2, "medium_vector", ZVEC_DATA_TYPE_VECTOR_FP32,
|
||||
medium_vec2, 128 * sizeof(float));
|
||||
zvec_doc_add_field_by_value(doc2, "large_vector", ZVEC_DATA_TYPE_VECTOR_FP32,
|
||||
large_vec2, 512 * sizeof(float));
|
||||
|
||||
// 7. Insert documents
|
||||
ZVecDoc *docs[] = {doc1, doc2};
|
||||
size_t success_count = 0, error_count = 0;
|
||||
error = zvec_collection_insert(collection, (const ZVecDoc **)docs, 2,
|
||||
&success_count, &error_count);
|
||||
if (handle_error(error, "inserting documents") == ZVEC_OK) {
|
||||
printf("✓ Documents inserted - Success: %zu, Failed: %zu\n", success_count,
|
||||
error_count);
|
||||
}
|
||||
|
||||
// 8. Flush and test queries
|
||||
zvec_collection_flush(collection);
|
||||
printf("✓ Collection flushed\n");
|
||||
|
||||
// Test vector query on medium vector field
|
||||
ZVecVectorQuery *query = zvec_vector_query_create();
|
||||
if (!query) {
|
||||
fprintf(stderr, "Failed to create vector query\n");
|
||||
goto cleanup;
|
||||
}
|
||||
zvec_vector_query_set_field_name(query, "medium_vector");
|
||||
zvec_vector_query_set_query_vector(query, medium_vec1, 128 * sizeof(float));
|
||||
zvec_vector_query_set_topk(query, 2);
|
||||
zvec_vector_query_set_filter(query, "");
|
||||
zvec_vector_query_set_include_vector(query, false);
|
||||
zvec_vector_query_set_include_doc_id(query, true);
|
||||
|
||||
ZVecDoc **results = NULL;
|
||||
size_t result_count = 0;
|
||||
error = zvec_collection_query(collection, (const ZVecVectorQuery *)query,
|
||||
&results, &result_count);
|
||||
if (error == ZVEC_OK) {
|
||||
printf("✓ Vector query successful - Found %zu results\n", result_count);
|
||||
zvec_docs_free(results, result_count);
|
||||
}
|
||||
zvec_vector_query_destroy(query);
|
||||
|
||||
// 9. Cleanup
|
||||
cleanup:
|
||||
if (doc1) zvec_doc_destroy(doc1);
|
||||
if (doc2) zvec_doc_destroy(doc2);
|
||||
zvec_collection_destroy(collection);
|
||||
zvec_collection_schema_destroy(schema);
|
||||
|
||||
printf("✓ Field schema example completed\n");
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,389 @@
|
||||
// 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 <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include "zvec/c_api.h"
|
||||
|
||||
/**
|
||||
* @brief Print error message and return error code
|
||||
*/
|
||||
static ZVecErrorCode handle_error(ZVecErrorCode error, const char *context) {
|
||||
if (error != ZVEC_OK) {
|
||||
char *error_msg = NULL;
|
||||
zvec_get_last_error(&error_msg);
|
||||
fprintf(stderr, "Error in %s: %d - %s\n", context, error,
|
||||
error_msg ? error_msg : "Unknown error");
|
||||
zvec_free(error_msg);
|
||||
}
|
||||
return error;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Index creation and management example
|
||||
*/
|
||||
int main() {
|
||||
printf("=== ZVec Index Example ===\n\n");
|
||||
|
||||
ZVecErrorCode error;
|
||||
|
||||
// 1. Create collection schema
|
||||
ZVecCollectionSchema *schema =
|
||||
zvec_collection_schema_create("index_example_collection");
|
||||
if (!schema) {
|
||||
fprintf(stderr, "Failed to create collection schema\n");
|
||||
return -1;
|
||||
}
|
||||
printf("✓ Collection schema created successfully\n");
|
||||
|
||||
// 2. Create different index parameter configurations
|
||||
printf("Creating index parameters...\n");
|
||||
|
||||
// Inverted index parameters
|
||||
ZVecIndexParams *invert_params_standard =
|
||||
zvec_index_params_create(ZVEC_INDEX_TYPE_INVERT);
|
||||
if (!invert_params_standard) {
|
||||
fprintf(stderr, "Failed to create invert index parameters (standard)\n");
|
||||
zvec_collection_schema_destroy(schema);
|
||||
return -1;
|
||||
}
|
||||
zvec_index_params_set_invert_params(invert_params_standard, true, false);
|
||||
|
||||
ZVecIndexParams *invert_params_extended =
|
||||
zvec_index_params_create(ZVEC_INDEX_TYPE_INVERT);
|
||||
if (!invert_params_extended) {
|
||||
fprintf(stderr, "Failed to create invert index parameters (extended)\n");
|
||||
zvec_index_params_destroy(invert_params_standard);
|
||||
zvec_collection_schema_destroy(schema);
|
||||
return -1;
|
||||
}
|
||||
zvec_index_params_set_invert_params(invert_params_extended, true, true);
|
||||
|
||||
// HNSW index parameters with different configurations
|
||||
ZVecIndexParams *hnsw_params_fast =
|
||||
zvec_index_params_create(ZVEC_INDEX_TYPE_HNSW);
|
||||
if (!hnsw_params_fast) {
|
||||
fprintf(stderr, "Failed to create HNSW index parameters (fast)\n");
|
||||
zvec_index_params_destroy(invert_params_standard);
|
||||
zvec_index_params_destroy(invert_params_extended);
|
||||
zvec_collection_schema_destroy(schema);
|
||||
return -1;
|
||||
}
|
||||
zvec_index_params_set_metric_type(hnsw_params_fast, ZVEC_METRIC_TYPE_L2);
|
||||
zvec_index_params_set_hnsw_params(hnsw_params_fast, 16, 100);
|
||||
|
||||
ZVecIndexParams *hnsw_params_balanced =
|
||||
zvec_index_params_create(ZVEC_INDEX_TYPE_HNSW);
|
||||
if (!hnsw_params_balanced) {
|
||||
fprintf(stderr, "Failed to create HNSW index parameters (balanced)\n");
|
||||
zvec_index_params_destroy(invert_params_standard);
|
||||
zvec_index_params_destroy(invert_params_extended);
|
||||
zvec_index_params_destroy(hnsw_params_fast);
|
||||
zvec_collection_schema_destroy(schema);
|
||||
return -1;
|
||||
}
|
||||
zvec_index_params_set_metric_type(hnsw_params_balanced,
|
||||
ZVEC_METRIC_TYPE_COSINE);
|
||||
zvec_index_params_set_hnsw_params(hnsw_params_balanced, 32, 200);
|
||||
|
||||
ZVecIndexParams *hnsw_params_accurate =
|
||||
zvec_index_params_create(ZVEC_INDEX_TYPE_HNSW);
|
||||
if (!hnsw_params_accurate) {
|
||||
fprintf(stderr, "Failed to create HNSW index parameters (accurate)\n");
|
||||
zvec_index_params_destroy(invert_params_standard);
|
||||
zvec_index_params_destroy(invert_params_extended);
|
||||
zvec_index_params_destroy(hnsw_params_fast);
|
||||
zvec_index_params_destroy(hnsw_params_balanced);
|
||||
zvec_collection_schema_destroy(schema);
|
||||
return -1;
|
||||
}
|
||||
zvec_index_params_set_metric_type(hnsw_params_accurate, ZVEC_METRIC_TYPE_IP);
|
||||
zvec_index_params_set_hnsw_params(hnsw_params_accurate, 64, 400);
|
||||
|
||||
// Flat index parameters
|
||||
ZVecIndexParams *flat_params_l2 =
|
||||
zvec_index_params_create(ZVEC_INDEX_TYPE_FLAT);
|
||||
if (!flat_params_l2) {
|
||||
fprintf(stderr, "Failed to create Flat index parameters (L2)\n");
|
||||
zvec_index_params_destroy(invert_params_standard);
|
||||
zvec_index_params_destroy(invert_params_extended);
|
||||
zvec_index_params_destroy(hnsw_params_fast);
|
||||
zvec_index_params_destroy(hnsw_params_balanced);
|
||||
zvec_index_params_destroy(hnsw_params_accurate);
|
||||
zvec_collection_schema_destroy(schema);
|
||||
return -1;
|
||||
}
|
||||
zvec_index_params_set_metric_type(flat_params_l2, ZVEC_METRIC_TYPE_L2);
|
||||
|
||||
ZVecIndexParams *flat_params_cosine =
|
||||
zvec_index_params_create(ZVEC_INDEX_TYPE_FLAT);
|
||||
if (!flat_params_cosine) {
|
||||
fprintf(stderr, "Failed to create Flat index parameters (cosine)\n");
|
||||
zvec_index_params_destroy(invert_params_standard);
|
||||
zvec_index_params_destroy(invert_params_extended);
|
||||
zvec_index_params_destroy(hnsw_params_fast);
|
||||
zvec_index_params_destroy(hnsw_params_balanced);
|
||||
zvec_index_params_destroy(hnsw_params_accurate);
|
||||
zvec_index_params_destroy(flat_params_l2);
|
||||
zvec_collection_schema_destroy(schema);
|
||||
return -1;
|
||||
}
|
||||
zvec_index_params_set_metric_type(flat_params_cosine,
|
||||
ZVEC_METRIC_TYPE_COSINE);
|
||||
|
||||
// 3. Create fields with different index types
|
||||
printf("Creating fields with various index types...\n");
|
||||
|
||||
// Fields with inverted indexes
|
||||
ZVecFieldSchema *id_field =
|
||||
zvec_field_schema_create("id", ZVEC_DATA_TYPE_STRING, false, 0);
|
||||
if (id_field) {
|
||||
zvec_field_schema_set_index_params(id_field, invert_params_standard);
|
||||
error = zvec_collection_schema_add_field(schema, id_field);
|
||||
if (handle_error(error, "adding ID field") == ZVEC_OK) {
|
||||
printf("✓ ID field with standard inverted index added\n");
|
||||
}
|
||||
}
|
||||
|
||||
ZVecFieldSchema *category_field =
|
||||
zvec_field_schema_create("category", ZVEC_DATA_TYPE_STRING, true, 0);
|
||||
if (category_field) {
|
||||
zvec_field_schema_set_index_params(category_field, invert_params_extended);
|
||||
error = zvec_collection_schema_add_field(schema, category_field);
|
||||
if (handle_error(error, "adding category field") == ZVEC_OK) {
|
||||
printf("✓ Category field with extended inverted index added\n");
|
||||
}
|
||||
}
|
||||
|
||||
// Vector fields with HNSW indexes (different configurations)
|
||||
ZVecFieldSchema *fast_search_field = zvec_field_schema_create(
|
||||
"fast_vector", ZVEC_DATA_TYPE_VECTOR_FP32, false, 64);
|
||||
if (fast_search_field) {
|
||||
zvec_field_schema_set_index_params(fast_search_field, hnsw_params_fast);
|
||||
error = zvec_collection_schema_add_field(schema, fast_search_field);
|
||||
if (handle_error(error, "adding fast search field") == ZVEC_OK) {
|
||||
printf("✓ Fast search vector field (64D) with HNSW index added\n");
|
||||
}
|
||||
}
|
||||
|
||||
ZVecFieldSchema *balanced_field = zvec_field_schema_create(
|
||||
"balanced_vector", ZVEC_DATA_TYPE_VECTOR_FP32, false, 128);
|
||||
if (balanced_field) {
|
||||
zvec_field_schema_set_index_params(balanced_field, hnsw_params_balanced);
|
||||
error = zvec_collection_schema_add_field(schema, balanced_field);
|
||||
if (handle_error(error, "adding balanced field") == ZVEC_OK) {
|
||||
printf("✓ Balanced vector field (128D) with HNSW index added\n");
|
||||
}
|
||||
}
|
||||
|
||||
ZVecFieldSchema *accurate_field = zvec_field_schema_create(
|
||||
"accurate_vector", ZVEC_DATA_TYPE_VECTOR_FP32, false, 256);
|
||||
if (accurate_field) {
|
||||
zvec_field_schema_set_index_params(accurate_field, hnsw_params_accurate);
|
||||
error = zvec_collection_schema_add_field(schema, accurate_field);
|
||||
if (handle_error(error, "adding accurate field") == ZVEC_OK) {
|
||||
printf("✓ Accurate vector field (256D) with HNSW index added\n");
|
||||
}
|
||||
}
|
||||
|
||||
// Vector field with Flat index
|
||||
ZVecFieldSchema *exact_field = zvec_field_schema_create(
|
||||
"exact_vector", ZVEC_DATA_TYPE_VECTOR_FP32, false, 32);
|
||||
if (exact_field) {
|
||||
zvec_field_schema_set_index_params(exact_field, flat_params_l2);
|
||||
error = zvec_collection_schema_add_field(schema, exact_field);
|
||||
if (handle_error(error, "adding exact field") == ZVEC_OK) {
|
||||
printf("✓ Exact search vector field (32D) with Flat index added\n");
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Create collection
|
||||
ZVecCollectionOptions *options = zvec_collection_options_create();
|
||||
if (!options) {
|
||||
fprintf(stderr, "Failed to create collection options\n");
|
||||
zvec_collection_schema_destroy(schema);
|
||||
return -1;
|
||||
}
|
||||
ZVecCollection *collection = NULL;
|
||||
|
||||
error = zvec_collection_create_and_open("./index_example_collection", schema,
|
||||
options, &collection);
|
||||
zvec_collection_options_destroy(options);
|
||||
if (handle_error(error, "creating collection") != ZVEC_OK) {
|
||||
zvec_collection_schema_destroy(schema);
|
||||
return -1;
|
||||
}
|
||||
printf("✓ Collection created successfully\n");
|
||||
|
||||
// 5. Create test data
|
||||
printf("Creating test documents...\n");
|
||||
|
||||
ZVecDoc *docs[3];
|
||||
for (int i = 0; i < 3; i++) {
|
||||
docs[i] = zvec_doc_create();
|
||||
if (!docs[i]) {
|
||||
fprintf(stderr, "Failed to create document %d\n", i);
|
||||
// Cleanup
|
||||
for (int j = 0; j < i; j++) {
|
||||
zvec_doc_destroy(docs[j]);
|
||||
}
|
||||
goto cleanup;
|
||||
}
|
||||
}
|
||||
|
||||
// Prepare vector data
|
||||
float fast_vec[3][64];
|
||||
float balanced_vec[3][128];
|
||||
float accurate_vec[3][256];
|
||||
float exact_vec[3][32];
|
||||
|
||||
// Generate different vector patterns for testing
|
||||
for (int doc_idx = 0; doc_idx < 3; doc_idx++) {
|
||||
for (int i = 0; i < 64; i++) {
|
||||
fast_vec[doc_idx][i] = (float)(doc_idx * 64 + i) / (64.0f * 3.0f);
|
||||
}
|
||||
for (int i = 0; i < 128; i++) {
|
||||
balanced_vec[doc_idx][i] = (float)(doc_idx * 128 + i) / (128.0f * 3.0f);
|
||||
}
|
||||
for (int i = 0; i < 256; i++) {
|
||||
accurate_vec[doc_idx][i] = (float)(doc_idx * 256 + i) / (256.0f * 3.0f);
|
||||
}
|
||||
for (int i = 0; i < 32; i++) {
|
||||
exact_vec[doc_idx][i] = (float)(doc_idx * 32 + i) / (32.0f * 3.0f);
|
||||
}
|
||||
}
|
||||
|
||||
// Populate documents
|
||||
for (int i = 0; i < 3; i++) {
|
||||
char pk[16];
|
||||
snprintf(pk, sizeof(pk), "doc%d", i + 1);
|
||||
zvec_doc_set_pk(docs[i], pk);
|
||||
|
||||
char id_val[16];
|
||||
snprintf(id_val, sizeof(id_val), "ID_%d", i + 1);
|
||||
zvec_doc_add_field_by_value(docs[i], "id", ZVEC_DATA_TYPE_STRING, id_val,
|
||||
strlen(id_val));
|
||||
|
||||
char category_val[16];
|
||||
snprintf(category_val, sizeof(category_val), "cat_%d", (i % 2) + 1);
|
||||
zvec_doc_add_field_by_value(docs[i], "category", ZVEC_DATA_TYPE_STRING,
|
||||
category_val, strlen(category_val));
|
||||
|
||||
zvec_doc_add_field_by_value(docs[i], "fast_vector",
|
||||
ZVEC_DATA_TYPE_VECTOR_FP32, fast_vec[i],
|
||||
64 * sizeof(float));
|
||||
zvec_doc_add_field_by_value(docs[i], "balanced_vector",
|
||||
ZVEC_DATA_TYPE_VECTOR_FP32, balanced_vec[i],
|
||||
128 * sizeof(float));
|
||||
zvec_doc_add_field_by_value(docs[i], "accurate_vector",
|
||||
ZVEC_DATA_TYPE_VECTOR_FP32, accurate_vec[i],
|
||||
256 * sizeof(float));
|
||||
zvec_doc_add_field_by_value(docs[i], "exact_vector",
|
||||
ZVEC_DATA_TYPE_VECTOR_FP32, exact_vec[i],
|
||||
32 * sizeof(float));
|
||||
}
|
||||
|
||||
// 6. Insert documents
|
||||
size_t success_count = 0, error_count = 0;
|
||||
error = zvec_collection_insert(collection, (const ZVecDoc **)docs, 3,
|
||||
&success_count, &error_count);
|
||||
if (handle_error(error, "inserting documents") == ZVEC_OK) {
|
||||
printf("✓ Documents inserted - Success: %zu, Failed: %zu\n", success_count,
|
||||
error_count);
|
||||
}
|
||||
|
||||
// Cleanup documents
|
||||
for (int i = 0; i < 3; i++) {
|
||||
zvec_doc_destroy(docs[i]);
|
||||
}
|
||||
|
||||
// 7. Flush collection to build indexes
|
||||
error = zvec_collection_flush(collection);
|
||||
if (handle_error(error, "flushing collection") == ZVEC_OK) {
|
||||
printf("✓ Collection flushed - indexes built\n");
|
||||
}
|
||||
|
||||
// 8. Test different query types
|
||||
printf("Testing various index queries...\n");
|
||||
|
||||
// Test HNSW query (balanced)
|
||||
ZVecVectorQuery *hnsw_query = zvec_vector_query_create();
|
||||
if (!hnsw_query) {
|
||||
fprintf(stderr, "Failed to create HNSW query\n");
|
||||
goto cleanup;
|
||||
}
|
||||
zvec_vector_query_set_field_name(hnsw_query, "balanced_vector");
|
||||
zvec_vector_query_set_query_vector(hnsw_query, balanced_vec[0],
|
||||
128 * sizeof(float));
|
||||
zvec_vector_query_set_topk(hnsw_query, 2);
|
||||
zvec_vector_query_set_filter(hnsw_query, "");
|
||||
zvec_vector_query_set_include_vector(hnsw_query, false);
|
||||
zvec_vector_query_set_include_doc_id(hnsw_query, true);
|
||||
|
||||
ZVecDoc **hnsw_results = NULL;
|
||||
size_t hnsw_result_count = 0;
|
||||
error = zvec_collection_query(collection, (const ZVecVectorQuery *)hnsw_query,
|
||||
&hnsw_results, &hnsw_result_count);
|
||||
if (error == ZVEC_OK) {
|
||||
printf("✓ HNSW query successful - Found %zu results\n", hnsw_result_count);
|
||||
zvec_docs_free(hnsw_results, hnsw_result_count);
|
||||
}
|
||||
zvec_vector_query_destroy(hnsw_query);
|
||||
|
||||
// Test Flat query (exact)
|
||||
ZVecVectorQuery *flat_query = zvec_vector_query_create();
|
||||
if (!flat_query) {
|
||||
fprintf(stderr, "Failed to create Flat query\n");
|
||||
goto cleanup;
|
||||
}
|
||||
zvec_vector_query_set_field_name(flat_query, "exact_vector");
|
||||
zvec_vector_query_set_query_vector(flat_query, exact_vec[0],
|
||||
32 * sizeof(float));
|
||||
zvec_vector_query_set_topk(flat_query, 2);
|
||||
zvec_vector_query_set_filter(flat_query, "");
|
||||
zvec_vector_query_set_include_vector(flat_query, false);
|
||||
zvec_vector_query_set_include_doc_id(flat_query, true);
|
||||
|
||||
ZVecDoc **flat_results = NULL;
|
||||
size_t flat_result_count = 0;
|
||||
error = zvec_collection_query(collection, (const ZVecVectorQuery *)flat_query,
|
||||
&flat_results, &flat_result_count);
|
||||
if (error == ZVEC_OK) {
|
||||
printf("✓ Flat (exact) query successful - Found %zu results\n",
|
||||
flat_result_count);
|
||||
zvec_docs_free(flat_results, flat_result_count);
|
||||
}
|
||||
zvec_vector_query_destroy(flat_query);
|
||||
|
||||
// 9. Performance comparison information
|
||||
printf("\nIndex Performance Characteristics:\n");
|
||||
printf("- Inverted Index: Fast text search, supports filtering\n");
|
||||
printf(
|
||||
"- HNSW Index: Approximate nearest neighbor search, good balance of "
|
||||
"speed/accuracy\n");
|
||||
printf("- Flat Index: Exact search, slower but 100%% accurate\n");
|
||||
printf(
|
||||
"- Trade-off: Speed vs Accuracy - choose based on your requirements\n");
|
||||
|
||||
// 10. Cleanup
|
||||
cleanup:
|
||||
zvec_collection_destroy(collection);
|
||||
zvec_collection_schema_destroy(schema);
|
||||
|
||||
// Cleanup index parameters
|
||||
|
||||
printf("✓ Index example completed\n");
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,307 @@
|
||||
// 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 <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <time.h>
|
||||
#include "zvec/c_api.h"
|
||||
|
||||
/**
|
||||
* @brief Print error message and return error code
|
||||
*/
|
||||
static ZVecErrorCode handle_error(ZVecErrorCode error, const char *context) {
|
||||
if (error != ZVEC_OK) {
|
||||
char *error_msg = NULL;
|
||||
zvec_get_last_error(&error_msg);
|
||||
fprintf(stderr, "Error in %s: %d - %s\n", context, error,
|
||||
error_msg ? error_msg : "Unknown error");
|
||||
zvec_free(error_msg);
|
||||
}
|
||||
return error;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Create test vector data
|
||||
*/
|
||||
static float *create_test_vector(size_t dimension) {
|
||||
float *vector = malloc(dimension * sizeof(float));
|
||||
if (!vector) {
|
||||
return NULL;
|
||||
}
|
||||
|
||||
for (size_t i = 0; i < dimension; i++) {
|
||||
vector[i] = (float)rand() / RAND_MAX;
|
||||
}
|
||||
|
||||
return vector;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Optimized C API usage example with performance considerations
|
||||
*/
|
||||
int main() {
|
||||
printf("=== ZVec Optimized C API Example ===\n\n");
|
||||
|
||||
// Get version information
|
||||
const char *version = zvec_get_version();
|
||||
printf("ZVec Version: %s\n\n", version ? version : "Unknown");
|
||||
|
||||
ZVecErrorCode error;
|
||||
|
||||
// 1. Create optimized collection schema
|
||||
ZVecCollectionSchema *schema =
|
||||
zvec_collection_schema_create("optimized_example_collection");
|
||||
if (!schema) {
|
||||
fprintf(stderr, "Failed to create collection schema\n");
|
||||
return -1;
|
||||
}
|
||||
printf("✓ Collection schema created\n");
|
||||
|
||||
// 2. Create optimized index parameters
|
||||
ZVecIndexParams *hnsw_params = zvec_index_params_create(ZVEC_INDEX_TYPE_HNSW);
|
||||
if (!hnsw_params) {
|
||||
fprintf(stderr, "Failed to create HNSW index parameters\n");
|
||||
zvec_collection_schema_destroy(schema);
|
||||
return -1;
|
||||
}
|
||||
zvec_index_params_set_metric_type(hnsw_params, ZVEC_METRIC_TYPE_L2);
|
||||
zvec_index_params_set_hnsw_params(hnsw_params, 32, 200);
|
||||
|
||||
// 3. Create fields with optimized configuration
|
||||
ZVecFieldSchema *id_field =
|
||||
zvec_field_schema_create("id", ZVEC_DATA_TYPE_STRING, false, 0);
|
||||
ZVecFieldSchema *text_field =
|
||||
zvec_field_schema_create("text", ZVEC_DATA_TYPE_STRING, true, 0);
|
||||
ZVecFieldSchema *embedding_field = zvec_field_schema_create(
|
||||
"embedding", ZVEC_DATA_TYPE_VECTOR_FP32, false, 128);
|
||||
|
||||
if (!id_field || !text_field || !embedding_field) {
|
||||
fprintf(stderr, "Failed to create field schemas\n");
|
||||
goto cleanup_params;
|
||||
}
|
||||
|
||||
// Set indexes
|
||||
zvec_field_schema_set_index_params(embedding_field, hnsw_params);
|
||||
|
||||
// Add fields to schema
|
||||
error = zvec_collection_schema_add_field(schema, id_field);
|
||||
if (handle_error(error, "adding ID field") != ZVEC_OK) goto cleanup_fields;
|
||||
|
||||
error = zvec_collection_schema_add_field(schema, text_field);
|
||||
if (handle_error(error, "adding text field") != ZVEC_OK) goto cleanup_fields;
|
||||
|
||||
error = zvec_collection_schema_add_field(schema, embedding_field);
|
||||
if (handle_error(error, "adding embedding field") != ZVEC_OK)
|
||||
goto cleanup_fields;
|
||||
|
||||
printf("✓ Fields configured with indexes\n");
|
||||
|
||||
// 4. Create collection with optimized options
|
||||
ZVecCollectionOptions *options = zvec_collection_options_create();
|
||||
if (!options) {
|
||||
fprintf(stderr, "Failed to create collection options\n");
|
||||
goto cleanup_fields;
|
||||
}
|
||||
zvec_collection_options_set_enable_mmap(
|
||||
options, true); // Enable memory mapping for better performance
|
||||
|
||||
ZVecCollection *collection = NULL;
|
||||
error = zvec_collection_create_and_open("./optimized_example_collection",
|
||||
schema, options, &collection);
|
||||
zvec_collection_options_destroy(options);
|
||||
if (handle_error(error, "creating collection") != ZVEC_OK) {
|
||||
goto cleanup_fields;
|
||||
}
|
||||
printf("✓ Collection created with optimized settings\n");
|
||||
|
||||
// 5. Bulk insert test data
|
||||
const size_t DOC_COUNT = 1000;
|
||||
const size_t BATCH_SIZE = 100;
|
||||
|
||||
printf("Inserting %zu documents in batches of %zu...\n", DOC_COUNT,
|
||||
BATCH_SIZE);
|
||||
|
||||
clock_t start_time = clock();
|
||||
|
||||
for (size_t batch_start = 0; batch_start < DOC_COUNT;
|
||||
batch_start += BATCH_SIZE) {
|
||||
size_t current_batch_size = (batch_start + BATCH_SIZE > DOC_COUNT)
|
||||
? DOC_COUNT - batch_start
|
||||
: BATCH_SIZE;
|
||||
|
||||
ZVecDoc **batch_docs = malloc(current_batch_size * sizeof(ZVecDoc *));
|
||||
if (!batch_docs) {
|
||||
fprintf(stderr, "Failed to allocate batch documents\n");
|
||||
break;
|
||||
}
|
||||
|
||||
// Create batch documents
|
||||
for (size_t i = 0; i < current_batch_size; i++) {
|
||||
batch_docs[i] = zvec_doc_create();
|
||||
if (!batch_docs[i]) {
|
||||
fprintf(stderr, "Failed to create document\n");
|
||||
// Cleanup previous documents in batch
|
||||
for (size_t j = 0; j < i; j++) {
|
||||
zvec_doc_destroy(batch_docs[j]);
|
||||
}
|
||||
free(batch_docs);
|
||||
goto cleanup_collection;
|
||||
}
|
||||
|
||||
size_t doc_id = batch_start + i;
|
||||
char pk[32];
|
||||
snprintf(pk, sizeof(pk), "doc_%zu", doc_id);
|
||||
zvec_doc_set_pk(batch_docs[i], pk);
|
||||
|
||||
// Add ID field
|
||||
char id_str[32];
|
||||
snprintf(id_str, sizeof(id_str), "ID_%zu", doc_id);
|
||||
zvec_doc_add_field_by_value(batch_docs[i], "id", ZVEC_DATA_TYPE_STRING,
|
||||
id_str, strlen(id_str));
|
||||
|
||||
// Add text field
|
||||
char text_str[64];
|
||||
snprintf(text_str, sizeof(text_str),
|
||||
"Document number %zu with sample text", doc_id);
|
||||
zvec_doc_add_field_by_value(batch_docs[i], "text", ZVEC_DATA_TYPE_STRING,
|
||||
text_str, strlen(text_str));
|
||||
|
||||
// Add vector field
|
||||
float *vector = create_test_vector(128);
|
||||
if (vector) {
|
||||
zvec_doc_add_field_by_value(batch_docs[i], "embedding",
|
||||
ZVEC_DATA_TYPE_VECTOR_FP32, vector,
|
||||
128 * sizeof(float));
|
||||
free(vector);
|
||||
}
|
||||
}
|
||||
|
||||
// Insert batch
|
||||
size_t success_count, error_count;
|
||||
error = zvec_collection_insert(collection, (const ZVecDoc **)batch_docs,
|
||||
current_batch_size, &success_count,
|
||||
&error_count);
|
||||
if (handle_error(error, "inserting batch") != ZVEC_OK) {
|
||||
// Cleanup batch documents
|
||||
for (size_t i = 0; i < current_batch_size; i++) {
|
||||
zvec_doc_destroy(batch_docs[i]);
|
||||
}
|
||||
free(batch_docs);
|
||||
goto cleanup_collection;
|
||||
}
|
||||
|
||||
printf(" Batch %zu-%zu: %zu successful, %zu failed\n", batch_start,
|
||||
batch_start + current_batch_size - 1, success_count, error_count);
|
||||
|
||||
// Cleanup batch documents
|
||||
for (size_t i = 0; i < current_batch_size; i++) {
|
||||
zvec_doc_destroy(batch_docs[i]);
|
||||
}
|
||||
free(batch_docs);
|
||||
}
|
||||
|
||||
clock_t insert_end_time = clock();
|
||||
double insert_time =
|
||||
((double)(insert_end_time - start_time)) / CLOCKS_PER_SEC;
|
||||
printf("✓ Bulk insertion completed in %.3f seconds (%.0f docs/sec)\n",
|
||||
insert_time, DOC_COUNT / insert_time);
|
||||
|
||||
// 6. Flush and optimize collection
|
||||
printf("Flushing and optimizing collection...\n");
|
||||
zvec_collection_flush(collection);
|
||||
zvec_collection_optimize(collection);
|
||||
printf("✓ Collection optimized\n");
|
||||
|
||||
// 7. Performance query test
|
||||
printf("Testing query performance...\n");
|
||||
|
||||
float *query_vector = create_test_vector(128);
|
||||
if (!query_vector) {
|
||||
fprintf(stderr, "Failed to create query vector\n");
|
||||
goto cleanup_collection;
|
||||
}
|
||||
|
||||
ZVecVectorQuery *query = zvec_vector_query_create();
|
||||
if (!query) {
|
||||
fprintf(stderr, "Failed to create vector query\n");
|
||||
free(query_vector);
|
||||
goto cleanup_collection;
|
||||
}
|
||||
zvec_vector_query_set_field_name(query, "embedding");
|
||||
zvec_vector_query_set_query_vector(query, query_vector, 128 * sizeof(float));
|
||||
zvec_vector_query_set_topk(query, 10);
|
||||
zvec_vector_query_set_filter(query, "");
|
||||
zvec_vector_query_set_include_vector(query, false);
|
||||
zvec_vector_query_set_include_doc_id(query, true);
|
||||
|
||||
const int QUERY_COUNT = 100;
|
||||
start_time = clock();
|
||||
|
||||
for (int q = 0; q < QUERY_COUNT; q++) {
|
||||
ZVecDoc **results = NULL;
|
||||
size_t result_count = 0;
|
||||
|
||||
error = zvec_collection_query(collection, (const ZVecVectorQuery *)query,
|
||||
&results, &result_count);
|
||||
if (error != ZVEC_OK) {
|
||||
char *error_msg = NULL;
|
||||
zvec_get_last_error(&error_msg);
|
||||
printf("Query %d failed: %s\n", q,
|
||||
error_msg ? error_msg : "Unknown error");
|
||||
zvec_free(error_msg);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (results) {
|
||||
zvec_docs_free(results, result_count);
|
||||
}
|
||||
}
|
||||
|
||||
clock_t query_end_time = clock();
|
||||
double query_time = ((double)(query_end_time - start_time)) / CLOCKS_PER_SEC;
|
||||
double avg_query_time = (query_time * 1000) / QUERY_COUNT;
|
||||
|
||||
printf("✓ Performance test completed\n");
|
||||
printf(" Average query time: %.2f ms\n", avg_query_time);
|
||||
printf(" Queries per second: %.0f\n", 1000.0 / avg_query_time);
|
||||
|
||||
free(query_vector);
|
||||
zvec_vector_query_destroy(query);
|
||||
|
||||
// 8. Memory usage information
|
||||
ZVecCollectionStats *stats = NULL;
|
||||
error = zvec_collection_get_stats(collection, &stats);
|
||||
if (error == ZVEC_OK && stats) {
|
||||
printf("Collection Statistics:\n");
|
||||
printf(" Document count: %llu\n",
|
||||
(unsigned long long)zvec_collection_stats_get_doc_count(stats));
|
||||
zvec_collection_stats_destroy(stats);
|
||||
}
|
||||
|
||||
// 9. Cleanup
|
||||
cleanup_collection:
|
||||
zvec_collection_destroy(collection);
|
||||
|
||||
cleanup_fields:
|
||||
// Field schemas are managed by the collection schema, no need to destroy
|
||||
// individually
|
||||
|
||||
cleanup_params:
|
||||
zvec_collection_schema_destroy(schema);
|
||||
|
||||
printf("✓ Optimized example completed\n");
|
||||
|
||||
return 0;
|
||||
}
|
||||
+1
-3
@@ -9,6 +9,4 @@ cc_directory(ailego)
|
||||
cc_directory(turbo)
|
||||
cc_directory(core)
|
||||
cc_directory(db)
|
||||
if(BUILD_PYTHON_BINDINGS)
|
||||
cc_directory(binding)
|
||||
endif()
|
||||
cc_directory(binding)
|
||||
|
||||
@@ -4,5 +4,11 @@ include(${PROJECT_ROOT_DIR}/cmake/option.cmake)
|
||||
# Retrieve version from git repository
|
||||
git_version(ZVEC_VERSION ${CMAKE_CURRENT_SOURCE_DIR})
|
||||
|
||||
# Add repository
|
||||
cc_directory(python)
|
||||
# Add repositories
|
||||
if(BUILD_C_BINDINGS)
|
||||
cc_directory(c)
|
||||
endif()
|
||||
|
||||
if(BUILD_PYTHON_BINDINGS)
|
||||
cc_directory(python)
|
||||
endif()
|
||||
@@ -0,0 +1,245 @@
|
||||
# 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(${PROJECT_ROOT_DIR}/cmake/bazel.cmake)
|
||||
include(${PROJECT_ROOT_DIR}/cmake/option.cmake)
|
||||
include(GNUInstallDirs)
|
||||
|
||||
# Retrieve version from git repository and generate version header
|
||||
git_version(ZVEC_VERSION ${CMAKE_CURRENT_SOURCE_DIR})
|
||||
|
||||
# Debug: print version variables
|
||||
message(STATUS "ZVEC_VERSION: ${ZVEC_VERSION}")
|
||||
|
||||
# Parse version string to extract major.minor.patch
|
||||
# Format: vX.Y.Z-commit-hash or vX.Y.Z
|
||||
if(ZVEC_VERSION MATCHES "^v([0-9]+)\\.([0-9]+)\\.([0-9]+)")
|
||||
set(ZVEC_VERSION_MAJOR "${CMAKE_MATCH_1}")
|
||||
set(ZVEC_VERSION_MINOR "${CMAKE_MATCH_2}")
|
||||
set(ZVEC_VERSION_PATCH "${CMAKE_MATCH_3}")
|
||||
set(ZVEC_VERSION_STRING "${ZVEC_VERSION}")
|
||||
else()
|
||||
# Default version if parsing fails
|
||||
set(ZVEC_VERSION_MAJOR 0)
|
||||
set(ZVEC_VERSION_MINOR 2)
|
||||
set(ZVEC_VERSION_PATCH 1)
|
||||
set(ZVEC_VERSION_STRING "${ZVEC_VERSION_MAJOR}.${ZVEC_VERSION_MINOR}.${ZVEC_VERSION_PATCH}")
|
||||
endif()
|
||||
|
||||
message(STATUS "Parsed version: ${ZVEC_VERSION_MAJOR}.${ZVEC_VERSION_MINOR}.${ZVEC_VERSION_PATCH} (${ZVEC_VERSION_STRING})")
|
||||
|
||||
# Configure version header file
|
||||
configure_file(
|
||||
${PROJECT_SOURCE_DIR}/src/include/zvec/version.h.in
|
||||
${PROJECT_BINARY_DIR}/src/generated/zvec_version.h
|
||||
)
|
||||
|
||||
# Configure c_api.h with version information embedded
|
||||
configure_file(
|
||||
${PROJECT_SOURCE_DIR}/src/include/zvec/c_api.h
|
||||
${PROJECT_BINARY_DIR}/src/generated/zvec/c_api.h
|
||||
@ONLY
|
||||
)
|
||||
|
||||
set(CMAKE_CXX_STANDARD 17)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
set(CMAKE_CXX_EXTENSIONS OFF)
|
||||
|
||||
# C API library source files
|
||||
set(ZVEC_C_API_SOURCES
|
||||
c_api.cc
|
||||
)
|
||||
|
||||
# C API library header files
|
||||
set(ZVEC_C_API_HEADERS
|
||||
${PROJECT_SOURCE_DIR}/src/include/zvec/c_api.h
|
||||
)
|
||||
|
||||
# =============================================================================
|
||||
# Build FAT Shared Library (zvec_c_api.so)
|
||||
# =============================================================================
|
||||
add_library(zvec_c_api SHARED
|
||||
${ZVEC_C_API_SOURCES}
|
||||
${ZVEC_C_API_HEADERS}
|
||||
)
|
||||
|
||||
# Set library properties
|
||||
set_target_properties(zvec_c_api PROPERTIES
|
||||
OUTPUT_NAME "zvec_c_api"
|
||||
POSITION_INDEPENDENT_CODE ON
|
||||
# Hide all symbols by default, only export C API
|
||||
CXX_VISIBILITY_PRESET hidden
|
||||
VISIBILITY_INLINES_HIDDEN ON
|
||||
)
|
||||
|
||||
find_package(Threads REQUIRED)
|
||||
|
||||
# Static linking of C++ standard library is handled in platform-specific sections
|
||||
|
||||
# Determine whole-archive flag for current platform
|
||||
if(MSVC)
|
||||
# MSVC uses /WHOLEARCHIVE:filename syntax
|
||||
set(ZVEC_WHOLE_ARCHIVE_PREFIX "/WHOLEARCHIVE:")
|
||||
set(ZVEC_NO_WHOLE_ARCHIVE_SUFFIX "")
|
||||
elseif(APPLE)
|
||||
# macOS uses -Wl,-force_load,filename
|
||||
set(ZVEC_WHOLE_ARCHIVE_PREFIX "-Wl,-force_load,")
|
||||
set(ZVEC_NO_WHOLE_ARCHIVE_SUFFIX "")
|
||||
else()
|
||||
# Linux/Unix uses -Wl,--whole-archive and -Wl,--no-whole-archive
|
||||
set(ZVEC_WHOLE_ARCHIVE_PREFIX "-Wl,--whole-archive")
|
||||
set(ZVEC_NO_WHOLE_ARCHIVE_SUFFIX "-Wl,--no-whole-archive")
|
||||
endif()
|
||||
|
||||
# FAT mode: embed ALL libraries (including third-party) statically
|
||||
# This creates a truly self-contained library with zero external dependencies
|
||||
# Users only need to link libzvec_c_api.so without installing any dependencies
|
||||
if(MSVC)
|
||||
# Windows MSVC: Use /WHOLEARCHIVE flag for static libraries only
|
||||
# Note: roaring might be a DLL on Windows, so we don't apply WHOLEARCHIVE to it
|
||||
target_link_options(zvec_c_api PRIVATE
|
||||
${ZVEC_WHOLE_ARCHIVE_PREFIX}$<TARGET_FILE:zvec_db>
|
||||
${ZVEC_WHOLE_ARCHIVE_PREFIX}$<TARGET_FILE:zvec_core>
|
||||
${ZVEC_WHOLE_ARCHIVE_PREFIX}$<TARGET_FILE:zvec_ailego>
|
||||
${ZVEC_WHOLE_ARCHIVE_PREFIX}$<TARGET_FILE:zvec_turbo>
|
||||
)
|
||||
|
||||
target_link_libraries(zvec_c_api
|
||||
PRIVATE
|
||||
zvec_db
|
||||
zvec_core
|
||||
zvec_ailego
|
||||
zvec_turbo
|
||||
roaring # May be DLL on Windows, link normally
|
||||
${ZVEC_CXX_STD_LIB}
|
||||
Threads::Threads
|
||||
)
|
||||
elseif(APPLE)
|
||||
# Third-party libraries that are dependencies of zvec_db and zvec_ailego
|
||||
# These must be linked before the internal libraries that depend on them
|
||||
target_link_libraries(zvec_c_api
|
||||
PRIVATE
|
||||
Arrow::arrow_static
|
||||
Arrow::parquet_static
|
||||
Arrow::arrow_compute
|
||||
Arrow::arrow_dataset
|
||||
Arrow::arrow_acero
|
||||
rocksdb
|
||||
glog
|
||||
libprotobuf
|
||||
antlr4
|
||||
)
|
||||
|
||||
# Link zvec internal libraries with -force_load to extract all objects
|
||||
# Use target names directly with -Wl,-force_load flag
|
||||
target_link_options(zvec_c_api PRIVATE
|
||||
-Wl,-force_load,$<TARGET_FILE:zvec_db>
|
||||
-Wl,-force_load,$<TARGET_FILE:zvec_core>
|
||||
-Wl,-force_load,$<TARGET_FILE:zvec_ailego>
|
||||
-Wl,-force_load,$<TARGET_FILE:zvec_turbo>
|
||||
-Wl,-force_load,$<TARGET_FILE:roaring>
|
||||
)
|
||||
|
||||
# Link the libraries themselves (without force_load flags)
|
||||
target_link_libraries(zvec_c_api
|
||||
PRIVATE
|
||||
zvec_db
|
||||
zvec_core
|
||||
zvec_ailego
|
||||
zvec_turbo
|
||||
roaring
|
||||
Threads::Threads
|
||||
${CMAKE_DL_LIBS}
|
||||
)
|
||||
|
||||
# Optional: Static link libc++ for better portability (uncomment if needed)
|
||||
# target_link_options(zvec_c_api PRIVATE -static-libstdc++)
|
||||
|
||||
else()
|
||||
# Linux and other Unix-like systems
|
||||
target_link_libraries(zvec_c_api
|
||||
PRIVATE
|
||||
# Force load all zvec internal libraries (extract all objects)
|
||||
${ZVEC_WHOLE_ARCHIVE_PREFIX}
|
||||
zvec_db
|
||||
zvec_core
|
||||
zvec_ailego
|
||||
zvec_turbo # Required by zvec_core (metric module)
|
||||
${ZVEC_NO_WHOLE_ARCHIVE_SUFFIX}
|
||||
# Most third-party libs are linked via zvec_db
|
||||
# Only roaring needs explicit whole-archive (C library)
|
||||
${ZVEC_WHOLE_ARCHIVE_PREFIX}
|
||||
roaring
|
||||
${ZVEC_NO_WHOLE_ARCHIVE_SUFFIX}
|
||||
Threads::Threads
|
||||
${CMAKE_DL_LIBS}
|
||||
)
|
||||
|
||||
# Static link libstdc++ to avoid runtime dependency
|
||||
# Must be done in target_link_options to ensure correct order
|
||||
target_link_options(zvec_c_api PRIVATE
|
||||
-static-libstdc++
|
||||
-static-libgcc
|
||||
)
|
||||
endif()
|
||||
|
||||
# Include directories
|
||||
target_include_directories(zvec_c_api
|
||||
PUBLIC
|
||||
$<BUILD_INTERFACE:${PROJECT_BINARY_DIR}/src/generated>
|
||||
$<BUILD_INTERFACE:${PROJECT_SOURCE_DIR}/src/include>
|
||||
$<INSTALL_INTERFACE:include>
|
||||
PRIVATE
|
||||
${PROJECT_SOURCE_DIR}/src
|
||||
)
|
||||
|
||||
# Compile options
|
||||
target_compile_options(zvec_c_api PRIVATE
|
||||
$<$<CXX_COMPILER_ID:GNU>:-Wall -Wextra -Wpedantic>
|
||||
$<$<CXX_COMPILER_ID:Clang>:-Wall -Wextra -Wpedantic>
|
||||
)
|
||||
|
||||
# Strip symbols in release builds to reduce library size
|
||||
if(NOT CMAKE_BUILD_TYPE STREQUAL "Debug")
|
||||
if(UNIX AND NOT APPLE)
|
||||
# Linux: Use strip command to remove symbols
|
||||
add_custom_command(TARGET zvec_c_api POST_BUILD
|
||||
COMMAND ${CMAKE_STRIP} $<TARGET_FILE:zvec_c_api>
|
||||
COMMENT "Stripping symbols from libzvec_c_api.so to reduce size"
|
||||
)
|
||||
elseif(APPLE)
|
||||
# macOS: Use strip with platform-specific flags
|
||||
add_custom_command(TARGET zvec_c_api POST_BUILD
|
||||
COMMAND /usr/bin/strip -x $<TARGET_FILE:zvec_c_api>
|
||||
COMMENT "Stripping symbols from libzvec_c_api.dylib to reduce size"
|
||||
)
|
||||
endif()
|
||||
endif()
|
||||
|
||||
# =============================================================================
|
||||
# Installation Rules
|
||||
# =============================================================================
|
||||
|
||||
# Install shared library
|
||||
install(TARGETS zvec_c_api
|
||||
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
|
||||
ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
|
||||
RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
|
||||
INCLUDES DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}
|
||||
)
|
||||
|
||||
# Install headers
|
||||
install(FILES ${PROJECT_SOURCE_DIR}/src/include/zvec/c_api.h
|
||||
DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/zvec
|
||||
)
|
||||
File diff suppressed because it is too large
Load Diff
@@ -80,4 +80,4 @@ elseif (MSVC)
|
||||
endforeach()
|
||||
endif ()
|
||||
|
||||
target_include_directories(_zvec PRIVATE ${PYBIND11_INCLUDE_DIR} ${PROJECT_ROOT_DIR}/src ${PROJECT_ROOT_DIR}/src/binding/python/include)
|
||||
target_include_directories(_zvec PRIVATE ${PYBIND11_INCLUDE_DIR} ${PROJECT_ROOT_DIR}/src ${PROJECT_ROOT_DIR}/src/binding/python/include)
|
||||
@@ -14,11 +14,11 @@ cc_directory(sqlengine)
|
||||
file(GLOB_RECURSE ALL_DB_SRCS *.cc *.c *.h)
|
||||
|
||||
cc_library(
|
||||
NAME zvec_db STATIC STRICT SRCS_NO_GLOB
|
||||
NAME zvec_db STATIC STRICT SRCS_NO_GLOB PACKED
|
||||
SRCS ${ALL_DB_SRCS} ${CMAKE_CURRENT_BINARY_DIR}/proto/zvec.pb.cc
|
||||
INCS . ${CMAKE_CURRENT_BINARY_DIR}
|
||||
PUBINCS ${PROJECT_ROOT_DIR}/src/include
|
||||
LIBS
|
||||
LIBS
|
||||
zvec_ailego
|
||||
zvec_core
|
||||
glog
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -68,6 +68,10 @@ class Doc {
|
||||
return pk_;
|
||||
}
|
||||
|
||||
const std::string &pk_ref() const {
|
||||
return pk_;
|
||||
}
|
||||
|
||||
void set_score(float score) {
|
||||
score_ = score;
|
||||
}
|
||||
@@ -232,6 +236,26 @@ class Doc {
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
// Get field value as const reference, throws exception if field doesn't exist
|
||||
// or type mismatches
|
||||
template <typename T>
|
||||
const T &get_ref(const std::string &field_name) const {
|
||||
auto it = fields_.find(field_name);
|
||||
if (it == fields_.end()) {
|
||||
throw std::runtime_error("Field '" + field_name + "' not found");
|
||||
}
|
||||
|
||||
if (std::holds_alternative<std::monostate>(it->second)) {
|
||||
throw std::runtime_error("Field '" + field_name + "' is null");
|
||||
}
|
||||
|
||||
try {
|
||||
return std::get<T>(it->second);
|
||||
} catch (const std::bad_variant_access &) {
|
||||
throw std::runtime_error("Field '" + field_name + "' type mismatch");
|
||||
}
|
||||
}
|
||||
|
||||
void remove(const std::string &field_name) {
|
||||
fields_.erase(field_name);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
#ifndef ZVEC_VERSION_H
|
||||
#define ZVEC_VERSION_H
|
||||
|
||||
/** @brief Major version number */
|
||||
#define ZVEC_VERSION_MAJOR @ZVEC_VERSION_MAJOR@
|
||||
|
||||
/** @brief Minor version number */
|
||||
#define ZVEC_VERSION_MINOR @ZVEC_VERSION_MINOR@
|
||||
|
||||
/** @brief Patch version number */
|
||||
#define ZVEC_VERSION_PATCH @ZVEC_VERSION_PATCH@
|
||||
|
||||
/** @brief Full version string */
|
||||
#define ZVEC_VERSION_STRING "@ZVEC_VERSION_STRING@"
|
||||
|
||||
#endif // ZVEC_VERSION_H
|
||||
@@ -4,3 +4,6 @@ include(${PROJECT_ROOT_DIR}/cmake/option.cmake)
|
||||
cc_directories(ailego)
|
||||
cc_directories(db)
|
||||
cc_directories(core)
|
||||
if(BUILD_C_BINDINGS)
|
||||
cc_directories(c)
|
||||
endif()
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
# 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(${PROJECT_ROOT_DIR}/cmake/bazel.cmake)
|
||||
|
||||
file(GLOB_RECURSE ALL_TEST_SRCS *_test.c)
|
||||
|
||||
foreach(CC_SRCS ${ALL_TEST_SRCS})
|
||||
get_filename_component(CC_TARGET ${CC_SRCS} NAME_WE)
|
||||
cc_gtest(
|
||||
NAME ${CC_TARGET}
|
||||
STRICT
|
||||
LIBS zvec_c_api
|
||||
SRCS ${CC_SRCS} utils.c
|
||||
INCS . .. ../../src
|
||||
)
|
||||
endforeach()
|
||||
File diff suppressed because it is too large
Load Diff
+967
@@ -0,0 +1,967 @@
|
||||
// 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 "utils.h"
|
||||
#include <assert.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
// =============================================================================
|
||||
// Internal Helper Functions
|
||||
// =============================================================================
|
||||
|
||||
static char *strdup_safe(const char *str) {
|
||||
if (!str) return NULL;
|
||||
size_t len = strlen(str) + 1;
|
||||
char *copy = (char *)malloc(len);
|
||||
if (copy) {
|
||||
memcpy(copy, str, len);
|
||||
}
|
||||
return copy;
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Schema Creation Helper Functions Implementation
|
||||
// =============================================================================
|
||||
|
||||
ZVecCollectionSchema *zvec_test_create_temp_schema(void) {
|
||||
// Create collection schema using C API
|
||||
ZVecCollectionSchema *schema = zvec_collection_schema_create("demo");
|
||||
zvec_collection_schema_set_max_doc_count_per_segment(schema, 1000);
|
||||
|
||||
// Create index parameters using new opaque pointer API
|
||||
ZVecIndexParams *invert_params =
|
||||
zvec_index_params_create(ZVEC_INDEX_TYPE_INVERT);
|
||||
zvec_index_params_set_invert_params(invert_params, true, true);
|
||||
|
||||
ZVecIndexParams *dense_hnsw_params =
|
||||
zvec_index_params_create(ZVEC_INDEX_TYPE_HNSW);
|
||||
zvec_index_params_set_metric_type(dense_hnsw_params, ZVEC_METRIC_TYPE_L2);
|
||||
zvec_index_params_set_hnsw_params(dense_hnsw_params, 16, 100);
|
||||
|
||||
ZVecIndexParams *sparse_hnsw_params =
|
||||
zvec_index_params_create(ZVEC_INDEX_TYPE_HNSW);
|
||||
zvec_index_params_set_metric_type(sparse_hnsw_params, ZVEC_METRIC_TYPE_IP);
|
||||
zvec_index_params_set_hnsw_params(sparse_hnsw_params, 16, 100);
|
||||
|
||||
ZVecIndexParams *name_invert_params =
|
||||
zvec_index_params_create(ZVEC_INDEX_TYPE_INVERT);
|
||||
zvec_index_params_set_invert_params(name_invert_params, false, false);
|
||||
|
||||
// Create and add fields
|
||||
ZVecFieldSchema *id_field =
|
||||
zvec_field_schema_create("id", ZVEC_DATA_TYPE_INT64, false, 0);
|
||||
zvec_field_schema_set_index_params(id_field, invert_params);
|
||||
zvec_collection_schema_add_field(schema, id_field);
|
||||
|
||||
// Create name field (inverted index without optimization)
|
||||
ZVecFieldSchema *name_field =
|
||||
zvec_field_schema_create("name", ZVEC_DATA_TYPE_STRING, false, 0);
|
||||
zvec_field_schema_set_index_params(name_field, name_invert_params);
|
||||
zvec_collection_schema_add_field(schema, name_field);
|
||||
|
||||
// Create weight field (no index)
|
||||
ZVecFieldSchema *weight_field =
|
||||
zvec_field_schema_create("weight", ZVEC_DATA_TYPE_FLOAT, true, 0);
|
||||
zvec_collection_schema_add_field(schema, weight_field);
|
||||
|
||||
// Create dense field (HNSW index)
|
||||
ZVecFieldSchema *dense_field =
|
||||
zvec_field_schema_create("dense", ZVEC_DATA_TYPE_VECTOR_FP32, false, 128);
|
||||
zvec_field_schema_set_index_params(dense_field, dense_hnsw_params);
|
||||
zvec_collection_schema_add_field(schema, dense_field);
|
||||
|
||||
// Create sparse field (HNSW index)
|
||||
ZVecFieldSchema *sparse_field = zvec_field_schema_create(
|
||||
"sparse", ZVEC_DATA_TYPE_SPARSE_VECTOR_FP32, false, 0);
|
||||
zvec_field_schema_set_index_params(sparse_field, sparse_hnsw_params);
|
||||
zvec_collection_schema_add_field(schema, sparse_field);
|
||||
|
||||
// Cleanup index parameters
|
||||
zvec_index_params_destroy(invert_params);
|
||||
zvec_index_params_destroy(dense_hnsw_params);
|
||||
zvec_index_params_destroy(sparse_hnsw_params);
|
||||
zvec_index_params_destroy(name_invert_params);
|
||||
|
||||
return schema;
|
||||
}
|
||||
|
||||
ZVecCollectionSchema *zvec_test_create_scalar_schema(void) {
|
||||
// Create collection schema using C API
|
||||
ZVecCollectionSchema *schema = zvec_collection_schema_create("demo");
|
||||
|
||||
// Create fields
|
||||
ZVecFieldSchema *int32_field =
|
||||
zvec_field_schema_create("int32", ZVEC_DATA_TYPE_INT32, false, 0);
|
||||
zvec_collection_schema_add_field(schema, int32_field);
|
||||
|
||||
ZVecFieldSchema *string_field =
|
||||
zvec_field_schema_create("string", ZVEC_DATA_TYPE_STRING, false, 0);
|
||||
zvec_collection_schema_add_field(schema, string_field);
|
||||
|
||||
return schema;
|
||||
}
|
||||
|
||||
ZVecCollectionSchema *zvec_test_create_normal_schema(
|
||||
bool nullable, const char *name, const ZVecIndexParams *scalar_index_params,
|
||||
const ZVecIndexParams *vector_index_params, uint64_t max_doc_count) {
|
||||
// Create collection schema using C API
|
||||
ZVecCollectionSchema *schema =
|
||||
zvec_collection_schema_create(name ? name : "demo");
|
||||
zvec_collection_schema_set_max_doc_count_per_segment(schema, max_doc_count);
|
||||
|
||||
// Create scalar fields (8)
|
||||
const char *scalar_names[] = {"int32", "string", "uint32", "bool",
|
||||
"float", "double", "int64", "uint64"};
|
||||
ZVecDataType scalar_types[] = {ZVEC_DATA_TYPE_INT32, ZVEC_DATA_TYPE_STRING,
|
||||
ZVEC_DATA_TYPE_UINT32, ZVEC_DATA_TYPE_BOOL,
|
||||
ZVEC_DATA_TYPE_FLOAT, ZVEC_DATA_TYPE_DOUBLE,
|
||||
ZVEC_DATA_TYPE_INT64, ZVEC_DATA_TYPE_UINT64};
|
||||
|
||||
for (int i = 0; i < 8; i++) {
|
||||
ZVecFieldSchema *field =
|
||||
zvec_field_schema_create(scalar_names[i], scalar_types[i], nullable, 0);
|
||||
if (scalar_index_params) {
|
||||
zvec_field_schema_set_index_params(field, scalar_index_params);
|
||||
}
|
||||
zvec_collection_schema_add_field(schema, field);
|
||||
}
|
||||
|
||||
// Create array fields (8)
|
||||
const char *array_names[] = {"array_int32", "array_string", "array_uint32",
|
||||
"array_bool", "array_float", "array_double",
|
||||
"array_int64", "array_uint64"};
|
||||
ZVecDataType array_types[] = {
|
||||
ZVEC_DATA_TYPE_ARRAY_INT32, ZVEC_DATA_TYPE_ARRAY_STRING,
|
||||
ZVEC_DATA_TYPE_ARRAY_UINT32, ZVEC_DATA_TYPE_ARRAY_BOOL,
|
||||
ZVEC_DATA_TYPE_ARRAY_FLOAT, ZVEC_DATA_TYPE_ARRAY_DOUBLE,
|
||||
ZVEC_DATA_TYPE_ARRAY_INT64, ZVEC_DATA_TYPE_ARRAY_UINT64};
|
||||
|
||||
for (int i = 0; i < 8; i++) {
|
||||
ZVecFieldSchema *field =
|
||||
zvec_field_schema_create(array_names[i], array_types[i], nullable, 0);
|
||||
if (scalar_index_params) {
|
||||
zvec_field_schema_set_index_params(field, scalar_index_params);
|
||||
}
|
||||
zvec_collection_schema_add_field(schema, field);
|
||||
}
|
||||
|
||||
// Create vector fields (5)
|
||||
// dense vectors
|
||||
ZVecFieldSchema *dense_fp32 = zvec_field_schema_create(
|
||||
"dense_fp32", ZVEC_DATA_TYPE_VECTOR_FP32, false, 128);
|
||||
if (vector_index_params) {
|
||||
zvec_field_schema_set_index_params(dense_fp32, vector_index_params);
|
||||
}
|
||||
zvec_collection_schema_add_field(schema, dense_fp32);
|
||||
|
||||
ZVecFieldSchema *dense_fp16 = zvec_field_schema_create(
|
||||
"dense_fp16", ZVEC_DATA_TYPE_VECTOR_FP16, false, 128);
|
||||
ZVecIndexParams *flat_params1 = zvec_test_create_default_flat_params();
|
||||
zvec_field_schema_set_index_params(dense_fp16, flat_params1);
|
||||
zvec_index_params_destroy(flat_params1);
|
||||
zvec_collection_schema_add_field(schema, dense_fp16);
|
||||
|
||||
ZVecFieldSchema *dense_int8 = zvec_field_schema_create(
|
||||
"dense_int8", ZVEC_DATA_TYPE_VECTOR_INT8, false, 128);
|
||||
ZVecIndexParams *flat_params2 = zvec_test_create_default_flat_params();
|
||||
zvec_field_schema_set_index_params(dense_int8, flat_params2);
|
||||
zvec_index_params_destroy(flat_params2);
|
||||
zvec_collection_schema_add_field(schema, dense_int8);
|
||||
|
||||
// sparse vectors
|
||||
ZVecFieldSchema *sparse_fp32 = zvec_field_schema_create(
|
||||
"sparse_fp32", ZVEC_DATA_TYPE_SPARSE_VECTOR_FP32, false, 0);
|
||||
if (vector_index_params) {
|
||||
zvec_field_schema_set_index_params(sparse_fp32, vector_index_params);
|
||||
}
|
||||
zvec_collection_schema_add_field(schema, sparse_fp32);
|
||||
|
||||
ZVecFieldSchema *sparse_fp16 = zvec_field_schema_create(
|
||||
"sparse_fp16", ZVEC_DATA_TYPE_SPARSE_VECTOR_FP16, false, 0);
|
||||
ZVecIndexParams *flat_params3 = zvec_test_create_default_flat_params();
|
||||
zvec_field_schema_set_index_params(sparse_fp16, flat_params3);
|
||||
zvec_index_params_destroy(flat_params3);
|
||||
zvec_collection_schema_add_field(schema, sparse_fp16);
|
||||
|
||||
return schema;
|
||||
}
|
||||
|
||||
ZVecCollectionSchema *zvec_test_create_schema_with_scalar_index(
|
||||
bool nullable, bool enable_optimize, const char *name) {
|
||||
ZVecIndexParams *invert_params =
|
||||
zvec_test_create_default_invert_params(enable_optimize);
|
||||
ZVecCollectionSchema *schema =
|
||||
zvec_test_create_normal_schema(nullable, name, invert_params, NULL, 1000);
|
||||
free(invert_params);
|
||||
return schema;
|
||||
}
|
||||
|
||||
ZVecCollectionSchema *zvec_test_create_schema_with_vector_index(
|
||||
bool nullable, const char *name,
|
||||
const ZVecIndexParams *vector_index_params) {
|
||||
ZVecIndexParams *default_params = NULL;
|
||||
if (!vector_index_params) {
|
||||
default_params = zvec_test_create_default_hnsw_params();
|
||||
}
|
||||
|
||||
ZVecCollectionSchema *schema = zvec_test_create_normal_schema(
|
||||
nullable, name, NULL,
|
||||
vector_index_params ? vector_index_params : default_params, 1000);
|
||||
|
||||
if (default_params) {
|
||||
free(default_params);
|
||||
}
|
||||
|
||||
return schema;
|
||||
}
|
||||
|
||||
ZVecCollectionSchema *zvec_test_create_schema_with_max_doc_count(
|
||||
uint64_t doc_count) {
|
||||
return zvec_test_create_normal_schema(false, "demo", NULL, NULL, doc_count);
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Document Creation Helper Functions Implementation
|
||||
// =============================================================================
|
||||
|
||||
char *zvec_test_make_pk(uint64_t doc_id) {
|
||||
char *pk = (char *)malloc(32); // Sufficiently large buffer
|
||||
if (pk) {
|
||||
snprintf(pk, 32, "pk_%llu", (unsigned long long)doc_id);
|
||||
}
|
||||
return pk;
|
||||
}
|
||||
|
||||
uint64_t zvec_test_extract_doc_id(const char *pk) {
|
||||
if (!pk || strlen(pk) < 4) return 0;
|
||||
return strtoull(pk + 3, NULL, 10);
|
||||
}
|
||||
|
||||
ZVecDoc *zvec_test_create_doc(uint64_t doc_id,
|
||||
const ZVecCollectionSchema *schema,
|
||||
const char *pk) {
|
||||
if (!schema) return NULL;
|
||||
ZVecDoc *doc = zvec_doc_create();
|
||||
if (!doc) return NULL;
|
||||
|
||||
// Set primary key
|
||||
char *primary_key = pk ? strdup_safe(pk) : zvec_test_make_pk(doc_id);
|
||||
if (primary_key) {
|
||||
zvec_doc_set_pk(doc, primary_key);
|
||||
free(primary_key);
|
||||
}
|
||||
|
||||
// Create test data for each field
|
||||
const char **field_names = NULL;
|
||||
size_t field_count = 0;
|
||||
ZVecErrorCode ret = zvec_collection_schema_get_all_field_names(
|
||||
schema, &field_names, &field_count);
|
||||
if (ret != ZVEC_OK || !field_names) {
|
||||
zvec_doc_destroy(doc);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
for (size_t i = 0; i < field_count; i++) {
|
||||
const char *field_name = field_names[i];
|
||||
const ZVecFieldSchema *field =
|
||||
zvec_collection_schema_get_field(schema, field_name);
|
||||
if (!field) continue;
|
||||
ZVecDataType field_type = zvec_field_schema_get_data_type(field);
|
||||
uint32_t field_dimension = zvec_field_schema_get_dimension(field);
|
||||
|
||||
switch (field_type) {
|
||||
case ZVEC_DATA_TYPE_BINARY: {
|
||||
char binary_str[32];
|
||||
snprintf(binary_str, sizeof(binary_str), "binary_%llu",
|
||||
(unsigned long long)doc_id);
|
||||
zvec_doc_add_field_by_value(doc, field_name, field_type, binary_str,
|
||||
strlen(binary_str));
|
||||
break;
|
||||
}
|
||||
case ZVEC_DATA_TYPE_BOOL: {
|
||||
zvec_doc_add_field_by_value(doc, field_name, field_type,
|
||||
&(bool){doc_id % 10 == 0}, sizeof(bool));
|
||||
break;
|
||||
}
|
||||
case ZVEC_DATA_TYPE_INT32: {
|
||||
zvec_doc_add_field_by_value(doc, field_name, field_type,
|
||||
&(int32_t){(int32_t)doc_id},
|
||||
sizeof(int32_t));
|
||||
break;
|
||||
}
|
||||
case ZVEC_DATA_TYPE_INT64: {
|
||||
zvec_doc_add_field_by_value(doc, field_name, field_type,
|
||||
&(int64_t){(int64_t)doc_id},
|
||||
sizeof(int64_t));
|
||||
break;
|
||||
}
|
||||
case ZVEC_DATA_TYPE_UINT32: {
|
||||
zvec_doc_add_field_by_value(doc, field_name, field_type,
|
||||
&(uint32_t){(uint32_t)doc_id},
|
||||
sizeof(uint32_t));
|
||||
break;
|
||||
}
|
||||
case ZVEC_DATA_TYPE_UINT64: {
|
||||
zvec_doc_add_field_by_value(doc, field_name, field_type,
|
||||
&(uint64_t){(uint64_t)doc_id},
|
||||
sizeof(uint64_t));
|
||||
break;
|
||||
}
|
||||
case ZVEC_DATA_TYPE_FLOAT: {
|
||||
zvec_doc_add_field_by_value(doc, field_name, field_type,
|
||||
&(float){(float)doc_id}, sizeof(float));
|
||||
break;
|
||||
}
|
||||
case ZVEC_DATA_TYPE_DOUBLE: {
|
||||
zvec_doc_add_field_by_value(doc, field_name, field_type,
|
||||
&(double){(double)doc_id}, sizeof(double));
|
||||
break;
|
||||
}
|
||||
case ZVEC_DATA_TYPE_STRING: {
|
||||
char string_val[64];
|
||||
snprintf(string_val, sizeof(string_val), "value_%llu",
|
||||
(unsigned long long)doc_id);
|
||||
zvec_doc_add_field_by_value(doc, field_name, field_type, string_val,
|
||||
strlen(string_val));
|
||||
break;
|
||||
}
|
||||
case ZVEC_DATA_TYPE_ARRAY_BOOL: {
|
||||
bool bool_array[10];
|
||||
for (int j = 0; j < 10; j++) {
|
||||
bool_array[j] = (doc_id + j) % 2 == 0;
|
||||
}
|
||||
zvec_doc_add_field_by_value(doc, field_name, field_type, bool_array,
|
||||
sizeof(bool_array));
|
||||
break;
|
||||
}
|
||||
case ZVEC_DATA_TYPE_ARRAY_INT32: {
|
||||
int32_t int32_array[10];
|
||||
for (int j = 0; j < 10; j++) {
|
||||
int32_array[j] = (int32_t)doc_id;
|
||||
}
|
||||
zvec_doc_add_field_by_value(doc, field_name, field_type, int32_array,
|
||||
sizeof(int32_array));
|
||||
break;
|
||||
}
|
||||
case ZVEC_DATA_TYPE_ARRAY_INT64: {
|
||||
int64_t int64_array[10];
|
||||
for (int j = 0; j < 10; j++) {
|
||||
int64_array[j] = (int64_t)doc_id;
|
||||
}
|
||||
zvec_doc_add_field_by_value(doc, field_name, field_type, int64_array,
|
||||
sizeof(int64_array));
|
||||
break;
|
||||
}
|
||||
case ZVEC_DATA_TYPE_ARRAY_UINT32: {
|
||||
uint32_t uint32_array[10];
|
||||
for (int j = 0; j < 10; j++) {
|
||||
uint32_array[j] = (uint32_t)doc_id;
|
||||
}
|
||||
zvec_doc_add_field_by_value(doc, field_name, field_type, uint32_array,
|
||||
sizeof(uint32_array));
|
||||
break;
|
||||
}
|
||||
case ZVEC_DATA_TYPE_ARRAY_UINT64: {
|
||||
uint64_t uint64_array[10];
|
||||
for (int j = 0; j < 10; j++) {
|
||||
uint64_array[j] = (uint64_t)doc_id;
|
||||
}
|
||||
zvec_doc_add_field_by_value(doc, field_name, field_type, uint64_array,
|
||||
sizeof(uint64_array));
|
||||
break;
|
||||
}
|
||||
case ZVEC_DATA_TYPE_ARRAY_FLOAT: {
|
||||
float float_array[10];
|
||||
for (int j = 0; j < 10; j++) {
|
||||
float_array[j] = (float)doc_id;
|
||||
}
|
||||
zvec_doc_add_field_by_value(doc, field_name, field_type, float_array,
|
||||
sizeof(float_array));
|
||||
break;
|
||||
}
|
||||
case ZVEC_DATA_TYPE_ARRAY_DOUBLE: {
|
||||
double double_array[10];
|
||||
for (int j = 0; j < 10; j++) {
|
||||
double_array[j] = (double)doc_id;
|
||||
}
|
||||
zvec_doc_add_field_by_value(doc, field_name, field_type, double_array,
|
||||
sizeof(double_array));
|
||||
break;
|
||||
}
|
||||
case ZVEC_DATA_TYPE_ARRAY_STRING: {
|
||||
// String arrays need special handling
|
||||
char string_data[256];
|
||||
size_t offset = 0;
|
||||
for (int j = 0; j < 10; j++) {
|
||||
char temp_str[32];
|
||||
snprintf(temp_str, sizeof(temp_str), "value_%llu_%d",
|
||||
(unsigned long long)doc_id, j);
|
||||
size_t len = strlen(temp_str);
|
||||
if (offset + len + 1 < sizeof(string_data)) {
|
||||
strcpy(string_data + offset, temp_str);
|
||||
offset += len + 1;
|
||||
}
|
||||
}
|
||||
zvec_doc_add_field_by_value(doc, field_name, field_type, string_data,
|
||||
offset);
|
||||
break;
|
||||
}
|
||||
case ZVEC_DATA_TYPE_VECTOR_BINARY32: {
|
||||
uint32_t *vector_data =
|
||||
(uint32_t *)malloc(field_dimension * sizeof(uint32_t));
|
||||
if (vector_data) {
|
||||
for (uint32_t j = 0; j < field_dimension; j++) {
|
||||
vector_data[j] = (uint32_t)(doc_id + j);
|
||||
}
|
||||
zvec_doc_add_field_by_value(doc, field_name, field_type, vector_data,
|
||||
field_dimension * sizeof(uint32_t));
|
||||
free(vector_data);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case ZVEC_DATA_TYPE_VECTOR_BINARY64: {
|
||||
uint64_t *vector_data =
|
||||
(uint64_t *)malloc(field_dimension * sizeof(uint64_t));
|
||||
if (vector_data) {
|
||||
for (uint32_t j = 0; j < field_dimension; j++) {
|
||||
vector_data[j] = (uint64_t)(doc_id + j);
|
||||
}
|
||||
zvec_doc_add_field_by_value(doc, field_name, field_type, vector_data,
|
||||
field_dimension * sizeof(uint64_t));
|
||||
free(vector_data);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case ZVEC_DATA_TYPE_VECTOR_FP32: {
|
||||
float *vector_data = (float *)malloc(field_dimension * sizeof(float));
|
||||
if (vector_data) {
|
||||
for (uint32_t j = 0; j < field_dimension; j++) {
|
||||
vector_data[j] = (float)(doc_id + j * 0.1);
|
||||
}
|
||||
zvec_doc_add_field_by_value(doc, field_name, field_type, vector_data,
|
||||
field_dimension * sizeof(float));
|
||||
free(vector_data);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case ZVEC_DATA_TYPE_VECTOR_FP64: {
|
||||
double *vector_data =
|
||||
(double *)malloc(field_dimension * sizeof(double));
|
||||
if (vector_data) {
|
||||
for (uint32_t j = 0; j < field_dimension; j++) {
|
||||
vector_data[j] = (double)(doc_id + j * 0.1);
|
||||
}
|
||||
zvec_doc_add_field_by_value(doc, field_name, field_type, vector_data,
|
||||
field_dimension * sizeof(double));
|
||||
free(vector_data);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case ZVEC_DATA_TYPE_VECTOR_FP16: {
|
||||
// FP16 needs special handling, simplified to FP32 here
|
||||
float *vector_data = (float *)malloc(field_dimension * sizeof(float));
|
||||
if (vector_data) {
|
||||
for (uint32_t j = 0; j < field_dimension; j++) {
|
||||
vector_data[j] = (float)(doc_id + j * 0.1);
|
||||
}
|
||||
zvec_doc_add_field_by_value(doc, field_name, field_type, vector_data,
|
||||
field_dimension * sizeof(float));
|
||||
free(vector_data);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case ZVEC_DATA_TYPE_VECTOR_INT8: {
|
||||
int8_t *vector_data =
|
||||
(int8_t *)malloc(field_dimension * sizeof(int8_t));
|
||||
if (vector_data) {
|
||||
for (uint32_t j = 0; j < field_dimension; j++) {
|
||||
vector_data[j] = (int8_t)((doc_id + j) % 256);
|
||||
}
|
||||
zvec_doc_add_field_by_value(doc, field_name, field_type, vector_data,
|
||||
field_dimension * sizeof(int8_t));
|
||||
free(vector_data);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case ZVEC_DATA_TYPE_VECTOR_INT16: {
|
||||
int16_t *vector_data =
|
||||
(int16_t *)malloc(field_dimension * sizeof(int16_t));
|
||||
if (vector_data) {
|
||||
for (uint32_t j = 0; j < field_dimension; j++) {
|
||||
vector_data[j] = (int16_t)((doc_id + j) % 65536);
|
||||
}
|
||||
zvec_doc_add_field_by_value(doc, field_name, field_type, vector_data,
|
||||
field_dimension * sizeof(int16_t));
|
||||
free(vector_data);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case ZVEC_DATA_TYPE_SPARSE_VECTOR_FP32: {
|
||||
// Sparse vectors need special handling
|
||||
uint32_t nnz = field_dimension > 0 ? field_dimension / 10
|
||||
: 10; // Number of non-zero elements
|
||||
size_t sparse_size =
|
||||
sizeof(uint32_t) + nnz * (sizeof(uint32_t) + sizeof(float));
|
||||
void *sparse_data = malloc(sparse_size);
|
||||
if (sparse_data) {
|
||||
uint32_t *data_ptr = (uint32_t *)sparse_data;
|
||||
*data_ptr = nnz; // Set number of non-zero elements
|
||||
uint32_t *indices = data_ptr + 1;
|
||||
float *values = (float *)(indices + nnz);
|
||||
for (uint32_t j = 0; j < nnz; j++) {
|
||||
indices[j] = j * 10; // Index
|
||||
values[j] = (float)(doc_id + j * 0.1); // Value
|
||||
}
|
||||
zvec_doc_add_field_by_value(doc, field_name, field_type, sparse_data,
|
||||
sparse_size);
|
||||
free(sparse_data);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case ZVEC_DATA_TYPE_SPARSE_VECTOR_FP16: {
|
||||
// Sparse FP16 vectors, simplified handling
|
||||
uint32_t nnz = field_dimension > 0 ? field_dimension / 10 : 10;
|
||||
size_t sparse_size =
|
||||
sizeof(uint32_t) +
|
||||
nnz * (sizeof(uint32_t) +
|
||||
sizeof(float)); // Still use float for storage
|
||||
void *sparse_data = malloc(sparse_size);
|
||||
if (sparse_data) {
|
||||
uint32_t *data_ptr = (uint32_t *)sparse_data;
|
||||
*data_ptr = nnz;
|
||||
uint32_t *indices = data_ptr + 1;
|
||||
float *values = (float *)(indices + nnz);
|
||||
for (uint32_t j = 0; j < nnz; j++) {
|
||||
indices[j] = j * 10;
|
||||
values[j] = (float)(doc_id + j * 0.1);
|
||||
}
|
||||
zvec_doc_add_field_by_value(doc, field_name, field_type, sparse_data,
|
||||
sparse_size);
|
||||
free(sparse_data);
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
default:
|
||||
// Unsupported data type
|
||||
break;
|
||||
}
|
||||
|
||||
// Remove reference to removed variable err
|
||||
/*
|
||||
if (err != ZVEC_OK) {
|
||||
// Error handling: continue processing other fields
|
||||
}
|
||||
*/
|
||||
}
|
||||
|
||||
// Free field names array (individual strings are freed by the API)
|
||||
if (field_names) {
|
||||
for (size_t i = 0; i < field_count; i++) {
|
||||
free((char *)field_names[i]);
|
||||
}
|
||||
free(field_names);
|
||||
}
|
||||
|
||||
return doc;
|
||||
}
|
||||
|
||||
ZVecDoc *zvec_test_create_doc_null(uint64_t doc_id,
|
||||
const ZVecCollectionSchema *schema,
|
||||
const char *pk) {
|
||||
// Reuse create_doc function, but only process vector fields
|
||||
ZVecDoc *doc = zvec_doc_create();
|
||||
if (!doc) return NULL;
|
||||
|
||||
// Set primary key
|
||||
char *primary_key = pk ? strdup_safe(pk) : zvec_test_make_pk(doc_id);
|
||||
if (primary_key) {
|
||||
zvec_doc_set_pk(doc, primary_key);
|
||||
free(primary_key);
|
||||
}
|
||||
|
||||
// Only create data for vector fields
|
||||
const char **field_names = NULL;
|
||||
size_t field_count = 0;
|
||||
ZVecErrorCode ret = zvec_collection_schema_get_all_field_names(
|
||||
schema, &field_names, &field_count);
|
||||
if (ret != ZVEC_OK || !field_names) {
|
||||
zvec_doc_destroy(doc);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
for (size_t i = 0; i < field_count; i++) {
|
||||
const char *field_name = field_names[i];
|
||||
const ZVecFieldSchema *field =
|
||||
zvec_collection_schema_get_field(schema, field_name);
|
||||
if (!field) continue;
|
||||
ZVecDataType field_type = zvec_field_schema_get_data_type(field);
|
||||
uint32_t field_dimension = zvec_field_schema_get_dimension(field);
|
||||
|
||||
// Only process specific vector type fields
|
||||
if (field_type != ZVEC_DATA_TYPE_VECTOR_FP32 &&
|
||||
field_type != ZVEC_DATA_TYPE_VECTOR_FP16 &&
|
||||
field_type != ZVEC_DATA_TYPE_VECTOR_INT8 &&
|
||||
field_type != ZVEC_DATA_TYPE_SPARSE_VECTOR_FP32 &&
|
||||
field_type != ZVEC_DATA_TYPE_SPARSE_VECTOR_FP16) {
|
||||
continue;
|
||||
}
|
||||
|
||||
ZVecErrorCode err = ZVEC_OK;
|
||||
|
||||
switch (field_type) {
|
||||
case ZVEC_DATA_TYPE_VECTOR_FP32: {
|
||||
float *vector_data = (float *)malloc(field_dimension * sizeof(float));
|
||||
if (vector_data) {
|
||||
for (uint32_t j = 0; j < field_dimension; j++) {
|
||||
vector_data[j] = (float)(doc_id + j * 0.1);
|
||||
}
|
||||
err = zvec_doc_add_field_by_value(doc, field_name, field_type,
|
||||
vector_data,
|
||||
field_dimension * sizeof(float));
|
||||
free(vector_data);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case ZVEC_DATA_TYPE_VECTOR_FP64: {
|
||||
double *vector_data =
|
||||
(double *)malloc(field_dimension * sizeof(double));
|
||||
if (vector_data) {
|
||||
for (uint32_t j = 0; j < field_dimension; j++) {
|
||||
vector_data[j] = (double)(doc_id + j * 0.1);
|
||||
}
|
||||
err = zvec_doc_add_field_by_value(doc, field_name, field_type,
|
||||
vector_data,
|
||||
field_dimension * sizeof(double));
|
||||
free(vector_data);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case ZVEC_DATA_TYPE_VECTOR_FP16: {
|
||||
float *vector_data = (float *)malloc(field_dimension * sizeof(float));
|
||||
if (vector_data) {
|
||||
for (uint32_t j = 0; j < field_dimension; j++) {
|
||||
vector_data[j] = (float)(doc_id + j * 0.1);
|
||||
}
|
||||
err = zvec_doc_add_field_by_value(doc, field_name, field_type,
|
||||
vector_data,
|
||||
field_dimension * sizeof(float));
|
||||
free(vector_data);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case ZVEC_DATA_TYPE_VECTOR_INT8: {
|
||||
int8_t *vector_data =
|
||||
(int8_t *)malloc(field_dimension * sizeof(int8_t));
|
||||
if (vector_data) {
|
||||
for (uint32_t j = 0; j < field_dimension; j++) {
|
||||
vector_data[j] = (int8_t)(doc_id % 128);
|
||||
}
|
||||
err = zvec_doc_add_field_by_value(doc, field_name, field_type,
|
||||
vector_data,
|
||||
field_dimension * sizeof(int8_t));
|
||||
free(vector_data);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case ZVEC_DATA_TYPE_VECTOR_INT16: {
|
||||
int16_t *vector_data =
|
||||
(int16_t *)malloc(field_dimension * sizeof(int16_t));
|
||||
if (vector_data) {
|
||||
for (uint32_t j = 0; j < field_dimension; j++) {
|
||||
vector_data[j] = (int16_t)(doc_id % 32768);
|
||||
}
|
||||
err = zvec_doc_add_field_by_value(doc, field_name, field_type,
|
||||
vector_data,
|
||||
field_dimension * sizeof(int16_t));
|
||||
free(vector_data);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case ZVEC_DATA_TYPE_SPARSE_VECTOR_FP16:
|
||||
case ZVEC_DATA_TYPE_SPARSE_VECTOR_FP32: {
|
||||
const size_t nnz = 100;
|
||||
size_t sparse_size =
|
||||
sizeof(size_t) + nnz * (sizeof(uint32_t) + sizeof(float));
|
||||
char *sparse_data = (char *)malloc(sparse_size);
|
||||
if (sparse_data) {
|
||||
char *ptr = sparse_data;
|
||||
*((size_t *)ptr) = nnz;
|
||||
ptr += sizeof(size_t);
|
||||
|
||||
for (size_t j = 0; j < nnz; j++) {
|
||||
*((uint32_t *)ptr) = (uint32_t)j;
|
||||
ptr += sizeof(uint32_t);
|
||||
*((float *)ptr) = (float)(doc_id + j * 0.1);
|
||||
ptr += sizeof(float);
|
||||
}
|
||||
err = zvec_doc_add_field_by_value(doc, field_name, field_type,
|
||||
sparse_data, sparse_size);
|
||||
free(sparse_data);
|
||||
}
|
||||
break;
|
||||
}
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
|
||||
if (err != ZVEC_OK) {
|
||||
// Free field names array before returning
|
||||
if (field_names) {
|
||||
for (size_t i = 0; i < field_count; i++) {
|
||||
free((char *)field_names[i]);
|
||||
}
|
||||
free(field_names);
|
||||
}
|
||||
zvec_doc_destroy(doc);
|
||||
return NULL;
|
||||
}
|
||||
}
|
||||
|
||||
// Free field names array (individual strings are freed by the API)
|
||||
if (field_names) {
|
||||
for (size_t i = 0; i < field_count; i++) {
|
||||
free((char *)field_names[i]);
|
||||
}
|
||||
free(field_names);
|
||||
}
|
||||
|
||||
return doc;
|
||||
}
|
||||
|
||||
ZVecDoc *zvec_test_create_doc_with_fields(uint64_t doc_id,
|
||||
const char **field_names,
|
||||
const ZVecDataType *field_types,
|
||||
size_t field_count, const char *pk) {
|
||||
ZVecDoc *doc = zvec_doc_create();
|
||||
if (!doc) return NULL;
|
||||
|
||||
// Set primary key
|
||||
char *primary_key = pk ? strdup_safe(pk) : zvec_test_make_pk(doc_id);
|
||||
if (primary_key) {
|
||||
zvec_doc_set_pk(doc, primary_key);
|
||||
free(primary_key);
|
||||
}
|
||||
|
||||
// Create data for specified fields
|
||||
for (size_t i = 0; i < field_count; i++) {
|
||||
ZVecErrorCode err = ZVEC_OK;
|
||||
|
||||
switch (field_types[i]) {
|
||||
case ZVEC_DATA_TYPE_INT32:
|
||||
err = zvec_doc_add_field_by_value(doc, field_names[i], field_types[i],
|
||||
&(int32_t){(int32_t)doc_id},
|
||||
sizeof(int32_t));
|
||||
break;
|
||||
case ZVEC_DATA_TYPE_STRING: {
|
||||
char string_val[64];
|
||||
snprintf(string_val, sizeof(string_val), "value_%llu",
|
||||
(unsigned long long)doc_id);
|
||||
err = zvec_doc_add_field_by_value(doc, field_names[i], field_types[i],
|
||||
string_val, strlen(string_val));
|
||||
break;
|
||||
}
|
||||
case ZVEC_DATA_TYPE_FLOAT:
|
||||
err =
|
||||
zvec_doc_add_field_by_value(doc, field_names[i], field_types[i],
|
||||
&(float){(float)doc_id}, sizeof(float));
|
||||
break;
|
||||
case ZVEC_DATA_TYPE_VECTOR_FP32: {
|
||||
float vector_data[128];
|
||||
for (int j = 0; j < 128; j++) {
|
||||
vector_data[j] = (float)(doc_id + j * 0.1);
|
||||
}
|
||||
err = zvec_doc_add_field_by_value(doc, field_names[i], field_types[i],
|
||||
vector_data, sizeof(vector_data));
|
||||
break;
|
||||
}
|
||||
default:
|
||||
// Other types can be added here
|
||||
break;
|
||||
}
|
||||
|
||||
if (err != ZVEC_OK) {
|
||||
zvec_doc_destroy(doc);
|
||||
return NULL;
|
||||
}
|
||||
}
|
||||
|
||||
return doc;
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Index Parameter Creation Helper Functions Implementation
|
||||
// =============================================================================
|
||||
|
||||
ZVecIndexParams *zvec_test_create_default_hnsw_params(void) {
|
||||
ZVecIndexParams *params = zvec_index_params_create(ZVEC_INDEX_TYPE_HNSW);
|
||||
if (!params) return NULL;
|
||||
|
||||
zvec_index_params_set_metric_type(params, ZVEC_METRIC_TYPE_IP);
|
||||
zvec_index_params_set_hnsw_params(params, 16, 100);
|
||||
|
||||
return params;
|
||||
}
|
||||
|
||||
ZVecIndexParams *zvec_test_create_default_flat_params(void) {
|
||||
ZVecIndexParams *params = zvec_index_params_create(ZVEC_INDEX_TYPE_FLAT);
|
||||
if (!params) return NULL;
|
||||
|
||||
zvec_index_params_set_metric_type(params, ZVEC_METRIC_TYPE_IP);
|
||||
|
||||
return params;
|
||||
}
|
||||
|
||||
ZVecIndexParams *zvec_test_create_default_invert_params(bool enable_optimize) {
|
||||
ZVecIndexParams *params = zvec_index_params_create(ZVEC_INDEX_TYPE_INVERT);
|
||||
if (!params) return NULL;
|
||||
|
||||
zvec_index_params_set_invert_params(params, enable_optimize, enable_optimize);
|
||||
|
||||
return params;
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Field Schema Creation Helper Functions Implementation
|
||||
// =============================================================================
|
||||
|
||||
ZVecFieldSchema *zvec_test_create_scalar_field(
|
||||
const char *name, ZVecDataType data_type, bool nullable,
|
||||
const ZVecIndexParams *invert_params) {
|
||||
// Use the public API to create the field
|
||||
ZVecFieldSchema *field =
|
||||
zvec_field_schema_create(name, data_type, nullable, 0);
|
||||
if (!field) return NULL;
|
||||
|
||||
if (invert_params) {
|
||||
// Clone the index params using setter API
|
||||
ZVecIndexType type = zvec_index_params_get_type(invert_params);
|
||||
ZVecIndexParams *cloned_params = zvec_index_params_create(type);
|
||||
if (cloned_params) {
|
||||
bool enable_range_opt, enable_wildcard;
|
||||
zvec_index_params_get_invert_params(invert_params, &enable_range_opt,
|
||||
&enable_wildcard);
|
||||
zvec_index_params_set_invert_params(cloned_params, enable_range_opt,
|
||||
enable_wildcard);
|
||||
zvec_field_schema_set_index_params(field, cloned_params);
|
||||
zvec_index_params_destroy(cloned_params);
|
||||
}
|
||||
}
|
||||
|
||||
return field;
|
||||
}
|
||||
|
||||
ZVecFieldSchema *zvec_test_create_vector_field(
|
||||
const char *name, ZVecDataType data_type, uint32_t dimension, bool nullable,
|
||||
const ZVecIndexParams *vector_index_params) {
|
||||
// Use the public API to create the field
|
||||
ZVecFieldSchema *field =
|
||||
zvec_field_schema_create(name, data_type, nullable, dimension);
|
||||
if (!field) return NULL;
|
||||
|
||||
if (vector_index_params) {
|
||||
// Clone the index params using setter API
|
||||
ZVecIndexType type = zvec_index_params_get_type(vector_index_params);
|
||||
ZVecIndexParams *cloned_params = zvec_index_params_create(type);
|
||||
if (cloned_params) {
|
||||
int m, ef_construction;
|
||||
m = zvec_index_params_get_hnsw_m(vector_index_params);
|
||||
ef_construction =
|
||||
zvec_index_params_get_hnsw_ef_construction(vector_index_params);
|
||||
zvec_index_params_set_hnsw_params(cloned_params, m, ef_construction);
|
||||
zvec_field_schema_set_index_params(field, cloned_params);
|
||||
zvec_index_params_destroy(cloned_params);
|
||||
}
|
||||
}
|
||||
|
||||
return field;
|
||||
}
|
||||
|
||||
ZVecFieldSchema *zvec_test_create_sparse_vector_field(
|
||||
const char *name, ZVecDataType data_type, bool nullable,
|
||||
const ZVecIndexParams *vector_index_params) {
|
||||
// Use the public API to create the field
|
||||
ZVecFieldSchema *field =
|
||||
zvec_field_schema_create(name, data_type, nullable, 0);
|
||||
if (!field) return NULL;
|
||||
|
||||
if (vector_index_params) {
|
||||
// Clone the index params using setter API
|
||||
ZVecIndexType type = zvec_index_params_get_type(vector_index_params);
|
||||
ZVecIndexParams *cloned_params = zvec_index_params_create(type);
|
||||
if (cloned_params) {
|
||||
int m, ef_construction;
|
||||
m = zvec_index_params_get_hnsw_m(vector_index_params);
|
||||
ef_construction =
|
||||
zvec_index_params_get_hnsw_ef_construction(vector_index_params);
|
||||
zvec_index_params_set_hnsw_params(cloned_params, m, ef_construction);
|
||||
zvec_field_schema_set_index_params(field, cloned_params);
|
||||
zvec_index_params_destroy(cloned_params);
|
||||
}
|
||||
}
|
||||
|
||||
return field;
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Memory Management Helper Functions Implementation
|
||||
// =============================================================================
|
||||
|
||||
// Note: zvec_test_free_field_schemas is deprecated.
|
||||
// Use zvec_field_schema_destroy() to free individual field schemas.
|
||||
|
||||
void zvec_test_free_strings(char **strings, size_t count) {
|
||||
if (!strings) return;
|
||||
|
||||
for (size_t i = 0; i < count; i++) {
|
||||
if (strings[i]) {
|
||||
free(strings[i]);
|
||||
}
|
||||
}
|
||||
|
||||
free(strings);
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// File System Helper Functions Implementation
|
||||
// =============================================================================
|
||||
|
||||
/**
|
||||
* @brief Delete directory and all its contents (wrapper function)
|
||||
*
|
||||
* @param dir_path Directory path
|
||||
* @return int 0 for success, -1 for failure
|
||||
*/
|
||||
int zvec_test_delete_dir(const char *dir_path) {
|
||||
if (!dir_path) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
#ifdef _WIN32
|
||||
// Windows platform implementation
|
||||
char cmd[1024];
|
||||
snprintf(cmd, sizeof(cmd), "rd /s /q \"%s\" >nul 2>&1", dir_path);
|
||||
int result = system(cmd);
|
||||
return (result == 0) ? 0 : -1;
|
||||
#else
|
||||
// Unix/Linux/macOS platform implementation
|
||||
char cmd[1024];
|
||||
snprintf(cmd, sizeof(cmd), "rm -rf \"%s\" 2>/dev/null", dir_path);
|
||||
int result = system(cmd);
|
||||
return (result == 0) ? 0 : -1;
|
||||
#endif
|
||||
}
|
||||
+247
@@ -0,0 +1,247 @@
|
||||
// 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.
|
||||
|
||||
#ifndef ZVEC_TESTS_C_API_UTILS_H
|
||||
#define ZVEC_TESTS_C_API_UTILS_H
|
||||
|
||||
#include <stdbool.h>
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
#include "zvec/c_api.h"
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
// =============================================================================
|
||||
// Schema Creation Helper Functions
|
||||
// =============================================================================
|
||||
|
||||
/**
|
||||
* @brief Create temporary test schema
|
||||
* Contains basic scalar fields and vector fields
|
||||
*
|
||||
* @return ZVecCollectionSchema* Created schema pointer, needs to be released by
|
||||
* calling zvec_collection_schema_cleanup
|
||||
*/
|
||||
ZVecCollectionSchema *zvec_test_create_temp_schema(void);
|
||||
|
||||
/**
|
||||
* @brief Create pure scalar schema
|
||||
* Contains only scalar fields (int32, string)
|
||||
*
|
||||
* @return ZVecCollectionSchema* Created schema pointer
|
||||
*/
|
||||
ZVecCollectionSchema *zvec_test_create_scalar_schema(void);
|
||||
|
||||
/**
|
||||
* @brief Create full-featured schema
|
||||
* Contains all supported data type fields
|
||||
*
|
||||
* @param nullable Whether to allow null values
|
||||
* @param name Schema name
|
||||
* @param scalar_index_params Scalar index parameters (can be NULL)
|
||||
* @param vector_index_params Vector index parameters (can be NULL)
|
||||
* @param max_doc_count Maximum documents per segment
|
||||
* @return ZVecCollectionSchema* Created schema pointer
|
||||
*/
|
||||
ZVecCollectionSchema *zvec_test_create_normal_schema(
|
||||
bool nullable, const char *name, const ZVecIndexParams *scalar_index_params,
|
||||
const ZVecIndexParams *vector_index_params, uint64_t max_doc_count);
|
||||
|
||||
/**
|
||||
* @brief Create schema with scalar index
|
||||
*
|
||||
* @param nullable Whether to allow null values
|
||||
* @param enable_optimize Whether to enable optimization
|
||||
* @param name Schema name
|
||||
* @return ZVecCollectionSchema* Created schema pointer
|
||||
*/
|
||||
ZVecCollectionSchema *zvec_test_create_schema_with_scalar_index(
|
||||
bool nullable, bool enable_optimize, const char *name);
|
||||
|
||||
/**
|
||||
* @brief Create schema with vector index
|
||||
*
|
||||
* @param nullable Whether to allow null values
|
||||
* @param name Schema name
|
||||
* @param vector_index_params Vector index parameters (can be NULL, uses default
|
||||
* HNSW parameters)
|
||||
* @return ZVecCollectionSchema* Created schema pointer
|
||||
*/
|
||||
ZVecCollectionSchema *zvec_test_create_schema_with_vector_index(
|
||||
bool nullable, const char *name,
|
||||
const ZVecIndexParams *vector_index_params);
|
||||
|
||||
/**
|
||||
* @brief Create schema with specified maximum document count
|
||||
*
|
||||
* @param doc_count Maximum documents per segment
|
||||
* @return ZVecCollectionSchema* Created schema pointer
|
||||
*/
|
||||
ZVecCollectionSchema *zvec_test_create_schema_with_max_doc_count(
|
||||
uint64_t doc_count);
|
||||
|
||||
// =============================================================================
|
||||
// Document Creation Helper Functions
|
||||
// =============================================================================
|
||||
|
||||
/**
|
||||
* @brief Generate primary key based on document ID
|
||||
*
|
||||
* @param doc_id Document ID
|
||||
* @return char* Generated primary key string, needs to be released by calling
|
||||
* free()
|
||||
*/
|
||||
char *zvec_test_make_pk(uint64_t doc_id);
|
||||
|
||||
/**
|
||||
* @brief Create complete document
|
||||
* Create corresponding test data for each field according to schema
|
||||
*
|
||||
* @param doc_id Document ID
|
||||
* @param schema Schema pointer
|
||||
* @param pk Primary key (can be NULL, auto-generated)
|
||||
* @return ZVecDoc* Created document pointer, needs to be released by calling
|
||||
* zvec_doc_destroy
|
||||
*/
|
||||
ZVecDoc *zvec_test_create_doc(uint64_t doc_id,
|
||||
const ZVecCollectionSchema *schema,
|
||||
const char *pk);
|
||||
|
||||
/**
|
||||
* @brief Create partial null document
|
||||
* Only set values for vector fields, keep scalar fields as null
|
||||
*
|
||||
* @param doc_id Document ID
|
||||
* @param schema Schema pointer
|
||||
* @param pk Primary key (can be NULL, auto-generated)
|
||||
* @return ZVecDoc* Created document pointer
|
||||
*/
|
||||
ZVecDoc *zvec_test_create_doc_null(uint64_t doc_id,
|
||||
const ZVecCollectionSchema *schema,
|
||||
const char *pk);
|
||||
|
||||
/**
|
||||
* @brief Create document with specified fields
|
||||
* Only create data for specified fields
|
||||
*
|
||||
* @param doc_id Document ID
|
||||
* @param field_names Field name array
|
||||
* @param field_types Field type array
|
||||
* @param field_count Number of fields
|
||||
* @param pk Primary key (can be NULL, auto-generated)
|
||||
* @return ZVecDoc* Created document pointer
|
||||
*/
|
||||
ZVecDoc *zvec_test_create_doc_with_fields(uint64_t doc_id,
|
||||
const char **field_names,
|
||||
const ZVecDataType *field_types,
|
||||
size_t field_count, const char *pk);
|
||||
|
||||
// =============================================================================
|
||||
// Index Parameter Creation Helper Functions
|
||||
// =============================================================================
|
||||
|
||||
/**
|
||||
* @brief Create default HNSW index parameters
|
||||
*
|
||||
* @return ZVecIndexParams* Created parameter pointer
|
||||
*/
|
||||
ZVecIndexParams *zvec_test_create_default_hnsw_params(void);
|
||||
|
||||
/**
|
||||
* @brief Create default Flat index parameters
|
||||
*
|
||||
* @return ZVecIndexParams* Created parameter pointer
|
||||
*/
|
||||
ZVecIndexParams *zvec_test_create_default_flat_params(void);
|
||||
|
||||
/**
|
||||
* @brief Create default scalar index parameters
|
||||
*
|
||||
* @param enable_optimize Whether to enable optimization
|
||||
* @return ZVecIndexParams* Created parameter pointer
|
||||
*/
|
||||
ZVecIndexParams *zvec_test_create_default_invert_params(bool enable_optimize);
|
||||
|
||||
// =============================================================================
|
||||
// Field Schema Creation Helper Functions
|
||||
// =============================================================================
|
||||
|
||||
/**
|
||||
* @brief Create scalar field schema
|
||||
*
|
||||
* @param name Field name
|
||||
* @param data_type Data type
|
||||
* @param nullable Whether to allow null values
|
||||
* @param invert_params Scalar index parameters (can be NULL)
|
||||
* @return ZVecFieldSchema* Created field schema pointer, needs to be released
|
||||
* by calling free()
|
||||
*/
|
||||
ZVecFieldSchema *zvec_test_create_scalar_field(
|
||||
const char *name, ZVecDataType data_type, bool nullable,
|
||||
const ZVecIndexParams *invert_params);
|
||||
|
||||
/**
|
||||
* @brief Create vector field schema
|
||||
*
|
||||
* @param name Field name
|
||||
* @param data_type Data type
|
||||
* @param dimension Vector dimension
|
||||
* @param nullable Whether to allow null values
|
||||
* @param vector_index_params Vector index parameters (can be NULL)
|
||||
* @return ZVecFieldSchema* Created field schema pointer
|
||||
*/
|
||||
ZVecFieldSchema *zvec_test_create_vector_field(
|
||||
const char *name, ZVecDataType data_type, uint32_t dimension, bool nullable,
|
||||
const ZVecIndexParams *vector_index_params);
|
||||
|
||||
/**
|
||||
* @brief Create sparse vector field schema
|
||||
*
|
||||
* @param name Field name
|
||||
* @param data_type Data type
|
||||
* @param nullable Whether to allow null values
|
||||
* @param vector_index_params Vector index parameters (can be NULL)
|
||||
* @return ZVecFieldSchema* Created field schema pointer
|
||||
*/
|
||||
ZVecFieldSchema *zvec_test_create_sparse_vector_field(
|
||||
const char *name, ZVecDataType data_type, bool nullable,
|
||||
const ZVecIndexParams *vector_index_params);
|
||||
|
||||
// =============================================================================
|
||||
// Memory Management Helper Functions
|
||||
// =============================================================================
|
||||
|
||||
/**
|
||||
* @brief Free string array
|
||||
*
|
||||
* @param strings String array pointer
|
||||
* @param count Number of strings
|
||||
*/
|
||||
void zvec_test_free_strings(char **strings, size_t count);
|
||||
|
||||
/**
|
||||
* @brief Delete directory and all its contents
|
||||
*
|
||||
* @param dir_path Directory path
|
||||
* @return int 0 for success, -1 for failure
|
||||
*/
|
||||
int zvec_test_delete_dir(const char *dir_path);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif // ZVEC_TESTS_C_API_UTILS_H
|
||||
Reference in New Issue
Block a user