Initial commit
This commit is contained in:
@@ -0,0 +1,22 @@
|
||||
include(${PROJECT_ROOT_DIR}/cmake/bazel.cmake)
|
||||
include(${PROJECT_ROOT_DIR}/cmake/option.cmake)
|
||||
|
||||
cc_proto_library(
|
||||
NAME zvec_proto STATIC
|
||||
SRCS proto/*.proto
|
||||
PROTOROOT ./
|
||||
)
|
||||
|
||||
cc_directory(common)
|
||||
cc_directory(index)
|
||||
cc_directory(sqlengine)
|
||||
|
||||
cc_library(
|
||||
NAME zvec STATIC STRICT
|
||||
SRCS *.cc
|
||||
LIBS zvec_common
|
||||
zvec_index
|
||||
zvec_sqlengine
|
||||
INCS .
|
||||
VERSION "${PROXIMA_ZVEC_VERSION}"
|
||||
)
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,111 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
#pragma once
|
||||
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <ailego/io/file.h>
|
||||
#include <ailego/pattern/expected.hpp>
|
||||
#include "db/common/status.h"
|
||||
#include "index/common/doc.h"
|
||||
#include "index/common/options.h"
|
||||
#include "index/common/stats.h"
|
||||
|
||||
namespace zvec {
|
||||
|
||||
class Collection {
|
||||
public:
|
||||
using Ptr = std::shared_ptr<Collection>;
|
||||
|
||||
/**
|
||||
* @brief Create and open a collection.
|
||||
*
|
||||
* @param path The path to the collection.
|
||||
* @param schema The schema of the collection.
|
||||
* @param option The options of the collection.
|
||||
* @return The collection OR an error.
|
||||
*/
|
||||
static Result<Ptr> CreateAndOpen(const std::string &path,
|
||||
const CollectionSchema &schema,
|
||||
const CollectionOptions &option);
|
||||
|
||||
/**
|
||||
* @brief Open an existing collection.
|
||||
*
|
||||
* @param path The path to the collection.
|
||||
* @param option The options of the collection.
|
||||
* @return The collection OR an error.
|
||||
*/
|
||||
static Result<Ptr> Open(const std::string &path,
|
||||
const CollectionOptions &option);
|
||||
|
||||
virtual ~Collection();
|
||||
|
||||
public:
|
||||
virtual Status Destroy() = 0;
|
||||
|
||||
virtual Status Flush() = 0;
|
||||
|
||||
virtual Result<std::string> Path() const = 0;
|
||||
|
||||
virtual Result<CollectionStats> Stats() const = 0;
|
||||
|
||||
virtual Result<CollectionSchema> Schema() const = 0;
|
||||
|
||||
virtual Result<CollectionOptions> Options() const = 0;
|
||||
|
||||
public:
|
||||
virtual Status CreateIndex(
|
||||
const std::string &column_name, const IndexParams::Ptr &index_params,
|
||||
const CreateIndexOptions &options = CreateIndexOptions{0}) = 0;
|
||||
|
||||
virtual Status DropIndex(const std::string &column_name) = 0;
|
||||
|
||||
virtual Status Optimize(const OptimizeOptions &options = OptimizeOptions{
|
||||
0}) = 0;
|
||||
|
||||
virtual Status AddColumn(const std::string &column_name,
|
||||
const FieldSchema::Ptr &column_schema,
|
||||
const std::string &expression,
|
||||
const AddColumnOptions &options = AddColumnOptions{
|
||||
0}) = 0;
|
||||
|
||||
virtual Status DropColumn(const std::string &column_name) = 0;
|
||||
|
||||
virtual Status AlterColumn(
|
||||
const std::string &column_name, const std::string &rename,
|
||||
const FieldSchema::Ptr &new_column_schema = nullptr,
|
||||
const AlterColumnOptions &options = AlterColumnOptions{0}) = 0;
|
||||
|
||||
virtual Result<WriteResults> Insert(std::vector<Doc> &docs) = 0;
|
||||
|
||||
virtual Result<WriteResults> Upsert(std::vector<Doc> &docs) = 0;
|
||||
|
||||
virtual Result<WriteResults> Update(std::vector<Doc> &docs) = 0;
|
||||
|
||||
virtual Result<WriteResults> Delete(const std::vector<std::string> &pks) = 0;
|
||||
|
||||
virtual Status DeleteByFilter(const std::string &filter) = 0;
|
||||
|
||||
virtual Result<DocPtrList> Query(const VectorQuery &query) const = 0;
|
||||
|
||||
virtual Result<GroupResults> GroupByQuery(
|
||||
const GroupByVectorQuery &query) const = 0;
|
||||
|
||||
virtual Result<DocPtrMap> Fetch(
|
||||
const std::vector<std::string> &pks) const = 0;
|
||||
};
|
||||
|
||||
} // namespace zvec
|
||||
@@ -0,0 +1,14 @@
|
||||
include(${PROJECT_ROOT_DIR}/cmake/bazel.cmake)
|
||||
include(${PROJECT_ROOT_DIR}/cmake/option.cmake)
|
||||
|
||||
# proxima_zvec_store library
|
||||
cc_library(
|
||||
NAME zvec_common STATIC STRICT ALWAYS_LINK
|
||||
SRCS *.cc
|
||||
LIBS glog
|
||||
zvec_ailego
|
||||
roaring
|
||||
rocksdb
|
||||
INCS .
|
||||
VERSION "${PROXIMA_ZVEC_VERSION}"
|
||||
)
|
||||
@@ -0,0 +1,467 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#include "db/common/cgroup_util.h"
|
||||
|
||||
namespace zvec {
|
||||
|
||||
// Static member definitions
|
||||
int CgroupUtil::cpu_cores_ = 0;
|
||||
uint64_t CgroupUtil::memory_limit_ = 0;
|
||||
bool CgroupUtil::initialized_ = false;
|
||||
unsigned long long CgroupUtil::last_idle_time_ = 0;
|
||||
unsigned long long CgroupUtil::last_total_time_ = 0;
|
||||
std::chrono::steady_clock::time_point CgroupUtil::last_cpu_check_;
|
||||
|
||||
#define ZVEC_CGROUP_MEMORY_UNLIMITED (9223372036854771712ULL)
|
||||
|
||||
// Static initialization method
|
||||
void CgroupUtil::initialize() {
|
||||
if (initialized_) {
|
||||
return;
|
||||
}
|
||||
|
||||
updateCpuCores();
|
||||
updateMemoryLimit();
|
||||
initializeCpuStats();
|
||||
|
||||
initialized_ = true;
|
||||
}
|
||||
|
||||
int CgroupUtil::getCpuLimit() {
|
||||
initialize();
|
||||
return cpu_cores_;
|
||||
}
|
||||
|
||||
uint64_t CgroupUtil::getMemoryLimit() {
|
||||
initialize();
|
||||
return memory_limit_;
|
||||
}
|
||||
|
||||
// Other static methods implementation
|
||||
double CgroupUtil::getCpuUsage() {
|
||||
initialize();
|
||||
return calculateCpuUsage();
|
||||
}
|
||||
|
||||
uint64_t CgroupUtil::getMemoryUsage() {
|
||||
initialize();
|
||||
return getCurrentMemoryUsage();
|
||||
}
|
||||
|
||||
uint64_t CgroupUtil::getUptime() {
|
||||
#if defined(PLATFORM_LINUX)
|
||||
struct sysinfo info;
|
||||
if (sysinfo(&info) == 0) {
|
||||
return info.uptime;
|
||||
}
|
||||
#elif defined(PLATFORM_MACOS)
|
||||
struct timeval boottime;
|
||||
size_t len = sizeof(boottime);
|
||||
int mib[2] = {CTL_KERN, KERN_BOOTTIME};
|
||||
if (sysctl(mib, 2, &boottime, &len, NULL, 0) == 0) {
|
||||
time_t bsec = boottime.tv_sec;
|
||||
time_t csec = time(NULL);
|
||||
return csec - bsec;
|
||||
}
|
||||
#endif
|
||||
return 0;
|
||||
}
|
||||
|
||||
void CgroupUtil::updateCpuCores() {
|
||||
if (readCpuCgroup()) {
|
||||
return;
|
||||
}
|
||||
|
||||
#if defined(PLATFORM_MACOS)
|
||||
int cores;
|
||||
size_t len = sizeof(cores);
|
||||
if (sysctlbyname("hw.ncpu", &cores, &len, nullptr, 0) == 0) {
|
||||
cpu_cores_ = cores;
|
||||
} else {
|
||||
cpu_cores_ = 1;
|
||||
}
|
||||
#elif defined(PLATFORM_LINUX)
|
||||
cpu_cores_ = sysconf(_SC_NPROCESSORS_ONLN);
|
||||
if (cpu_cores_ <= 0) {
|
||||
cpu_cores_ = 1;
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
bool CgroupUtil::readCpuCgroup() {
|
||||
#if defined(PLATFORM_LINUX)
|
||||
// cgroup v2
|
||||
std::ifstream file("/sys/fs/cgroup/cpu.max");
|
||||
if (file.is_open()) {
|
||||
uint64_t quota, period;
|
||||
char slash;
|
||||
file >> quota >> slash >> period;
|
||||
file.close();
|
||||
|
||||
if (quota != std::numeric_limits<uint64_t>::max() && quota != 0 &&
|
||||
period > 0) {
|
||||
cpu_cores_ =
|
||||
static_cast<int>(std::ceil(static_cast<double>(quota) / period));
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// cgroup v1
|
||||
std::ifstream quota_file("/sys/fs/cgroup/cpu/cpu.cfs_quota_us");
|
||||
std::ifstream period_file("/sys/fs/cgroup/cpu/cpu.cfs_period_us");
|
||||
|
||||
if (quota_file.is_open() && period_file.is_open()) {
|
||||
long long quota, period;
|
||||
quota_file >> quota;
|
||||
period_file >> period;
|
||||
quota_file.close();
|
||||
period_file.close();
|
||||
|
||||
if (quota > 0 && period > 0) {
|
||||
cpu_cores_ =
|
||||
static_cast<int>(std::ceil(static_cast<double>(quota) / period));
|
||||
return true;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
return false;
|
||||
}
|
||||
|
||||
void CgroupUtil::updateMemoryLimit() {
|
||||
if (readMemoryCgroup()) {
|
||||
return;
|
||||
}
|
||||
|
||||
#if defined(PLATFORM_MACOS)
|
||||
uint64_t mem;
|
||||
size_t len = sizeof(mem);
|
||||
if (sysctlbyname("hw.memsize", &mem, &len, nullptr, 0) == 0) {
|
||||
memory_limit_ = mem;
|
||||
} else {
|
||||
memory_limit_ = 0;
|
||||
}
|
||||
#elif defined(PLATFORM_LINUX)
|
||||
long pages = sysconf(_SC_PHYS_PAGES);
|
||||
long page_size = sysconf(_SC_PAGE_SIZE);
|
||||
if (pages > 0 && page_size > 0) {
|
||||
memory_limit_ = static_cast<uint64_t>(pages) * page_size;
|
||||
} else {
|
||||
memory_limit_ = 0;
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
bool CgroupUtil::readMemoryCgroup() {
|
||||
#if defined(PLATFORM_LINUX)
|
||||
// cgroup v2
|
||||
std::ifstream file("/sys/fs/cgroup/memory.max");
|
||||
if (file.is_open()) {
|
||||
uint64_t limit;
|
||||
file >> limit;
|
||||
file.close();
|
||||
|
||||
if (limit != std::numeric_limits<uint64_t>::max() && limit != 0 &&
|
||||
limit != ZVEC_CGROUP_MEMORY_UNLIMITED) {
|
||||
memory_limit_ = limit;
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// cgroup v1
|
||||
std::ifstream v1_file("/sys/fs/cgroup/memory/memory.limit_in_bytes");
|
||||
if (v1_file.is_open()) {
|
||||
uint64_t limit;
|
||||
v1_file >> limit;
|
||||
v1_file.close();
|
||||
|
||||
if (limit < std::numeric_limits<uint64_t>::max() &&
|
||||
limit != ZVEC_CGROUP_MEMORY_UNLIMITED) {
|
||||
memory_limit_ = limit;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
return false;
|
||||
}
|
||||
|
||||
void CgroupUtil::initializeCpuStats() {
|
||||
last_cpu_check_ = std::chrono::steady_clock::now();
|
||||
#if defined(PLATFORM_LINUX)
|
||||
readProcStat();
|
||||
#endif
|
||||
}
|
||||
|
||||
#if defined(PLATFORM_LINUX)
|
||||
bool CgroupUtil::readProcStat() {
|
||||
std::ifstream file("/proc/stat");
|
||||
if (!file.is_open()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
std::string line;
|
||||
if (!std::getline(file, line)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
std::istringstream iss(line);
|
||||
std::string cpu_label;
|
||||
iss >> cpu_label;
|
||||
|
||||
if (cpu_label != "cpu") {
|
||||
return false;
|
||||
}
|
||||
|
||||
unsigned long long user, nice, system, idle, iowait, irq, softirq, steal;
|
||||
iss >> user >> nice >> system >> idle >> iowait >> irq >> softirq >> steal;
|
||||
|
||||
unsigned long long idle_time = idle + iowait;
|
||||
unsigned long long total_time =
|
||||
user + nice + system + irq + softirq + steal + idle_time;
|
||||
|
||||
last_idle_time_ = idle_time;
|
||||
last_total_time_ = total_time;
|
||||
|
||||
return true;
|
||||
}
|
||||
#endif
|
||||
|
||||
uint64_t CgroupUtil::getCurrentMemoryUsage() {
|
||||
#if defined(PLATFORM_LINUX)
|
||||
// cgroup
|
||||
uint64_t usage = readMemoryUsageCgroup();
|
||||
if (usage > 0) {
|
||||
return usage;
|
||||
}
|
||||
|
||||
// back to /proc/meminfo
|
||||
return readMemoryUsageProc();
|
||||
#elif defined(PLATFORM_MACOS)
|
||||
return getMacOSMemoryUsage();
|
||||
#endif
|
||||
}
|
||||
|
||||
#if defined(PLATFORM_LINUX)
|
||||
uint64_t CgroupUtil::readMemoryUsageCgroup() {
|
||||
// cgroup v2
|
||||
std::ifstream file("/sys/fs/cgroup/memory.current");
|
||||
if (file.is_open()) {
|
||||
uint64_t usage;
|
||||
file >> usage;
|
||||
file.close();
|
||||
return usage;
|
||||
}
|
||||
|
||||
// cgroup v1
|
||||
std::ifstream v1_file("/sys/fs/cgroup/memory/memory.usage_in_bytes");
|
||||
if (v1_file.is_open()) {
|
||||
uint64_t usage;
|
||||
v1_file >> usage;
|
||||
v1_file.close();
|
||||
return usage;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
uint64_t CgroupUtil::readMemoryUsageProc() {
|
||||
std::ifstream file("/proc/meminfo");
|
||||
if (!file.is_open()) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
std::string line;
|
||||
uint64_t total_mem = 0;
|
||||
uint64_t free_mem = 0;
|
||||
uint64_t available_mem = 0;
|
||||
uint64_t buffers = 0;
|
||||
uint64_t cached = 0;
|
||||
|
||||
while (std::getline(file, line)) {
|
||||
if (line.find("MemTotal:") == 0) {
|
||||
total_mem = extractMemoryValue(line);
|
||||
} else if (line.find("MemFree:") == 0) {
|
||||
free_mem = extractMemoryValue(line);
|
||||
} else if (line.find("MemAvailable:") == 0) {
|
||||
available_mem = extractMemoryValue(line);
|
||||
} else if (line.find("Buffers:") == 0) {
|
||||
buffers = extractMemoryValue(line);
|
||||
} else if (line.find("Cached:") == 0) {
|
||||
cached = extractMemoryValue(line);
|
||||
}
|
||||
}
|
||||
|
||||
if (available_mem > 0 && total_mem > available_mem) {
|
||||
return total_mem - available_mem;
|
||||
}
|
||||
|
||||
if (total_mem > 0 && free_mem > 0) {
|
||||
return total_mem - free_mem - buffers - cached;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
#endif
|
||||
|
||||
#if defined(PLATFORM_MACOS)
|
||||
uint64_t CgroupUtil::getMacOSMemoryUsage() {
|
||||
mach_port_t host_port = mach_host_self();
|
||||
mach_msg_type_number_t host_size =
|
||||
sizeof(vm_statistics64_data_t) / sizeof(integer_t);
|
||||
vm_size_t page_size;
|
||||
vm_statistics64_data_t vm_stat;
|
||||
|
||||
if (host_page_size(host_port, &page_size) != KERN_SUCCESS) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (host_statistics64(host_port, HOST_VM_INFO64, (host_info64_t)&vm_stat,
|
||||
&host_size) != KERN_SUCCESS) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
uint64_t used_memory =
|
||||
((vm_stat.active_count + vm_stat.inactive_count + vm_stat.wire_count) *
|
||||
page_size);
|
||||
|
||||
return used_memory;
|
||||
}
|
||||
#endif
|
||||
|
||||
uint64_t CgroupUtil::extractMemoryValue(const std::string &line) {
|
||||
size_t colon_pos = line.find(':');
|
||||
if (colon_pos == std::string::npos) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
std::string value_str = line.substr(colon_pos + 1);
|
||||
std::istringstream iss(value_str);
|
||||
uint64_t value;
|
||||
std::string unit;
|
||||
|
||||
iss >> value;
|
||||
if (iss >> unit) {
|
||||
if (unit == "kB") {
|
||||
value *= 1024;
|
||||
}
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
double CgroupUtil::calculateCpuUsage() {
|
||||
#if defined(PLATFORM_LINUX)
|
||||
return calculateLinuxCpuUsage();
|
||||
#elif defined(PLATFORM_MACOS)
|
||||
return calculateMacOSCpuUsage();
|
||||
#endif
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
#if defined(PLATFORM_LINUX)
|
||||
double CgroupUtil::calculateLinuxCpuUsage() {
|
||||
if (!readProcStat()) {
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(100));
|
||||
|
||||
std::ifstream file("/proc/stat");
|
||||
if (!file.is_open()) {
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
std::string line;
|
||||
if (!std::getline(file, line)) {
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
std::istringstream iss(line);
|
||||
std::string cpu_label;
|
||||
iss >> cpu_label;
|
||||
|
||||
if (cpu_label != "cpu") {
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
unsigned long long user, nice, system, idle, iowait, irq, softirq, steal;
|
||||
iss >> user >> nice >> system >> idle >> iowait >> irq >> softirq >> steal;
|
||||
|
||||
unsigned long long current_idle = idle + iowait;
|
||||
unsigned long long current_total =
|
||||
user + nice + system + irq + softirq + steal + current_idle;
|
||||
|
||||
unsigned long long idle_delta = current_idle - last_idle_time_;
|
||||
unsigned long long total_delta = current_total - last_total_time_;
|
||||
|
||||
last_idle_time_ = current_idle;
|
||||
last_total_time_ = current_total;
|
||||
|
||||
if (total_delta == 0) {
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
double cpu_usage =
|
||||
100.0 * (1.0 - static_cast<double>(idle_delta) / total_delta);
|
||||
return std::max(0.0, std::min(100.0, cpu_usage));
|
||||
}
|
||||
#endif
|
||||
|
||||
#if defined(PLATFORM_MACOS)
|
||||
double CgroupUtil::calculateMacOSCpuUsage() {
|
||||
host_cpu_load_info_data_t cpuinfo;
|
||||
mach_msg_type_number_t count = HOST_CPU_LOAD_INFO_COUNT;
|
||||
|
||||
if (host_statistics(mach_host_self(), HOST_CPU_LOAD_INFO,
|
||||
(host_info_t)&cpuinfo, &count) != KERN_SUCCESS) {
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
unsigned long long total_tick =
|
||||
cpuinfo.cpu_ticks[CPU_STATE_USER] + cpuinfo.cpu_ticks[CPU_STATE_SYSTEM] +
|
||||
cpuinfo.cpu_ticks[CPU_STATE_NICE] + cpuinfo.cpu_ticks[CPU_STATE_IDLE];
|
||||
|
||||
unsigned long long idle_tick = cpuinfo.cpu_ticks[CPU_STATE_IDLE];
|
||||
|
||||
static unsigned long long prev_total = 0;
|
||||
static unsigned long long prev_idle = 0;
|
||||
|
||||
if (prev_total == 0) {
|
||||
prev_total = total_tick;
|
||||
prev_idle = idle_tick;
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(100));
|
||||
return calculateMacOSCpuUsage();
|
||||
}
|
||||
|
||||
unsigned long long total_delta = total_tick - prev_total;
|
||||
unsigned long long idle_delta = idle_tick - prev_idle;
|
||||
|
||||
prev_total = total_tick;
|
||||
prev_idle = idle_tick;
|
||||
|
||||
if (total_delta == 0) {
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
double cpu_usage =
|
||||
100.0 * (1.0 - static_cast<double>(idle_delta) / total_delta);
|
||||
return std::max(0.0, std::min(100.0, cpu_usage));
|
||||
}
|
||||
#endif
|
||||
|
||||
} // namespace zvec
|
||||
@@ -0,0 +1,101 @@
|
||||
// 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 <chrono>
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
#include <memory>
|
||||
#include <sstream>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
#if defined(__APPLE__)
|
||||
#define PLATFORM_MACOS 1
|
||||
#include <mach/mach.h>
|
||||
#include <sys/sysctl.h>
|
||||
#elif defined(__linux__)
|
||||
#define PLATFORM_LINUX 1
|
||||
#include <sys/sysinfo.h>
|
||||
#include <unistd.h>
|
||||
#endif
|
||||
|
||||
namespace zvec {
|
||||
|
||||
class CgroupUtil {
|
||||
public:
|
||||
// Static methods to get CPU and memory limits
|
||||
static int getCpuLimit();
|
||||
static uint64_t getMemoryLimit();
|
||||
|
||||
// Static methods to get other resources
|
||||
static double getCpuUsage();
|
||||
static uint64_t getMemoryUsage();
|
||||
static uint64_t getUptime();
|
||||
|
||||
private:
|
||||
CgroupUtil() = default;
|
||||
~CgroupUtil() = default;
|
||||
|
||||
// Static member variables to store the computed values
|
||||
static int cpu_cores_;
|
||||
static uint64_t memory_limit_;
|
||||
static bool initialized_;
|
||||
|
||||
// Other member variables for tracking state
|
||||
static unsigned long long last_idle_time_;
|
||||
static unsigned long long last_total_time_;
|
||||
static std::chrono::steady_clock::time_point last_cpu_check_;
|
||||
|
||||
// Static initialization method
|
||||
static void initialize();
|
||||
|
||||
// Helper methods (also made static)
|
||||
static void updateCpuCores();
|
||||
static bool readCpuCgroup();
|
||||
static void updateMemoryLimit();
|
||||
static bool readMemoryCgroup();
|
||||
static void initializeCpuStats();
|
||||
|
||||
#if defined(PLATFORM_LINUX)
|
||||
static bool readProcStat();
|
||||
#endif
|
||||
|
||||
static uint64_t getCurrentMemoryUsage();
|
||||
|
||||
#if defined(PLATFORM_LINUX)
|
||||
static uint64_t readMemoryUsageCgroup();
|
||||
static uint64_t readMemoryUsageProc();
|
||||
#endif
|
||||
|
||||
#if defined(PLATFORM_MACOS)
|
||||
static uint64_t getMacOSMemoryUsage();
|
||||
#endif
|
||||
|
||||
static uint64_t extractMemoryValue(const std::string &line);
|
||||
static double calculateCpuUsage();
|
||||
|
||||
#if defined(PLATFORM_LINUX)
|
||||
static double calculateLinuxCpuUsage();
|
||||
#endif
|
||||
|
||||
#if defined(PLATFORM_MACOS)
|
||||
static double calculateMacOSCpuUsage();
|
||||
#endif
|
||||
};
|
||||
|
||||
} // namespace zvec
|
||||
@@ -0,0 +1,211 @@
|
||||
// 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 "concurrent_roaring_bitmap.h"
|
||||
#include <ailego/hash/crc32c.h>
|
||||
|
||||
|
||||
namespace zvec {
|
||||
|
||||
|
||||
Status ConcurrentRoaringBitmap32::serialize(std::string *out) {
|
||||
std::unique_lock<std::shared_mutex> lock(mutex_);
|
||||
size_t bitmap_size = roaring_bitmap_portable_size_in_bytes(bitmap_);
|
||||
out->resize(bitmap_size);
|
||||
size_t written_size = roaring_bitmap_portable_serialize(bitmap_, out->data());
|
||||
if (written_size == bitmap_size) {
|
||||
return Status::OK();
|
||||
} else {
|
||||
LOG_ERROR("Failed to serialize bitmap");
|
||||
return Status::InternalError();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Status ConcurrentRoaringBitmap32::deserialize(const std::string &in) {
|
||||
std::unique_lock<std::shared_mutex> lock(mutex_);
|
||||
roaring_bitmap_free(bitmap_);
|
||||
bitmap_ = nullptr;
|
||||
bitmap_ = roaring_bitmap_portable_deserialize_safe(in.data(), in.size());
|
||||
if (bitmap_) {
|
||||
return Status::OK();
|
||||
} else {
|
||||
LOG_ERROR("Failed to deserialize bitmap");
|
||||
return Status::InternalError();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Status ConcurrentRoaringBitmap64::serialize(const std::string &file_path,
|
||||
bool overwrite) {
|
||||
std::unique_lock<std::shared_mutex> lock(mutex_);
|
||||
FILE file;
|
||||
const std::string file_str = "[" + file_path + "]";
|
||||
|
||||
if (FILE::IsExist(file_path)) {
|
||||
if (!FILE::IsRegular(file_path)) {
|
||||
auto msg = debug_str(file_str, " is not a regular file");
|
||||
LOG_ERROR("%s", msg.c_str());
|
||||
return Status::InvalidArgument(msg);
|
||||
}
|
||||
if (!overwrite) {
|
||||
auto msg = debug_str(file_str, " already exists");
|
||||
LOG_ERROR("%s", msg.c_str());
|
||||
return Status::AlreadyExists(msg);
|
||||
}
|
||||
if (!FILE::RemovePath(file_path)) {
|
||||
auto msg = debug_str("failed to remove ", file_str);
|
||||
LOG_ERROR("%s", msg.c_str());
|
||||
return Status::InternalError(msg);
|
||||
}
|
||||
}
|
||||
if (!file.create(file_path.c_str(), 0)) {
|
||||
auto msg = debug_str("failed to create ", file_str);
|
||||
LOG_ERROR("%s", msg.c_str());
|
||||
return Status::InternalError(msg);
|
||||
}
|
||||
|
||||
// Serialize bitmap to buffer
|
||||
BitmapMetaHeader header;
|
||||
size_t bitmap_size;
|
||||
std::vector<char> bitmap_buffer;
|
||||
if (is_32bit_) {
|
||||
bitmap_size = bitmap32_->getSizeInBytes();
|
||||
bitmap_buffer.resize(bitmap_size);
|
||||
if (bitmap32_->write(bitmap_buffer.data()) != bitmap_size) {
|
||||
auto msg = debug_str("failed to serialize bitmap to buffer");
|
||||
LOG_ERROR("%s", msg.c_str());
|
||||
return Status::InternalError(msg);
|
||||
}
|
||||
header.is_32bit = 1;
|
||||
} else {
|
||||
bitmap_size = bitmap64_->getSizeInBytes();
|
||||
bitmap_buffer.resize(bitmap_size);
|
||||
if (bitmap64_->write(bitmap_buffer.data()) != bitmap_size) {
|
||||
auto msg = debug_str("failed to serialize bitmap to buffer");
|
||||
LOG_ERROR("%s", msg.c_str());
|
||||
return Status::InternalError(msg);
|
||||
}
|
||||
header.is_32bit = 0;
|
||||
}
|
||||
header.magic = roaring_magic_number;
|
||||
header.checksum = ailego::Crc32c::Hash(bitmap_buffer.data(), bitmap_size);
|
||||
header.timestamp = time(nullptr);
|
||||
|
||||
// Write meta header to file
|
||||
if (file.write(&header, sizeof(header)) != sizeof(header)) {
|
||||
auto msg = debug_str("failed to serialize header to ", file_str);
|
||||
LOG_ERROR("%s", msg.c_str());
|
||||
return Status::InternalError(msg);
|
||||
}
|
||||
|
||||
// Write serialized bitmap to file
|
||||
if (file.write(bitmap_buffer.data(), bitmap_size) != bitmap_size) {
|
||||
auto msg = debug_str("failed to write bitmap data to ", file_str);
|
||||
LOG_ERROR("%s", msg.c_str());
|
||||
return Status::InternalError(msg);
|
||||
};
|
||||
|
||||
LOG_DEBUG("%s: serialized bitmap to file[%s], checksum[%u], timestamp[%zu]",
|
||||
identifier_.c_str(), file_path.c_str(), header.checksum,
|
||||
(size_t)header.timestamp);
|
||||
return Status::OK();
|
||||
}
|
||||
|
||||
|
||||
Status ConcurrentRoaringBitmap64::deserialize(const std::string &file_path) {
|
||||
std::unique_lock<std::shared_mutex> lock(mutex_);
|
||||
FILE file;
|
||||
const std::string file_str = "[" + file_path + "]";
|
||||
|
||||
if (!FILE::IsExist(file_path)) {
|
||||
auto msg = debug_str(file_str, " does not exist");
|
||||
LOG_ERROR("%s", msg.c_str());
|
||||
return Status::NotFound(msg);
|
||||
}
|
||||
if (!FILE::IsRegular(file_path)) {
|
||||
auto msg = debug_str(file_str, " is not a regular file");
|
||||
LOG_ERROR("%s", msg.c_str());
|
||||
return Status::InvalidArgument(msg);
|
||||
}
|
||||
if (!file.open(file_path.c_str(), true, false)) {
|
||||
auto msg = debug_str("failed to open ", file_str);
|
||||
LOG_ERROR("%s", msg.c_str());
|
||||
return Status::InternalError(msg);
|
||||
}
|
||||
|
||||
// Deserialize and verify the meta header
|
||||
BitmapMetaHeader header;
|
||||
if (file.size() < sizeof(BitmapMetaHeader)) {
|
||||
auto msg =
|
||||
debug_str(file_str, " is too small to to contain a valid bitmap");
|
||||
LOG_ERROR("%s", msg.c_str());
|
||||
return Status::InternalError(msg);
|
||||
}
|
||||
if (file.read(&header, sizeof(header)) != sizeof(header)) {
|
||||
auto msg = debug_str("failed to read meta header from ", file_str);
|
||||
LOG_ERROR("%s", msg.c_str());
|
||||
return Status::InternalError(msg);
|
||||
}
|
||||
if (header.magic != roaring_magic_number) {
|
||||
auto msg = debug_str("magic number mismatch, ", file_str);
|
||||
LOG_ERROR("%s", msg.c_str());
|
||||
return Status::InternalError(msg);
|
||||
}
|
||||
if (header.is_32bit != 0 && header.is_32bit != 1) {
|
||||
auto msg = debug_str("bitmap type mismatch, ", file_str);
|
||||
LOG_ERROR("%s", msg.c_str());
|
||||
return Status::InternalError(msg);
|
||||
}
|
||||
is_32bit_ = header.is_32bit == 1 ? true : false;
|
||||
|
||||
// Read from file to buffer
|
||||
size_t bitmap_size = file.size() - sizeof(BitmapMetaHeader);
|
||||
std::vector<char> bitmap_buffer(bitmap_size);
|
||||
if (file.read(bitmap_buffer.data(), bitmap_size) != bitmap_size) {
|
||||
auto msg = debug_str("failed to read bitmap data from ", file_str);
|
||||
LOG_ERROR("%s", msg.c_str());
|
||||
return Status::InternalError(msg);
|
||||
}
|
||||
if (header.checksum !=
|
||||
ailego::Crc32c::Hash(bitmap_buffer.data(), bitmap_size)) {
|
||||
auto msg = debug_str("checksum mismatch, ", file_str);
|
||||
LOG_ERROR("%s", msg.c_str());
|
||||
return Status::InternalError(msg);
|
||||
}
|
||||
|
||||
// Deserialize from buffer
|
||||
try {
|
||||
if (is_32bit_) {
|
||||
bitmap32_ = std::make_unique<roaring::Roaring>(
|
||||
roaring::Roaring::readSafe(bitmap_buffer.data(), bitmap_size));
|
||||
} else {
|
||||
bitmap64_ = std::make_unique<roaring::Roaring64Map>(
|
||||
roaring::Roaring64Map::readSafe(bitmap_buffer.data(), bitmap_size));
|
||||
}
|
||||
} catch (...) {
|
||||
auto msg = debug_str("failed to deserialize bitmap from ", file_str);
|
||||
LOG_ERROR("%s", msg.c_str());
|
||||
return Status::InternalError(msg);
|
||||
}
|
||||
|
||||
LOG_DEBUG(
|
||||
"%s: deserialized bitmap from file[%s], checksum[%u], timestamp[%zu]",
|
||||
identifier_.c_str(), file_path.c_str(), header.checksum,
|
||||
(size_t)header.timestamp);
|
||||
return Status::OK();
|
||||
}
|
||||
|
||||
|
||||
} // namespace zvec
|
||||
@@ -0,0 +1,321 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
#pragma once
|
||||
|
||||
#include <mutex>
|
||||
#include <shared_mutex>
|
||||
#include <sstream>
|
||||
#include <roaring.hh>
|
||||
#include <roaring64map.hh>
|
||||
#include <ailego/io/file.h>
|
||||
#include <ailego/logger/logger.h>
|
||||
#include <roaring/roaring.h>
|
||||
#include "status.h"
|
||||
|
||||
|
||||
namespace zvec {
|
||||
|
||||
|
||||
/*
|
||||
* A thread-safe 32-bit Roaring bitmap implementation.
|
||||
*/
|
||||
class ConcurrentRoaringBitmap32 {
|
||||
public:
|
||||
using Ptr = std::shared_ptr<ConcurrentRoaringBitmap32>;
|
||||
|
||||
explicit ConcurrentRoaringBitmap32()
|
||||
: identifier_("Roaring bitmap[32-bit]"),
|
||||
bitmap_(roaring_bitmap_create()) {}
|
||||
|
||||
~ConcurrentRoaringBitmap32() {
|
||||
roaring_bitmap_free(bitmap_);
|
||||
}
|
||||
|
||||
ConcurrentRoaringBitmap32(const ConcurrentRoaringBitmap32 &) = delete;
|
||||
ConcurrentRoaringBitmap32 &operator=(const ConcurrentRoaringBitmap32 &) =
|
||||
delete;
|
||||
ConcurrentRoaringBitmap32 &operator=(ConcurrentRoaringBitmap32 &&) = delete;
|
||||
|
||||
|
||||
/***** Serialization and Deserialization - Start *****/
|
||||
public:
|
||||
Status serialize(std::string *out);
|
||||
|
||||
Status deserialize(const std::string &in);
|
||||
/***** Serialization and Deserialization - End *****/
|
||||
|
||||
|
||||
public:
|
||||
bool contains(uint32_t pos) const {
|
||||
std::shared_lock<std::shared_mutex> lock(mutex_);
|
||||
return roaring_bitmap_contains(bitmap_, pos);
|
||||
}
|
||||
|
||||
|
||||
size_t cardinality() const {
|
||||
std::shared_lock<std::shared_mutex> lock(mutex_);
|
||||
return roaring_bitmap_get_cardinality(bitmap_);
|
||||
}
|
||||
|
||||
|
||||
size_t range_cardinality(uint32_t min_doc_id, uint32_t max_doc_id) const {
|
||||
if (ailego_unlikely(min_doc_id > max_doc_id)) {
|
||||
LOG_WARN("%s: input range min_doc_id[%u] > max_doc_id[%u]",
|
||||
identifier_.c_str(), min_doc_id, max_doc_id);
|
||||
return 0;
|
||||
}
|
||||
std::shared_lock<std::shared_mutex> lock(mutex_);
|
||||
uint64_t max_rank{0}, min_rank{0};
|
||||
max_rank = roaring_bitmap_rank(bitmap_, max_doc_id);
|
||||
min_rank = roaring_bitmap_rank(bitmap_, min_doc_id - 1);
|
||||
return max_rank - min_rank;
|
||||
}
|
||||
|
||||
|
||||
void add(uint32_t pos) {
|
||||
std::unique_lock<std::shared_mutex> lock(mutex_);
|
||||
roaring_bitmap_add(bitmap_, pos);
|
||||
}
|
||||
|
||||
|
||||
void clear() {
|
||||
std::unique_lock<std::shared_mutex> lock(mutex_);
|
||||
roaring_bitmap_clear(bitmap_);
|
||||
}
|
||||
|
||||
|
||||
//! Remove all values in the closed interval [min, max]
|
||||
void remove_range_closed(uint32_t min, uint32_t max) {
|
||||
std::unique_lock<std::shared_mutex> lock(mutex_);
|
||||
roaring_bitmap_remove_range_closed(bitmap_, min, max);
|
||||
}
|
||||
|
||||
|
||||
size_t storage_size_in_bytes() const {
|
||||
std::unique_lock<std::shared_mutex> lock(mutex_);
|
||||
return roaring_bitmap_portable_size_in_bytes(bitmap_);
|
||||
}
|
||||
|
||||
|
||||
roaring_bitmap_t *bitmap() const {
|
||||
return bitmap_;
|
||||
}
|
||||
|
||||
|
||||
roaring_bitmap_t *copy() const {
|
||||
std::shared_lock<std::shared_mutex> lock(mutex_);
|
||||
return roaring_bitmap_copy(bitmap_);
|
||||
}
|
||||
|
||||
|
||||
private:
|
||||
std::string identifier_;
|
||||
roaring_bitmap_t *bitmap_{nullptr};
|
||||
mutable std::shared_mutex mutex_;
|
||||
};
|
||||
|
||||
|
||||
/*
|
||||
* A thread-safe Roaring bitmap implementation supporting both 32-bit and 64-bit
|
||||
* bitmaps with transparent conversion between them.
|
||||
*/
|
||||
class ConcurrentRoaringBitmap64 {
|
||||
public:
|
||||
using Ptr = std::shared_ptr<ConcurrentRoaringBitmap64>;
|
||||
|
||||
|
||||
explicit ConcurrentRoaringBitmap64()
|
||||
: is_32bit_(true),
|
||||
identifier_("Roaring bitmap[32-bit]"),
|
||||
bitmap32_(std::make_unique<roaring::Roaring>()) {}
|
||||
|
||||
explicit ConcurrentRoaringBitmap64(const std::string &name)
|
||||
: name_(name),
|
||||
is_32bit_(true),
|
||||
identifier_("Roaring bitmap[" + name_ + ", 32-bit]"),
|
||||
bitmap32_(std::make_unique<roaring::Roaring>()) {}
|
||||
|
||||
~ConcurrentRoaringBitmap64() = default;
|
||||
|
||||
ConcurrentRoaringBitmap64 &operator=(const ConcurrentRoaringBitmap64 &other) {
|
||||
if (this != &other) {
|
||||
std::unique_lock<std::shared_mutex> lock(mutex_, std::defer_lock);
|
||||
std::shared_lock<std::shared_mutex> other_lock(other.mutex_,
|
||||
std::defer_lock);
|
||||
std::lock(lock, other_lock);
|
||||
|
||||
name_ = other.name_;
|
||||
is_32bit_ = other.is_32bit_;
|
||||
identifier_ = other.identifier_;
|
||||
|
||||
if (other.is_32bit_) {
|
||||
bitmap32_ = std::make_unique<roaring::Roaring>(*other.bitmap32_);
|
||||
bitmap64_.reset();
|
||||
} else {
|
||||
bitmap64_ = std::make_unique<roaring::Roaring64Map>(*other.bitmap64_);
|
||||
bitmap32_.reset();
|
||||
}
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
/***** Serialization and Deserialization - Start *****/
|
||||
public:
|
||||
Status serialize(const std::string &file_path, bool overwrite);
|
||||
|
||||
Status deserialize(const std::string &file_path);
|
||||
|
||||
private:
|
||||
static const uint64_t roaring_magic_number{0x362DDA444AC1B99A};
|
||||
|
||||
struct BitmapMetaHeader {
|
||||
uint64_t magic;
|
||||
uint32_t is_32bit;
|
||||
uint32_t checksum;
|
||||
uint64_t timestamp;
|
||||
uint32_t reserved_[10];
|
||||
};
|
||||
/***** Serialization and Deserialization - End *****/
|
||||
|
||||
|
||||
public:
|
||||
bool contains(size_t pos) const {
|
||||
std::shared_lock<std::shared_mutex> lock(mutex_);
|
||||
if (is_32bit_) {
|
||||
return bitmap32_->contains(static_cast<uint32_t>(pos));
|
||||
} else {
|
||||
return bitmap64_->contains(static_cast<uint64_t>(pos));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
size_t cardinality() const {
|
||||
std::shared_lock<std::shared_mutex> lock(mutex_);
|
||||
if (is_32bit_) {
|
||||
return bitmap32_->cardinality();
|
||||
} else {
|
||||
return bitmap64_->cardinality();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
size_t range_cardinality(uint64_t min_doc_id, uint64_t max_doc_id) const {
|
||||
if (ailego_unlikely(min_doc_id > max_doc_id)) {
|
||||
LOG_WARN("%s: input range min_doc_id[%zu] > max_doc_id[%zu]",
|
||||
identifier_.c_str(), static_cast<size_t>(min_doc_id),
|
||||
static_cast<size_t>(max_doc_id));
|
||||
return 0;
|
||||
}
|
||||
std::shared_lock<std::shared_mutex> lock(mutex_);
|
||||
uint64_t max_rank{0}, min_rank{0};
|
||||
if (is_32bit_) {
|
||||
max_rank = bitmap32_->rank(max_doc_id);
|
||||
min_rank = min_doc_id <= 0 ? 0 : bitmap32_->rank(min_doc_id - 1);
|
||||
} else {
|
||||
max_rank = bitmap64_->rank(max_doc_id);
|
||||
min_rank = min_doc_id <= 0 ? 0 : bitmap64_->rank(min_doc_id - 1);
|
||||
}
|
||||
return max_rank - min_rank;
|
||||
}
|
||||
|
||||
|
||||
void add(size_t pos) {
|
||||
std::unique_lock<std::shared_mutex> lock(mutex_);
|
||||
if (ailego_unlikely(pos > std::numeric_limits<uint32_t>::max() &&
|
||||
is_32bit_)) {
|
||||
upgrade_from_32_to_64();
|
||||
}
|
||||
if (is_32bit_) {
|
||||
return bitmap32_->add(static_cast<uint32_t>(pos));
|
||||
} else {
|
||||
return bitmap64_->add(static_cast<uint64_t>(pos));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
void clear() {
|
||||
std::unique_lock<std::shared_mutex> lock(mutex_);
|
||||
bitmap32_.reset();
|
||||
bitmap64_.reset();
|
||||
if (is_32bit_) {
|
||||
bitmap32_ = std::make_unique<roaring::Roaring>();
|
||||
} else {
|
||||
bitmap64_ = std::make_unique<roaring::Roaring64Map>();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
//! Remove all values in the closed interval [min, max]
|
||||
void remove_range_closed(uint64_t min, uint64_t max) {
|
||||
std::unique_lock<std::shared_mutex> lock(mutex_);
|
||||
if (!is_32bit_) {
|
||||
return bitmap64_->removeRangeClosed(min, max);
|
||||
}
|
||||
if (min > std::numeric_limits<uint32_t>::max()) {
|
||||
return; // No valid values in the 32-bit range that can be removed
|
||||
}
|
||||
if (max > std::numeric_limits<uint32_t>::max()) {
|
||||
max = std::numeric_limits<uint32_t>::max();
|
||||
}
|
||||
bitmap32_->removeRangeClosed(min, max);
|
||||
}
|
||||
|
||||
|
||||
size_t storage_size_in_bytes() const {
|
||||
std::unique_lock<std::shared_mutex> lock(mutex_);
|
||||
if (is_32bit_) {
|
||||
return bitmap32_->getSizeInBytes() + sizeof(BitmapMetaHeader);
|
||||
} else {
|
||||
return bitmap64_->getSizeInBytes() + sizeof(BitmapMetaHeader);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private:
|
||||
using FILE = ailego::File;
|
||||
|
||||
|
||||
template <typename... Args>
|
||||
std::string debug_str(Args &&...args) {
|
||||
std::ostringstream oss;
|
||||
oss << identifier_ << ": ";
|
||||
(oss << ... << args);
|
||||
return oss.str();
|
||||
}
|
||||
|
||||
|
||||
void upgrade_from_32_to_64() {
|
||||
if (ailego_unlikely(!is_32bit_)) {
|
||||
LOG_WARN("%s: bitmap is already 64-bit", identifier_.c_str());
|
||||
return;
|
||||
}
|
||||
bitmap64_ = std::make_unique<roaring::Roaring64Map>(
|
||||
roaring::Roaring64Map{std::move(*bitmap32_)});
|
||||
is_32bit_ = false;
|
||||
bitmap32_.reset();
|
||||
identifier_ = "Roaring bitmap[" + name_ + ", 64-bit]";
|
||||
LOG_DEBUG("%s: upgraded to 64-bit", identifier_.c_str());
|
||||
}
|
||||
|
||||
|
||||
std::string name_;
|
||||
bool is_32bit_;
|
||||
std::string identifier_;
|
||||
std::unique_ptr<roaring::Roaring> bitmap32_{nullptr};
|
||||
std::unique_ptr<roaring::Roaring64Map> bitmap64_{nullptr};
|
||||
mutable std::shared_mutex mutex_;
|
||||
};
|
||||
|
||||
|
||||
} // namespace zvec
|
||||
@@ -0,0 +1,130 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#include "db/common/config.h"
|
||||
#include <iostream>
|
||||
#include <memory>
|
||||
#include "db/common/global_resource.h"
|
||||
#include "constants.h"
|
||||
#include "glogger.h"
|
||||
#include "logger.h"
|
||||
#include "status.h"
|
||||
#include "typedef.h"
|
||||
|
||||
namespace zvec {
|
||||
|
||||
static void ExitLogHandler() {
|
||||
LogUtil::Shutdown();
|
||||
}
|
||||
|
||||
Status GlobalConfig::Validate(const ConfigData &config) const {
|
||||
if (config.memory_limit_bytes < MIN_MEMORY_LIMIT_BYTES) {
|
||||
return Status::InvalidArgument("memory_limit_bytes must be greater than ",
|
||||
MIN_MEMORY_LIMIT_BYTES);
|
||||
}
|
||||
|
||||
if (config.memory_limit_bytes > CgroupUtil::getMemoryLimit()) {
|
||||
return Status::InvalidArgument("memory_limit_bytes must be less than ",
|
||||
CgroupUtil::getMemoryLimit());
|
||||
}
|
||||
|
||||
// Validate query thread count
|
||||
if (config.query_thread_count == 0) {
|
||||
return Status::InvalidArgument("query_thread_count must be greater than 0");
|
||||
}
|
||||
|
||||
// Validate invert_to_forward_scan_ratio (should be between 0 and 1)
|
||||
if (config.invert_to_forward_scan_ratio < 0.0f ||
|
||||
config.invert_to_forward_scan_ratio > 1.0f) {
|
||||
return Status::InvalidArgument(
|
||||
"invert_to_forward_scan_ratio must be between 0 and 1");
|
||||
}
|
||||
|
||||
// Validate brute_force_by_keys_ratio (should be between 0 and 1)
|
||||
if (config.brute_force_by_keys_ratio < 0.0f ||
|
||||
config.brute_force_by_keys_ratio > 1.0f) {
|
||||
return Status::InvalidArgument(
|
||||
"brute_force_by_keys_ratio must be between 0 and 1");
|
||||
}
|
||||
|
||||
// Validate optimize thread count
|
||||
if (config.optimize_thread_count == 0) {
|
||||
return Status::InvalidArgument(
|
||||
"optimize_thread_count must be greater than 0");
|
||||
}
|
||||
|
||||
// Validate log configuration
|
||||
if (config.log_config->GetLoggerType() == FILE_LOG_TYPE_NAME) {
|
||||
auto log_config =
|
||||
std::dynamic_pointer_cast<FileLogConfig>(config.log_config);
|
||||
|
||||
// Validate file log specific configurations
|
||||
if (log_config->dir.empty()) {
|
||||
return Status::InvalidArgument(
|
||||
"log_dir cannot be empty when set to FileLogger");
|
||||
}
|
||||
|
||||
if (log_config->basename.empty()) {
|
||||
return Status::InvalidArgument(
|
||||
"log_file basename cannot be empty when set to FileLogger");
|
||||
}
|
||||
|
||||
if (log_config->file_size <= MIN_LOG_FILE_SIZE) {
|
||||
return Status::InvalidArgument("log file_size must be greater than ",
|
||||
MIN_LOG_FILE_SIZE,
|
||||
" when set to FileLogger");
|
||||
}
|
||||
|
||||
if (log_config->overdue_days == 0) {
|
||||
return Status::InvalidArgument(
|
||||
"log_overdue_days must be greater than 0 when set to FileLogger");
|
||||
}
|
||||
}
|
||||
|
||||
return Status::OK();
|
||||
}
|
||||
|
||||
Status GlobalConfig::Initialize(const ConfigData &config) {
|
||||
// Use atomic compare-exchange to ensure only one initialization
|
||||
bool expected = false;
|
||||
if (!initialized_.compare_exchange_strong(expected, true)) {
|
||||
// Already initialized
|
||||
return Status::InvalidArgument("GlobalConfig is already initialized");
|
||||
}
|
||||
|
||||
auto s = Validate(config);
|
||||
CHECK_RETURN_STATUS(s);
|
||||
|
||||
config_ = config;
|
||||
|
||||
s = LogUtil::Init(log_dir(), log_file_basename(), int(log_level()),
|
||||
log_type(), log_file_size(), log_overdue_days());
|
||||
CHECK_RETURN_STATUS(s);
|
||||
|
||||
if (std::atexit(ExitLogHandler) != 0) {
|
||||
std::cerr << "Failed to register exit handler" << std::endl;
|
||||
return Status::InternalError("Failed to register exit handler");
|
||||
}
|
||||
|
||||
GlobalResource::Instance().initialize();
|
||||
return Status::OK();
|
||||
}
|
||||
|
||||
uint64_t GlobalConfig::memory_limit_bytes() const noexcept {
|
||||
return config_.memory_limit_bytes;
|
||||
}
|
||||
|
||||
FACTORY_REGISTER_LOGGER(AppendLogger);
|
||||
|
||||
} // namespace zvec
|
||||
@@ -0,0 +1,172 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
#pragma once
|
||||
|
||||
#include <atomic>
|
||||
#include <cstdint>
|
||||
#include <memory>
|
||||
#include <ailego/logger/logger.h>
|
||||
#include <ailego/pattern/singleton.h>
|
||||
#include "cgroup_util.h"
|
||||
#include "constants.h"
|
||||
#include "status.h"
|
||||
|
||||
namespace zvec {
|
||||
|
||||
class GlobalConfig : public ailego::Singleton<GlobalConfig> {
|
||||
friend class ailego::Singleton<GlobalConfig>;
|
||||
|
||||
public:
|
||||
enum class LogLevel : uint8_t {
|
||||
DEBUG = 0,
|
||||
INFO,
|
||||
WARN,
|
||||
ERROR,
|
||||
FATAL,
|
||||
};
|
||||
|
||||
struct LogConfig {
|
||||
LogLevel level;
|
||||
|
||||
LogConfig(LogLevel level) : level(level) {}
|
||||
virtual ~LogConfig() = default;
|
||||
virtual std::string GetLoggerType() const = 0;
|
||||
};
|
||||
|
||||
// Console log configuration
|
||||
struct ConsoleLogConfig : LogConfig {
|
||||
ConsoleLogConfig(LogLevel level = LogLevel::WARN) : LogConfig{level} {}
|
||||
|
||||
std::string GetLoggerType() const override {
|
||||
return CONSOLE_LOG_TYPE_NAME;
|
||||
}
|
||||
};
|
||||
|
||||
// File log configuration
|
||||
struct FileLogConfig : LogConfig {
|
||||
std::string dir;
|
||||
std::string basename;
|
||||
uint32_t file_size; // MB
|
||||
uint32_t overdue_days;
|
||||
|
||||
FileLogConfig(LogLevel level = LogLevel::WARN,
|
||||
std::string dir = DEFAULT_LOG_DIR,
|
||||
std::string basename = DEFAULT_LOG_BASENAME,
|
||||
uint32_t file_size = DEFAULT_LOG_FILE_SIZE,
|
||||
uint32_t overdue_days = DEFAULT_LOG_OVERDUE_DAYS)
|
||||
: LogConfig{level},
|
||||
dir{dir},
|
||||
basename{basename},
|
||||
file_size{file_size},
|
||||
overdue_days(overdue_days) {}
|
||||
|
||||
std::string GetLoggerType() const override {
|
||||
return FILE_LOG_TYPE_NAME;
|
||||
}
|
||||
};
|
||||
|
||||
// Configuration data structure
|
||||
struct ConfigData {
|
||||
uint64_t memory_limit_bytes =
|
||||
CgroupUtil::getMemoryLimit() * DEFAULT_MEMORY_LIMIT_RATIO;
|
||||
|
||||
// log
|
||||
std::shared_ptr<LogConfig> log_config =
|
||||
std::make_shared<ConsoleLogConfig>();
|
||||
|
||||
// query
|
||||
uint32_t query_thread_count = CgroupUtil::getCpuLimit();
|
||||
float invert_to_forward_scan_ratio = 0.9;
|
||||
float brute_force_by_keys_ratio = 0.1;
|
||||
|
||||
// optimize
|
||||
uint32_t optimize_thread_count = CgroupUtil::getCpuLimit();
|
||||
};
|
||||
|
||||
// Initialize the configuration (can only be called once)
|
||||
Status Initialize(const ConfigData &config);
|
||||
|
||||
Status Validate(const ConfigData &config) const;
|
||||
|
||||
// Read-only accessors
|
||||
uint64_t memory_limit_bytes() const noexcept;
|
||||
|
||||
const LogConfig &log_config() const noexcept {
|
||||
return *config_.log_config;
|
||||
}
|
||||
|
||||
std::string log_type() const noexcept {
|
||||
return config_.log_config->GetLoggerType();
|
||||
}
|
||||
|
||||
LogLevel log_level() const noexcept {
|
||||
return config_.log_config->level;
|
||||
}
|
||||
|
||||
// File log specific accessors (only valid when using FileLogConfig)
|
||||
const std::string &log_dir() const noexcept {
|
||||
const FileLogConfig *file_config =
|
||||
dynamic_cast<const FileLogConfig *>(config_.log_config.get());
|
||||
static const std::string empty_string = "";
|
||||
return file_config ? file_config->dir : empty_string;
|
||||
}
|
||||
|
||||
const std::string &log_file_basename() const noexcept {
|
||||
const FileLogConfig *file_config =
|
||||
dynamic_cast<const FileLogConfig *>(config_.log_config.get());
|
||||
static const std::string empty_string = "";
|
||||
return file_config ? file_config->basename : empty_string;
|
||||
}
|
||||
|
||||
uint32_t log_file_size() const noexcept {
|
||||
const FileLogConfig *file_config =
|
||||
dynamic_cast<const FileLogConfig *>(config_.log_config.get());
|
||||
return file_config ? file_config->file_size : 0;
|
||||
}
|
||||
|
||||
uint32_t log_overdue_days() const noexcept {
|
||||
const FileLogConfig *file_config =
|
||||
dynamic_cast<const FileLogConfig *>(config_.log_config.get());
|
||||
return file_config ? file_config->overdue_days : 0;
|
||||
}
|
||||
|
||||
//! Query thread count
|
||||
uint32_t query_thread_count() const noexcept {
|
||||
return config_.query_thread_count;
|
||||
}
|
||||
|
||||
//! Invert to forward scan ratio
|
||||
float invert_to_forward_scan_ratio() const noexcept {
|
||||
return config_.invert_to_forward_scan_ratio;
|
||||
}
|
||||
|
||||
//! Brute force by keys ratio
|
||||
float brute_force_by_keys_ratio() const noexcept {
|
||||
return config_.brute_force_by_keys_ratio;
|
||||
}
|
||||
|
||||
//! Optimize thread count
|
||||
uint32_t optimize_thread_count() const noexcept {
|
||||
return config_.optimize_thread_count;
|
||||
}
|
||||
|
||||
private:
|
||||
// Configuration data
|
||||
ConfigData config_;
|
||||
|
||||
// Atomic flag to ensure initialization happens only once
|
||||
std::atomic<bool> initialized_{false};
|
||||
};
|
||||
|
||||
} // namespace zvec
|
||||
@@ -0,0 +1,105 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
#include <regex>
|
||||
#include <string>
|
||||
|
||||
namespace zvec {
|
||||
|
||||
// global config
|
||||
const float DEFAULT_MEMORY_LIMIT_RATIO = 0.8f;
|
||||
|
||||
const uint32_t MIN_MEMORY_LIMIT_BYTES = 100 * 1024 * 1024;
|
||||
|
||||
const uint32_t MIN_LOG_FILE_SIZE = 128;
|
||||
|
||||
const uint32_t DEFAULT_LOG_FILE_SIZE = 2048;
|
||||
|
||||
const uint32_t DEFAULT_LOG_OVERDUE_DAYS = 7;
|
||||
|
||||
const std::string CONSOLE_LOG_TYPE_NAME = "ConsoleLogger";
|
||||
|
||||
const std::string FILE_LOG_TYPE_NAME = "AppendLogger";
|
||||
|
||||
const std::string DEFAULT_LOG_DIR = "./logs";
|
||||
|
||||
const std::string DEFAULT_LOG_BASENAME = "zvec.log";
|
||||
|
||||
const uint64_t INVALID_DOC_ID = -1UL;
|
||||
|
||||
const std::string LOCAL_ROW_ID = "_zvec_row_id_";
|
||||
|
||||
const std::string GLOBAL_DOC_ID = "_zvec_g_doc_id_";
|
||||
|
||||
const std::string USER_ID = "_zvec_uid_";
|
||||
|
||||
const int kSparseMaxDimSize = 4096;
|
||||
|
||||
const int64_t kMaxRecordBatchNumRows = 4096;
|
||||
|
||||
constexpr uint32_t MAX_ARRAY_FIELD_LEN = 32;
|
||||
|
||||
const uint64_t MAX_DOC_COUNT_PER_SEGMENT = 10000000;
|
||||
|
||||
const uint64_t MAX_DOC_COUNT_PER_SEGMENT_MIN_THRESHOLD = 1000;
|
||||
|
||||
const float COMPACT_DELETE_RATIO_THRESHOLD = 0.3f;
|
||||
|
||||
const std::regex COLLECTION_NAME_REGEX("^[a-zA-Z0-9_-]{3,64}$");
|
||||
|
||||
const std::regex FIELD_NAME_REGEX("^[a-zA-Z0-9_-]{1,32}$");
|
||||
|
||||
const std::regex DOC_PK_REGEX("^[a-zA-Z0-9_!@#$%+=.-]{1,64}$");
|
||||
|
||||
const std::regex COLLECTION_PATH_REGEX(
|
||||
R"(^/?(?:[a-zA-Z0-9_.\-]+/)*[a-zA-Z0-9_.\-]+$)");
|
||||
|
||||
constexpr uint32_t kMaxDenseDimSize = 20000;
|
||||
|
||||
constexpr uint32_t kMaxScalarFieldSize = 1024;
|
||||
|
||||
constexpr uint32_t kMaxVectorFieldSize = 5;
|
||||
|
||||
constexpr uint32_t kMaxQueryTopk = 1024;
|
||||
|
||||
constexpr uint32_t kMaxOutputFieldSize = 1024;
|
||||
|
||||
constexpr uint32_t kMaxWriteBatchSize = 1024;
|
||||
|
||||
// Inverted index
|
||||
const std::string INVERT_SUFFIX_TERMS{"$TERMS"};
|
||||
|
||||
const std::string INVERT_SUFFIX_REVERSED_TERMS{"$SMRET"};
|
||||
|
||||
const std::string INVERT_SUFFIX_ARRAY_LEN{"$ARRAY_LEN"};
|
||||
|
||||
const std::string INVERT_SUFFIX_RANGES{"$RANGES"};
|
||||
|
||||
const std::string INVERT_CDF{"$CDF"};
|
||||
|
||||
const std::string INVERT_KEY_MAX_ID{"$ZVEC$MAX_ID"};
|
||||
|
||||
const std::string INVERT_KEY_NULL{"$ZVEC$NULL"};
|
||||
|
||||
const std::string INVERT_KEY_SEALED{"$ZVEC$SEALED"};
|
||||
|
||||
const uint32_t INVERT_ID_LIST_SIZE_THRESHOLD = 3;
|
||||
|
||||
// Segment Options
|
||||
const uint32_t DEFAULT_MAX_BUFFER_SIZE = 64 * 1024 * 1024; // 128M
|
||||
|
||||
|
||||
} // namespace zvec
|
||||
@@ -0,0 +1,155 @@
|
||||
// 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 "error_code.h"
|
||||
|
||||
namespace zvec {
|
||||
|
||||
// 0~999 [Builtin]
|
||||
PROXIMA_ZVEC_ERROR_CODE_DEFINE(Success, 0, "Success");
|
||||
|
||||
// 1000~1999 [Common Error]
|
||||
PROXIMA_ZVEC_ERROR_CODE_DEFINE(RuntimeError, 1000, "Runtime Error");
|
||||
PROXIMA_ZVEC_ERROR_CODE_DEFINE(LogicError, 1001, "Logic Error");
|
||||
PROXIMA_ZVEC_ERROR_CODE_DEFINE(StatusError, 1002, "Status Error");
|
||||
PROXIMA_ZVEC_ERROR_CODE_DEFINE(LoadConfig, 1003, "Load Config Error");
|
||||
PROXIMA_ZVEC_ERROR_CODE_DEFINE(ConfigError, 1004, "Config Error");
|
||||
PROXIMA_ZVEC_ERROR_CODE_DEFINE(InvalidArgument, 1005, "Invalid Argument");
|
||||
PROXIMA_ZVEC_ERROR_CODE_DEFINE(NotInitialized, 1006, "Not Initialized");
|
||||
PROXIMA_ZVEC_ERROR_CODE_DEFINE(OpenFile, 1007, "Open File Error");
|
||||
PROXIMA_ZVEC_ERROR_CODE_DEFINE(ReadData, 1008, "Read Data Error");
|
||||
PROXIMA_ZVEC_ERROR_CODE_DEFINE(WriteData, 1009, "Write Data Error");
|
||||
PROXIMA_ZVEC_ERROR_CODE_DEFINE(ExceedLimit, 1010, "Exceed Limit");
|
||||
PROXIMA_ZVEC_ERROR_CODE_DEFINE(SerializeError, 1011, "Serialize Error");
|
||||
PROXIMA_ZVEC_ERROR_CODE_DEFINE(DeserializeError, 1012, "Deserialize Error");
|
||||
PROXIMA_ZVEC_ERROR_CODE_DEFINE(StartServer, 1013, "Start Server Error");
|
||||
PROXIMA_ZVEC_ERROR_CODE_DEFINE(StoppedService, 1014, "Visit Stopped Service");
|
||||
PROXIMA_ZVEC_ERROR_CODE_DEFINE(FileSystem, 1015, "File System Error");
|
||||
PROXIMA_ZVEC_ERROR_CODE_DEFINE(RpcError, 1016, "RPC Error");
|
||||
PROXIMA_ZVEC_ERROR_CODE_DEFINE(InitChannelError, 1017,
|
||||
"Init brpc channel Error");
|
||||
PROXIMA_ZVEC_ERROR_CODE_DEFINE(AddSubChannelError, 1018,
|
||||
"Add sub channel Error");
|
||||
PROXIMA_ZVEC_ERROR_CODE_DEFINE(NoNeedProcess, 1019, "No need process");
|
||||
PROXIMA_ZVEC_ERROR_CODE_DEFINE(EtcdError, 1020, "Etcd Error");
|
||||
PROXIMA_ZVEC_ERROR_CODE_DEFINE(MessageQueueError, 1021, "Message Queue Error");
|
||||
PROXIMA_ZVEC_ERROR_CODE_DEFINE(KafkaSubTopicExistErr, 1022,
|
||||
"Kafka topic subscribe already exist Error");
|
||||
PROXIMA_ZVEC_ERROR_CODE_DEFINE(KafkaUnSubTopicNotExistErr, 1023,
|
||||
"Kafka topic unsubscribe not exist Error");
|
||||
PROXIMA_ZVEC_ERROR_CODE_DEFINE(InitKafkaError, 1024, "Init kafka error");
|
||||
PROXIMA_ZVEC_ERROR_CODE_DEFINE(KafkaPublishError, 1025, "Kafka publish error");
|
||||
PROXIMA_ZVEC_ERROR_CODE_DEFINE(ExceedKafkaMessageSizeLimit, 1026,
|
||||
"Exceed kafka message size limit");
|
||||
PROXIMA_ZVEC_ERROR_CODE_DEFINE(NotImplemented, 1027,
|
||||
"The function is not implemented");
|
||||
PROXIMA_ZVEC_ERROR_CODE_DEFINE(Timeout, 1028, "Timeout");
|
||||
PROXIMA_ZVEC_ERROR_CODE_DEFINE(MasterNoLeader, 1029, "Master no leader");
|
||||
PROXIMA_ZVEC_ERROR_CODE_DEFINE(NeedRetry, 1030, "Need retry");
|
||||
PROXIMA_ZVEC_ERROR_CODE_DEFINE(Abort, 1031, "Abort");
|
||||
|
||||
PROXIMA_ZVEC_ERROR_CODE_DEFINE(EmptyCollectionName, 2000,
|
||||
"Empty Collection Name");
|
||||
PROXIMA_ZVEC_ERROR_CODE_DEFINE(EmptyColumnName, 2001, "Empty Column Name");
|
||||
PROXIMA_ZVEC_ERROR_CODE_DEFINE(EmptyPartitionName, 2002,
|
||||
"Empty collection partition name");
|
||||
PROXIMA_ZVEC_ERROR_CODE_DEFINE(EmptyColumns, 2003, "Empty Columns");
|
||||
PROXIMA_ZVEC_ERROR_CODE_DEFINE(EmptyPrimaryKey, 2004, "Empty primary key");
|
||||
PROXIMA_ZVEC_ERROR_CODE_DEFINE(EmptyDocList, 2005, "Empty doc list");
|
||||
PROXIMA_ZVEC_ERROR_CODE_DEFINE(EmptyDocFields, 2006, "Empty doc fields");
|
||||
PROXIMA_ZVEC_ERROR_CODE_DEFINE(EmptyIndexField, 2007, "Empty index field");
|
||||
PROXIMA_ZVEC_ERROR_CODE_DEFINE(InvalidRecord, 2008, "Invalid Record");
|
||||
PROXIMA_ZVEC_ERROR_CODE_DEFINE(InvalidQuery, 2009, "Invalid Query");
|
||||
PROXIMA_ZVEC_ERROR_CODE_DEFINE(InvalidWriteRequest, 2010,
|
||||
"Invalid Write Request");
|
||||
PROXIMA_ZVEC_ERROR_CODE_DEFINE(InvalidVectorFormat, 2011,
|
||||
"Invalid Vector Format");
|
||||
PROXIMA_ZVEC_ERROR_CODE_DEFINE(InvalidDataType, 2012, "Invalid Data Type");
|
||||
PROXIMA_ZVEC_ERROR_CODE_DEFINE(InvalidIndexType, 2013, "Invalid Index Type");
|
||||
PROXIMA_ZVEC_ERROR_CODE_DEFINE(InvalidFeature, 2014, "Invalid Feature");
|
||||
PROXIMA_ZVEC_ERROR_CODE_DEFINE(InvalidFilter, 2015, "Invalid Filter");
|
||||
PROXIMA_ZVEC_ERROR_CODE_DEFINE(InvalidPrimaryKey, 2016, "Invalid primary key");
|
||||
PROXIMA_ZVEC_ERROR_CODE_DEFINE(InvalidField, 2017, "Invalid field");
|
||||
PROXIMA_ZVEC_ERROR_CODE_DEFINE(MismatchedIndexColumn, 2018,
|
||||
"Mismatched Index Column");
|
||||
PROXIMA_ZVEC_ERROR_CODE_DEFINE(MismatchedDimension, 2019,
|
||||
"Mismatched Dimension");
|
||||
PROXIMA_ZVEC_ERROR_CODE_DEFINE(MismatchedDataType, 2020,
|
||||
"Mismatched Data Type");
|
||||
PROXIMA_ZVEC_ERROR_CODE_DEFINE(InexistentCollection, 2021,
|
||||
"Collection Not Exist");
|
||||
PROXIMA_ZVEC_ERROR_CODE_DEFINE(InexistentPartition, 2022,
|
||||
"Inexistent collection partition");
|
||||
PROXIMA_ZVEC_ERROR_CODE_DEFINE(InexistentColumn, 2023, "Column Not Exist");
|
||||
PROXIMA_ZVEC_ERROR_CODE_DEFINE(InexistentKey, 2024, "Key Not Exist");
|
||||
PROXIMA_ZVEC_ERROR_CODE_DEFINE(DuplicateCollection, 2025,
|
||||
"Duplicate Collection");
|
||||
PROXIMA_ZVEC_ERROR_CODE_DEFINE(DuplicatePartition, 2026,
|
||||
"Duplicate collection partition");
|
||||
PROXIMA_ZVEC_ERROR_CODE_DEFINE(DuplicateKey, 2027, "Duplicate Key");
|
||||
PROXIMA_ZVEC_ERROR_CODE_DEFINE(DuplicateField, 2028, "Duplicate field");
|
||||
PROXIMA_ZVEC_ERROR_CODE_DEFINE(UnreadyPartition, 2029,
|
||||
"Status of collection partition is incorrect");
|
||||
PROXIMA_ZVEC_ERROR_CODE_DEFINE(UnreadyCollection, 2030,
|
||||
"Status of collection is incorrect");
|
||||
PROXIMA_ZVEC_ERROR_CODE_DEFINE(UnsupportedCondition, 2031,
|
||||
"Query condition has error or not supported");
|
||||
PROXIMA_ZVEC_ERROR_CODE_DEFINE(
|
||||
OrderbyNotInSelectItems, 2032,
|
||||
"Order by column must exists in select item list");
|
||||
PROXIMA_ZVEC_ERROR_CODE_DEFINE(PbToSqlInfoError, 2033, "Pb to sql info error");
|
||||
PROXIMA_ZVEC_ERROR_CODE_DEFINE(ExceedRateLimit, 2034, "Exceed Rate Limit");
|
||||
PROXIMA_ZVEC_ERROR_CODE_DEFINE(InvalidSparseValues, 2035,
|
||||
"Invalid Sparse Values");
|
||||
PROXIMA_ZVEC_ERROR_CODE_DEFINE(InvalidBatchSize, 2036, "Invalid batch size");
|
||||
PROXIMA_ZVEC_ERROR_CODE_DEFINE(InvalidDimension, 2037, "Invalid dimension");
|
||||
PROXIMA_ZVEC_ERROR_CODE_DEFINE(InvalidExtraParam, 2038, "Invalid extra param");
|
||||
PROXIMA_ZVEC_ERROR_CODE_DEFINE(InvalidRadius, 2039, "Invalid radius");
|
||||
PROXIMA_ZVEC_ERROR_CODE_DEFINE(InvalidLinear, 2040, "Invalid is linear");
|
||||
PROXIMA_ZVEC_ERROR_CODE_DEFINE(InvalidTopk, 2041, "Invalid topk");
|
||||
PROXIMA_ZVEC_ERROR_CODE_DEFINE(InvalidCollectionName, 2042,
|
||||
"Invalid collection name");
|
||||
PROXIMA_ZVEC_ERROR_CODE_DEFINE(InvalidPartitionName, 2043,
|
||||
"Invalid partition name");
|
||||
PROXIMA_ZVEC_ERROR_CODE_DEFINE(InvalidFieldName, 2044, "Invalid field name");
|
||||
PROXIMA_ZVEC_ERROR_CODE_DEFINE(InvalidChannelCount, 2045, "Invalid field name");
|
||||
PROXIMA_ZVEC_ERROR_CODE_DEFINE(InvalidReplicaCount, 2046, "Invalid field name");
|
||||
PROXIMA_ZVEC_ERROR_CODE_DEFINE(InvalidJson, 2047, "Invalid json");
|
||||
// used by master
|
||||
PROXIMA_ZVEC_ERROR_CODE_DEFINE(InvalidClusterConfig, 2048,
|
||||
"Invalid cluster config");
|
||||
PROXIMA_ZVEC_ERROR_CODE_DEFINE(DuplicateCluster, 2049, "Duplicate Cluster");
|
||||
PROXIMA_ZVEC_ERROR_CODE_DEFINE(InexistentCluster, 2050, "Inexistent Cluster");
|
||||
PROXIMA_ZVEC_ERROR_CODE_DEFINE(InvalidClusterStatus, 2051,
|
||||
"Invalid Cluster Status");
|
||||
PROXIMA_ZVEC_ERROR_CODE_DEFINE(RpcTimedout, 2052, "Rpc Timedout");
|
||||
PROXIMA_ZVEC_ERROR_CODE_DEFINE(InvalidGroupBy, 2053, "Invalid GroupBy Request");
|
||||
PROXIMA_ZVEC_ERROR_CODE_DEFINE(EmptyVectorField, 2054, "Empty vector field");
|
||||
PROXIMA_ZVEC_ERROR_CODE_DEFINE(VectorNotAllowed, 2055, "Vector not allowed");
|
||||
PROXIMA_ZVEC_ERROR_CODE_DEFINE(InvalidReferenceCollection, 2056,
|
||||
"Invalid reference collection");
|
||||
PROXIMA_ZVEC_ERROR_CODE_DEFINE(InvalidOrderBy, 2057, "Invalid OrderBy field");
|
||||
|
||||
|
||||
PROXIMA_ZVEC_ERROR_CODE_DEFINE(UnreadyQueue, 5002,
|
||||
"Compute Queue Is Unready Yet");
|
||||
PROXIMA_ZVEC_ERROR_CODE_DEFINE(ScheduleError, 5003, "Schedule Task Error");
|
||||
PROXIMA_ZVEC_ERROR_CODE_DEFINE(TaskIsRunning, 5004,
|
||||
"Task is running in other coroutine");
|
||||
|
||||
const char *ErrorCode::What(int val) {
|
||||
return ErrorCode::Instance()->what(val);
|
||||
}
|
||||
|
||||
} // namespace zvec
|
||||
@@ -0,0 +1,212 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
#pragma once
|
||||
|
||||
#include <map>
|
||||
#include <ailego/pattern/expected.hpp>
|
||||
namespace zvec {
|
||||
|
||||
/*! Error
|
||||
*/
|
||||
|
||||
class ErrorCode;
|
||||
|
||||
class ErrorCode {
|
||||
public:
|
||||
/*! Error Code
|
||||
*/
|
||||
class Code {
|
||||
public:
|
||||
//! Constructor
|
||||
Code(int val, const char *str) : value_(-val), desc_(str) {
|
||||
ErrorCode::Instance()->emplace(this);
|
||||
}
|
||||
|
||||
//! Retrieve the value of code
|
||||
operator int() const {
|
||||
return (this->value_);
|
||||
}
|
||||
|
||||
//! Retrieve the value of code
|
||||
int value() const {
|
||||
return (this->value_);
|
||||
}
|
||||
|
||||
//! Retrieve the description of code
|
||||
const char *desc() const {
|
||||
return (this->desc_);
|
||||
}
|
||||
|
||||
private:
|
||||
int value_;
|
||||
const char *desc_;
|
||||
};
|
||||
|
||||
//! Retrieve the description of code
|
||||
static const char *What(int val);
|
||||
|
||||
protected:
|
||||
//! Constructor
|
||||
ErrorCode(void) : map_() {}
|
||||
|
||||
//! Inserts a new code into map
|
||||
void emplace(const ErrorCode::Code *code) {
|
||||
map_.emplace(code->value(), code);
|
||||
}
|
||||
|
||||
//! Retrieve the description of code
|
||||
const char *what(int val) const {
|
||||
auto iter = map_.find(val);
|
||||
if (iter != map_.end()) {
|
||||
return iter->second->desc();
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
//! Retrieve the singleton
|
||||
static ErrorCode *Instance(void) {
|
||||
static ErrorCode error;
|
||||
return (&error);
|
||||
}
|
||||
|
||||
private:
|
||||
//! Disable them
|
||||
ErrorCode(const ErrorCode &) = delete;
|
||||
ErrorCode(ErrorCode &&) = delete;
|
||||
ErrorCode &operator=(const ErrorCode &) = delete;
|
||||
|
||||
//! Error code map
|
||||
std::map<int, const ErrorCode::Code *> map_;
|
||||
};
|
||||
|
||||
//! Error Code Define
|
||||
#define PROXIMA_ZVEC_ERROR_CODE_DEFINE(__NAME__, __VAL__, __DESC__) \
|
||||
const zvec::ErrorCode::Code ErrorCode_##__NAME__((__VAL__), (__DESC__)); \
|
||||
const zvec::ErrorCode::Code &_ErrorCode_##__VAL__##_Register( \
|
||||
ErrorCode_##__NAME__)
|
||||
|
||||
//! Proxima SE Error Code Declare
|
||||
#define PROXIMA_ZVEC_ERROR_CODE_DECLARE(__NAME__) \
|
||||
extern const zvec::ErrorCode::Code ErrorCode_##__NAME__
|
||||
|
||||
//! Error code helper
|
||||
#define PROXIMA_ZVEC_ERROR_CODE(__NAME__) zvec::ErrorCode_##__NAME__
|
||||
|
||||
// 0~999 [Builtin]
|
||||
PROXIMA_ZVEC_ERROR_CODE_DECLARE(Success);
|
||||
|
||||
// 1000~1999 [Common Error]
|
||||
PROXIMA_ZVEC_ERROR_CODE_DECLARE(RuntimeError);
|
||||
PROXIMA_ZVEC_ERROR_CODE_DECLARE(LogicError);
|
||||
PROXIMA_ZVEC_ERROR_CODE_DECLARE(StatusError);
|
||||
PROXIMA_ZVEC_ERROR_CODE_DECLARE(LoadConfig);
|
||||
PROXIMA_ZVEC_ERROR_CODE_DECLARE(ConfigError);
|
||||
PROXIMA_ZVEC_ERROR_CODE_DECLARE(InvalidArgument);
|
||||
PROXIMA_ZVEC_ERROR_CODE_DECLARE(NotInitialized);
|
||||
PROXIMA_ZVEC_ERROR_CODE_DECLARE(OpenFile);
|
||||
PROXIMA_ZVEC_ERROR_CODE_DECLARE(ReadData);
|
||||
PROXIMA_ZVEC_ERROR_CODE_DECLARE(WriteData);
|
||||
PROXIMA_ZVEC_ERROR_CODE_DECLARE(ExceedLimit);
|
||||
PROXIMA_ZVEC_ERROR_CODE_DECLARE(SerializeError);
|
||||
PROXIMA_ZVEC_ERROR_CODE_DECLARE(DeserializeError);
|
||||
PROXIMA_ZVEC_ERROR_CODE_DECLARE(StartServer);
|
||||
PROXIMA_ZVEC_ERROR_CODE_DECLARE(StoppedService);
|
||||
PROXIMA_ZVEC_ERROR_CODE_DECLARE(FileSystem);
|
||||
PROXIMA_ZVEC_ERROR_CODE_DECLARE(RpcError);
|
||||
PROXIMA_ZVEC_ERROR_CODE_DECLARE(InitChannelError);
|
||||
PROXIMA_ZVEC_ERROR_CODE_DECLARE(AddSubChannelError);
|
||||
PROXIMA_ZVEC_ERROR_CODE_DECLARE(NoNeedProcess);
|
||||
PROXIMA_ZVEC_ERROR_CODE_DECLARE(EtcdError);
|
||||
PROXIMA_ZVEC_ERROR_CODE_DECLARE(MessageQueueError);
|
||||
PROXIMA_ZVEC_ERROR_CODE_DECLARE(KafkaSubTopicExistErr);
|
||||
PROXIMA_ZVEC_ERROR_CODE_DECLARE(KafkaUnSubTopicNotExistErr);
|
||||
PROXIMA_ZVEC_ERROR_CODE_DECLARE(InitKafkaError);
|
||||
PROXIMA_ZVEC_ERROR_CODE_DECLARE(KafkaPublishError);
|
||||
PROXIMA_ZVEC_ERROR_CODE_DECLARE(ExceedKafkaMessageSizeLimit);
|
||||
PROXIMA_ZVEC_ERROR_CODE_DECLARE(NotImplemented);
|
||||
PROXIMA_ZVEC_ERROR_CODE_DECLARE(Timeout);
|
||||
PROXIMA_ZVEC_ERROR_CODE_DECLARE(MasterNoLeader);
|
||||
PROXIMA_ZVEC_ERROR_CODE_DECLARE(NeedRetry);
|
||||
PROXIMA_ZVEC_ERROR_CODE_DECLARE(Abort);
|
||||
|
||||
PROXIMA_ZVEC_ERROR_CODE_DECLARE(UnreadyQueue);
|
||||
PROXIMA_ZVEC_ERROR_CODE_DECLARE(ScheduleError);
|
||||
PROXIMA_ZVEC_ERROR_CODE_DECLARE(TaskIsRunning);
|
||||
|
||||
PROXIMA_ZVEC_ERROR_CODE_DECLARE(DirectoryAlreadyExists);
|
||||
PROXIMA_ZVEC_ERROR_CODE_DECLARE(DirectoryNotExists);
|
||||
|
||||
// 2000~2999 [Client Check]
|
||||
PROXIMA_ZVEC_ERROR_CODE_DECLARE(EmptyCollectionName);
|
||||
PROXIMA_ZVEC_ERROR_CODE_DECLARE(EmptyColumnName);
|
||||
PROXIMA_ZVEC_ERROR_CODE_DECLARE(EmptyPartitionName);
|
||||
PROXIMA_ZVEC_ERROR_CODE_DECLARE(EmptyColumns);
|
||||
PROXIMA_ZVEC_ERROR_CODE_DECLARE(EmptyPrimaryKey);
|
||||
PROXIMA_ZVEC_ERROR_CODE_DECLARE(EmptyDocList);
|
||||
PROXIMA_ZVEC_ERROR_CODE_DECLARE(EmptyDocFields);
|
||||
PROXIMA_ZVEC_ERROR_CODE_DECLARE(EmptyIndexField);
|
||||
PROXIMA_ZVEC_ERROR_CODE_DECLARE(InvalidRecord);
|
||||
PROXIMA_ZVEC_ERROR_CODE_DECLARE(InvalidQuery);
|
||||
PROXIMA_ZVEC_ERROR_CODE_DECLARE(InvalidWriteRequest);
|
||||
PROXIMA_ZVEC_ERROR_CODE_DECLARE(InvalidVectorFormat);
|
||||
PROXIMA_ZVEC_ERROR_CODE_DECLARE(InvalidDataType);
|
||||
PROXIMA_ZVEC_ERROR_CODE_DECLARE(InvalidIndexType);
|
||||
PROXIMA_ZVEC_ERROR_CODE_DECLARE(InvalidFeature);
|
||||
PROXIMA_ZVEC_ERROR_CODE_DECLARE(InvalidFilter);
|
||||
PROXIMA_ZVEC_ERROR_CODE_DECLARE(InvalidPrimaryKey);
|
||||
PROXIMA_ZVEC_ERROR_CODE_DECLARE(InvalidField);
|
||||
PROXIMA_ZVEC_ERROR_CODE_DECLARE(MismatchedIndexColumn);
|
||||
PROXIMA_ZVEC_ERROR_CODE_DECLARE(MismatchedDimension);
|
||||
PROXIMA_ZVEC_ERROR_CODE_DECLARE(MismatchedDataType);
|
||||
PROXIMA_ZVEC_ERROR_CODE_DECLARE(InexistentCollection);
|
||||
PROXIMA_ZVEC_ERROR_CODE_DECLARE(InexistentPartition);
|
||||
PROXIMA_ZVEC_ERROR_CODE_DECLARE(InexistentColumn);
|
||||
PROXIMA_ZVEC_ERROR_CODE_DECLARE(InexistentKey);
|
||||
PROXIMA_ZVEC_ERROR_CODE_DECLARE(DuplicateCollection);
|
||||
PROXIMA_ZVEC_ERROR_CODE_DECLARE(DuplicatePartition);
|
||||
PROXIMA_ZVEC_ERROR_CODE_DECLARE(DuplicateKey);
|
||||
PROXIMA_ZVEC_ERROR_CODE_DECLARE(DuplicateField);
|
||||
PROXIMA_ZVEC_ERROR_CODE_DECLARE(UnreadyPartition);
|
||||
PROXIMA_ZVEC_ERROR_CODE_DECLARE(UnreadyCollection);
|
||||
PROXIMA_ZVEC_ERROR_CODE_DECLARE(UnsupportedCondition);
|
||||
PROXIMA_ZVEC_ERROR_CODE_DECLARE(OrderbyNotInSelectItems);
|
||||
PROXIMA_ZVEC_ERROR_CODE_DECLARE(PbToSqlInfoError);
|
||||
PROXIMA_ZVEC_ERROR_CODE_DECLARE(ExceedRateLimit);
|
||||
PROXIMA_ZVEC_ERROR_CODE_DECLARE(InvalidSparseValues);
|
||||
PROXIMA_ZVEC_ERROR_CODE_DECLARE(InvalidBatchSize);
|
||||
PROXIMA_ZVEC_ERROR_CODE_DECLARE(InvalidDimension);
|
||||
PROXIMA_ZVEC_ERROR_CODE_DECLARE(InvalidExtraParam);
|
||||
PROXIMA_ZVEC_ERROR_CODE_DECLARE(InvalidRadius);
|
||||
PROXIMA_ZVEC_ERROR_CODE_DECLARE(InvalidLinear);
|
||||
PROXIMA_ZVEC_ERROR_CODE_DECLARE(InvalidTopk);
|
||||
PROXIMA_ZVEC_ERROR_CODE_DECLARE(InvalidCollectionName);
|
||||
PROXIMA_ZVEC_ERROR_CODE_DECLARE(InvalidPartitionName);
|
||||
PROXIMA_ZVEC_ERROR_CODE_DECLARE(InvalidFieldName);
|
||||
PROXIMA_ZVEC_ERROR_CODE_DECLARE(InvalidChannelCount);
|
||||
PROXIMA_ZVEC_ERROR_CODE_DECLARE(InvalidReplicaCount);
|
||||
PROXIMA_ZVEC_ERROR_CODE_DECLARE(InvalidJson);
|
||||
PROXIMA_ZVEC_ERROR_CODE_DECLARE(InvalidClusterConfig);
|
||||
PROXIMA_ZVEC_ERROR_CODE_DECLARE(DuplicateCluster);
|
||||
PROXIMA_ZVEC_ERROR_CODE_DECLARE(InexistentCluster);
|
||||
PROXIMA_ZVEC_ERROR_CODE_DECLARE(InvalidClusterStatus);
|
||||
PROXIMA_ZVEC_ERROR_CODE_DECLARE(RpcTimedout);
|
||||
PROXIMA_ZVEC_ERROR_CODE_DECLARE(InvalidGroupBy);
|
||||
PROXIMA_ZVEC_ERROR_CODE_DECLARE(EmptyVectorField);
|
||||
PROXIMA_ZVEC_ERROR_CODE_DECLARE(VectorNotAllowed);
|
||||
PROXIMA_ZVEC_ERROR_CODE_DECLARE(InvalidReferenceCollection);
|
||||
PROXIMA_ZVEC_ERROR_CODE_DECLARE(InvalidOrderBy);
|
||||
|
||||
|
||||
// 40000~49999 [De Admin]
|
||||
} // namespace zvec
|
||||
@@ -0,0 +1,128 @@
|
||||
// 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 "file_helper.h"
|
||||
#include <sys/stat.h>
|
||||
#include <dirent.h>
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <string.h>
|
||||
#include <unistd.h>
|
||||
#include <cstdio>
|
||||
#include <ailego/pattern/defer.h>
|
||||
|
||||
namespace zvec {
|
||||
|
||||
|
||||
// keep consistent with MANIFEST_BACKUP_FILE
|
||||
const std::string FileHelper::BACKUP_SUFFIX = ".backup_";
|
||||
const std::string FileHelper::RECOVER_SUFFIX = ".recovering";
|
||||
|
||||
bool FileHelper::CopyFile(const std::string &src_file_path,
|
||||
const std::string &dst_file_path) {
|
||||
int src_fd = open(src_file_path.c_str(), O_RDONLY, 0);
|
||||
if (src_fd < 0) {
|
||||
return false;
|
||||
}
|
||||
AILEGO_DEFER([src_fd] { close(src_fd); });
|
||||
|
||||
std::string dst_file_path_tmp = dst_file_path + ".tmp";
|
||||
int dst_fd =
|
||||
open(dst_file_path_tmp.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0644);
|
||||
if (dst_fd < 0) {
|
||||
return false;
|
||||
}
|
||||
AILEGO_DEFER([dst_fd] { close(dst_fd); });
|
||||
|
||||
ssize_t size;
|
||||
char buf[BUFSIZ];
|
||||
while ((size = read(src_fd, buf, BUFSIZ)) > 0) {
|
||||
if (size != write(dst_fd, buf, size)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return rename(dst_file_path_tmp.c_str(), dst_file_path.c_str()) == 0;
|
||||
}
|
||||
|
||||
bool FileHelper::CopyDirectory(const std::string &src_dir_path,
|
||||
const std::string &dst_dir_path) {
|
||||
DIR *dir = opendir(src_dir_path.c_str());
|
||||
if (!dir) {
|
||||
return false;
|
||||
}
|
||||
AILEGO_DEFER([dir] { closedir(dir); });
|
||||
|
||||
if (!ailego::FileHelper::IsExist(dst_dir_path.c_str())) {
|
||||
if (!ailego::FileHelper::MakePath(dst_dir_path.c_str())) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
struct dirent *dent;
|
||||
while ((dent = readdir(dir)) != nullptr) {
|
||||
if (!strcmp(dent->d_name, ".") || !strcmp(dent->d_name, "..")) {
|
||||
continue;
|
||||
}
|
||||
std::string src_full_path =
|
||||
ailego::StringHelper::Concat(src_dir_path, "/", dent->d_name);
|
||||
std::string dst_full_path =
|
||||
ailego::StringHelper::Concat(dst_dir_path, "/", dent->d_name);
|
||||
|
||||
if (ailego::FileHelper::IsDirectory(src_full_path.c_str())) {
|
||||
if (!CopyDirectory(src_full_path, dst_full_path)) {
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
if (!CopyFile(src_full_path, dst_full_path)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void FileHelper::CleanupDirectory(const std::string &backup_dir,
|
||||
size_t max_backup_count,
|
||||
const char *prefix_name) {
|
||||
if (max_backup_count <= 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
DIR *dir = opendir(backup_dir.c_str());
|
||||
if (!dir) {
|
||||
return;
|
||||
}
|
||||
|
||||
AILEGO_DEFER([dir] { closedir(dir); });
|
||||
|
||||
size_t prefix_len = strlen(prefix_name);
|
||||
std::vector<std::string> candidates;
|
||||
struct dirent *dent;
|
||||
while ((dent = readdir(dir)) != nullptr) {
|
||||
if (strncmp(dent->d_name, prefix_name, prefix_len) == 0) {
|
||||
candidates.emplace_back(dent->d_name);
|
||||
}
|
||||
}
|
||||
if (candidates.size() <= max_backup_count) {
|
||||
return;
|
||||
}
|
||||
std::sort(candidates.begin(), candidates.end());
|
||||
for (size_t i = 0; i < candidates.size() - max_backup_count; ++i) {
|
||||
std::string path =
|
||||
ailego::StringHelper::Concat(backup_dir, "/", candidates[i].c_str());
|
||||
ailego::FileHelper::RemovePath(path.c_str());
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace zvec
|
||||
@@ -0,0 +1,260 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
#pragma once
|
||||
|
||||
#include <stdint.h>
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include <ailego/io/file.h>
|
||||
#include <ailego/utility/file_helper.h>
|
||||
#include <ailego/utility/string_helper.h>
|
||||
|
||||
namespace zvec {
|
||||
|
||||
/*
|
||||
* File type and id
|
||||
*/
|
||||
enum class FileID : uint32_t {
|
||||
UNDEFINED = 0,
|
||||
ID_FILE,
|
||||
DELETE_FILE,
|
||||
FORWARD_FILE,
|
||||
PROXIMA_FILE,
|
||||
SEGMENT_FILE,
|
||||
LSN_FILE,
|
||||
MANIFEST_FILE,
|
||||
WAL_FILE,
|
||||
RESHARD_STATE,
|
||||
};
|
||||
|
||||
/*
|
||||
* File name coresponding to file id
|
||||
*/
|
||||
static const char *GetFileName(FileID t) {
|
||||
switch (t) {
|
||||
case FileID::ID_FILE:
|
||||
return "idmap";
|
||||
case FileID::DELETE_FILE:
|
||||
return "del";
|
||||
case FileID::FORWARD_FILE:
|
||||
return "data.fwd";
|
||||
case FileID::PROXIMA_FILE:
|
||||
return "data.pxa";
|
||||
case FileID::SEGMENT_FILE:
|
||||
return "data.seg";
|
||||
case FileID::LSN_FILE:
|
||||
return "data.lsn";
|
||||
case FileID::MANIFEST_FILE:
|
||||
return "manifest";
|
||||
case FileID::WAL_FILE:
|
||||
return "data.wal";
|
||||
case FileID::RESHARD_STATE:
|
||||
return "reshard.state";
|
||||
default:
|
||||
return "UnknownFile";
|
||||
};
|
||||
}
|
||||
|
||||
/*
|
||||
* This helper class is mainly to wrapper filesystem operations.
|
||||
*/
|
||||
class FileHelper {
|
||||
public:
|
||||
static const std::string MakeWalPath(const std::string &path, uint32_t seg_id,
|
||||
uint32_t block_id) {
|
||||
return ailego::StringHelper::Concat(path, "/", seg_id, "/", block_id,
|
||||
".wal");
|
||||
}
|
||||
|
||||
static std::string MakeSegmentPath(const std::string &path, uint32_t id,
|
||||
const std::string &suffix = "") {
|
||||
if (suffix.empty()) {
|
||||
return ailego::StringHelper::Concat(path, "/", id);
|
||||
}
|
||||
return ailego::StringHelper::Concat(path, "/", id, ".", suffix);
|
||||
}
|
||||
|
||||
static std::string MakeTempSegmentPath(const std::string &path, uint32_t id) {
|
||||
return MakeSegmentPath(path, id, "tmp");
|
||||
}
|
||||
|
||||
// e.g.: **/seg1/scalar.block.1.ipc, **/seg1/scalar.block.1.parquet
|
||||
static const std::string MakeForwardBlockPath(const std::string &path,
|
||||
uint32_t seg_id,
|
||||
uint32_t block_id,
|
||||
bool use_parquet = false) {
|
||||
return use_parquet ? MakeForwardBlockPath(path, seg_id, block_id,
|
||||
std::string("parquet"))
|
||||
: MakeForwardBlockPath(path, seg_id, block_id,
|
||||
std::string("ipc"));
|
||||
}
|
||||
|
||||
static const std::string MakeForwardBlockPath(const std::string &path,
|
||||
uint32_t seg_id,
|
||||
uint32_t block_id,
|
||||
const std::string &suffix) {
|
||||
return ailego::StringHelper::Concat(path, "/", seg_id, "/scalar.", block_id,
|
||||
".", suffix);
|
||||
}
|
||||
|
||||
static const std::string MakeForwardBlockPath(const std::string &seg_path,
|
||||
uint32_t block_id,
|
||||
bool use_parquet = false) {
|
||||
return use_parquet ? ailego::StringHelper::Concat(seg_path, "/scalar.",
|
||||
block_id, ".parquet")
|
||||
: ailego::StringHelper::Concat(seg_path, "/scalar.",
|
||||
block_id, ".ipc");
|
||||
}
|
||||
|
||||
static const std::string MakeForwardBlockPath(const std::string &seg_path,
|
||||
uint32_t block_id,
|
||||
const std::string &suffix) {
|
||||
return ailego::StringHelper::Concat(seg_path, "/scalar.", block_id, ".",
|
||||
suffix);
|
||||
}
|
||||
|
||||
// e.g.: **/seg1/scalar.index.block.1.rocksdb
|
||||
static const std::string MakeInvertIndexPath(const std::string &path,
|
||||
uint32_t seg_id,
|
||||
uint32_t block_id) {
|
||||
return ailego::StringHelper::Concat(path, "/", seg_id, "/scalar.index.",
|
||||
block_id, ".rocksdb");
|
||||
}
|
||||
|
||||
static const std::string MakeInvertIndexPath(const std::string &seg_path,
|
||||
uint32_t block_id) {
|
||||
return ailego::StringHelper::Concat(seg_path, "/scalar.index.", block_id,
|
||||
".rocksdb");
|
||||
}
|
||||
|
||||
static const std::string MakeVectorIndexPath(const std::string &path,
|
||||
const std::string &column,
|
||||
uint32_t seg_id,
|
||||
uint32_t block_id) {
|
||||
return ailego::StringHelper::Concat(path, "/", seg_id, "/", column,
|
||||
".index.", block_id, ".proxima");
|
||||
}
|
||||
|
||||
static const std::string MakeVectorIndexPath(const std::string &seg_path,
|
||||
const std::string &column,
|
||||
uint32_t block_id) {
|
||||
return ailego::StringHelper::Concat(seg_path, "/", column, ".index.",
|
||||
block_id, ".proxima");
|
||||
}
|
||||
|
||||
// e.g.: **/{seg_id}/{column}.index.block.{block_id}.proxima
|
||||
static const std::string MakeQuantizeVectorIndexPath(
|
||||
const std::string &path, const std::string &column, uint32_t seg_id,
|
||||
uint32_t block_id) {
|
||||
return ailego::StringHelper::Concat(path, "/", seg_id, "/", column,
|
||||
".qindex.", block_id, ".proxima");
|
||||
}
|
||||
|
||||
static const std::string MakeQuantizeVectorIndexPath(
|
||||
const std::string &seg_path, const std::string &column,
|
||||
uint32_t block_id) {
|
||||
return ailego::StringHelper::Concat(seg_path, "/", column, ".qindex.",
|
||||
block_id, ".proxima");
|
||||
}
|
||||
|
||||
//! Make file path with ${prefix_path}/${file_name}
|
||||
static std::string MakeFilePath(const std::string &prefix_path,
|
||||
FileID file_id) {
|
||||
return ailego::StringHelper::Concat(prefix_path, "/", GetFileName(file_id));
|
||||
}
|
||||
|
||||
//! Make file path with ${prefix_path}/${file_name}.${number}
|
||||
static std::string MakeFilePath(const std::string &prefix_path,
|
||||
FileID file_id, uint32_t number) {
|
||||
return ailego::StringHelper::Concat(prefix_path, "/", GetFileName(file_id),
|
||||
".", number);
|
||||
}
|
||||
|
||||
//! Make file path with ${prefix_path}/${file_name}.${suffix_name}.${number}
|
||||
static std::string MakeFilePath(const std::string &prefix_path,
|
||||
FileID file_id, uint32_t number,
|
||||
const std::string &suffix_name) {
|
||||
return ailego::StringHelper::Concat(prefix_path, "/", GetFileName(file_id),
|
||||
".", suffix_name, ".", number);
|
||||
}
|
||||
|
||||
//! Create directory
|
||||
static bool CreateDirectory(const std::string &dir_path) {
|
||||
return ailego::File::MakePath(dir_path);
|
||||
}
|
||||
|
||||
//! Remove directory
|
||||
static bool RemoveDirectory(const std::string &dir_path) {
|
||||
return ailego::File::RemoveDirectory(dir_path);
|
||||
}
|
||||
|
||||
//! Remove file
|
||||
static bool RemoveFile(const std::string &file_path) {
|
||||
return ailego::File::Delete(file_path);
|
||||
}
|
||||
|
||||
//! Move file
|
||||
static bool MoveFile(const std::string &src_path,
|
||||
const std::string &dest_path) {
|
||||
return ailego::File::Rename(src_path, dest_path);
|
||||
}
|
||||
|
||||
//! Move directory
|
||||
static bool MoveDirectory(const std::string &src_path,
|
||||
const std::string &dest_path) {
|
||||
return ailego::File::Rename(src_path, dest_path);
|
||||
}
|
||||
|
||||
//! Check if file exists
|
||||
static bool FileExists(const std::string &file_path) {
|
||||
return ailego::File::IsExist(file_path);
|
||||
}
|
||||
|
||||
//! Check if directory exists
|
||||
static bool DirectoryExists(const std::string &dir_path) {
|
||||
return ailego::File::IsExist(dir_path);
|
||||
}
|
||||
|
||||
//! Return file size
|
||||
static size_t FileSize(const std::string &file_path) {
|
||||
return ailego::FileHelper::FileSize(file_path.c_str());
|
||||
}
|
||||
|
||||
//! Copy file
|
||||
//! src_file_path and dst_file_path must be the full path
|
||||
//! dst_file_path/.. must exist
|
||||
static bool CopyFile(const std::string &src_file_path,
|
||||
const std::string &dst_file_path);
|
||||
|
||||
//! Copy directory recursively
|
||||
//! src_dir_path and dst_dir_path must be the full path
|
||||
//! dst_dir_path will be created if not exist
|
||||
static bool CopyDirectory(const std::string &src_dir_path,
|
||||
const std::string &dst_dir_path);
|
||||
|
||||
//! Clean up file or directory with the prefix `prefix_name` under
|
||||
//! `backup_dir`, keep at most `max_backup_count` file or directory.
|
||||
//! If `max_backup_count` is 0, nothing is performed.
|
||||
//!
|
||||
//! The name pattern must be `prefix_name`_`number`, comparable by name.
|
||||
static void CleanupDirectory(const std::string &backup_dir,
|
||||
size_t max_backup_count,
|
||||
const char *prefix_name);
|
||||
|
||||
static const std::string BACKUP_SUFFIX;
|
||||
static const std::string RECOVER_SUFFIX;
|
||||
};
|
||||
|
||||
|
||||
} // namespace zvec
|
||||
@@ -0,0 +1,33 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
#include "db/common/global_resource.h"
|
||||
#include <mutex>
|
||||
#include <ailego/buffer/buffer_manager.h>
|
||||
#include "db/common/config.h"
|
||||
|
||||
namespace zvec {
|
||||
|
||||
void GlobalResource::initialize() {
|
||||
static std::once_flag flag;
|
||||
std::call_once(flag, [this]() mutable {
|
||||
this->query_thread_pool_.reset(
|
||||
new ailego::ThreadPool(GlobalConfig::Instance().query_thread_count()));
|
||||
this->optimize_thread_pool_.reset(new ailego::ThreadPool(
|
||||
GlobalConfig::Instance().optimize_thread_count()));
|
||||
ailego::BufferManager::Instance().init(
|
||||
GlobalConfig::Instance().memory_limit_bytes(), 1);
|
||||
});
|
||||
}
|
||||
|
||||
} // namespace zvec
|
||||
@@ -0,0 +1,41 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
#pragma once
|
||||
|
||||
#include <memory>
|
||||
#include <ailego/pattern/singleton.h>
|
||||
#include "ailego/parallel/thread_pool.h"
|
||||
|
||||
namespace zvec {
|
||||
|
||||
class GlobalResource : public ailego::Singleton<GlobalResource> {
|
||||
public:
|
||||
void initialize();
|
||||
|
||||
ailego::ThreadPool *query_thread_pool() {
|
||||
initialize();
|
||||
return query_thread_pool_.get();
|
||||
}
|
||||
|
||||
ailego::ThreadPool *optimize_thread_pool() {
|
||||
initialize();
|
||||
return optimize_thread_pool_.get();
|
||||
}
|
||||
|
||||
private:
|
||||
std::unique_ptr<ailego::ThreadPool> query_thread_pool_;
|
||||
std::unique_ptr<ailego::ThreadPool> optimize_thread_pool_;
|
||||
};
|
||||
|
||||
} // namespace zvec
|
||||
@@ -0,0 +1,99 @@
|
||||
// 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 <ailego/io/file.h>
|
||||
#include <ailego/logger/logger.h>
|
||||
|
||||
#ifdef __GNUC__
|
||||
#pragma GCC diagnostic push
|
||||
#pragma GCC diagnostic ignored "-Wshadow"
|
||||
#pragma GCC diagnostic ignored "-Wunused-parameter"
|
||||
#endif
|
||||
|
||||
#include <glog/logging.h>
|
||||
|
||||
#ifdef __GNUC__
|
||||
#pragma GCC diagnostic pop
|
||||
#endif
|
||||
|
||||
namespace google {
|
||||
namespace glog_internal_namespace_ {
|
||||
extern bool IsGoogleLoggingInitialized(void);
|
||||
extern bool ShutdownGoogleLoggingUtilities(void);
|
||||
} // namespace glog_internal_namespace_
|
||||
} // namespace google
|
||||
|
||||
namespace zvec {
|
||||
|
||||
class AppendLogger : public ailego::Logger {
|
||||
public:
|
||||
AppendLogger() = default;
|
||||
|
||||
~AppendLogger() {
|
||||
this->cleanup();
|
||||
}
|
||||
|
||||
public:
|
||||
int init(const ailego::Params ¶ms) override {
|
||||
if (!google::glog_internal_namespace_::IsGoogleLoggingInitialized()) {
|
||||
std::string log_dir = params.get_as_string("proxima.file.logger.log_dir");
|
||||
std::string log_file =
|
||||
params.get_as_string("proxima.file.logger.log_file");
|
||||
uint32_t log_file_size =
|
||||
params.get_as_uint32("proxima.file.logger.file_size");
|
||||
uint32_t log_overdue_days =
|
||||
params.get_as_uint32("proxima.file.logger.overdue_days");
|
||||
|
||||
if (!ailego::File::IsExist(log_dir)) {
|
||||
ailego::File::MakePath(log_dir);
|
||||
}
|
||||
|
||||
FLAGS_log_dir = log_dir;
|
||||
FLAGS_max_log_size = log_file_size;
|
||||
FLAGS_logbufsecs = 1;
|
||||
// it's really a bad feature for glog
|
||||
// logs <= LOG_FATAL will also output to stderr
|
||||
// and we can only set FATAL at most
|
||||
// and so we should avoid to use LOG_FATAL
|
||||
FLAGS_stderrthreshold = google::GLOG_FATAL;
|
||||
|
||||
static std::string new_log_file = log_file;
|
||||
google::InitGoogleLogging(new_log_file.c_str());
|
||||
google::EnableLogCleaner(log_overdue_days);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
int cleanup() override {
|
||||
if (google::glog_internal_namespace_::IsGoogleLoggingInitialized()) {
|
||||
google::DisableLogCleaner();
|
||||
google::ShutdownGoogleLogging();
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
void log(int level, const char *file, int line, const char *format,
|
||||
va_list args) override {
|
||||
static google::LogSeverity severities[] = {
|
||||
google::GLOG_INFO, google::GLOG_INFO, google::GLOG_WARNING,
|
||||
google::GLOG_ERROR, google::GLOG_FATAL};
|
||||
char buf[2048];
|
||||
vsnprintf(buf, sizeof(buf), format, args);
|
||||
google::LogMessage(file, line, severities[level]).stream() << buf;
|
||||
// NOTE: glog will flush WARN and above immediately, flush INFO every
|
||||
// `FLAGS_logbufsecs` or every 1M bytes. FlushLogFiles not needed.
|
||||
// google::FlushLogFiles(severities[level]);
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace zvec
|
||||
@@ -0,0 +1,75 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <ailego/io/file.h>
|
||||
#include <ailego/logger/logger.h>
|
||||
#include <gflags/gflags.h>
|
||||
#include "ailego/pattern/factory.h"
|
||||
#include "constants.h"
|
||||
#include "error_code.h"
|
||||
#include "status.h"
|
||||
|
||||
namespace zvec {
|
||||
|
||||
class LogUtil {
|
||||
public:
|
||||
static Status Init(const std::string &log_dir, const std::string &log_file,
|
||||
int log_level, const std::string &logger_type,
|
||||
int log_file_size, int log_overdue_days) {
|
||||
if (logger_type == FILE_LOG_TYPE_NAME) {
|
||||
if (log_dir.empty() || log_file.empty()) {
|
||||
return Status::InvalidArgument("log_dir or log_file is empty");
|
||||
}
|
||||
|
||||
if (!ailego::File::IsExist(log_dir)) {
|
||||
ailego::File::MakePath(log_dir);
|
||||
}
|
||||
}
|
||||
|
||||
auto logger =
|
||||
ailego::Factory<ailego::Logger>::MakeShared(logger_type.c_str());
|
||||
if (!logger) {
|
||||
LOG_FATAL("Invalid logger_type[%s]", logger_type.c_str());
|
||||
return Status::InvalidArgument("Invalid logger_type: ", logger_type);
|
||||
}
|
||||
|
||||
ailego::Params params;
|
||||
if (logger_type == FILE_LOG_TYPE_NAME) {
|
||||
params.set("proxima.file.logger.log_dir", log_dir);
|
||||
params.set("proxima.file.logger.log_file", log_file);
|
||||
params.set("proxima.file.logger.path", log_dir + "/" + log_file);
|
||||
std::string program_name = ailego::File::BaseName(gflags::GetArgv0());
|
||||
params.set("proxima.program.program_name", program_name);
|
||||
params.set("proxima.file.logger.file_size", log_file_size);
|
||||
params.set("proxima.file.logger.overdue_days", log_overdue_days);
|
||||
}
|
||||
|
||||
int ret = logger->init(params);
|
||||
if (ret != 0) {
|
||||
return Status::InternalError(ErrorCode::What(ret));
|
||||
}
|
||||
|
||||
zvec::ailego::LoggerBroker::SetLevel(log_level);
|
||||
zvec::ailego::LoggerBroker::Register(logger);
|
||||
return Status::OK();
|
||||
}
|
||||
|
||||
static void Shutdown() {
|
||||
zvec::ailego::LoggerBroker::Unregister();
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace zvec
|
||||
@@ -0,0 +1,201 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
#pragma once
|
||||
|
||||
#include <memory>
|
||||
#include <vector>
|
||||
#include <ailego/encoding/json.h>
|
||||
#include <ailego/logger/logger.h>
|
||||
#include <ailego/utility/time_helper.h>
|
||||
#include "error_code.h"
|
||||
|
||||
namespace zvec {
|
||||
|
||||
//! Profiler collecting all the latency and other information during query
|
||||
class Profiler {
|
||||
public:
|
||||
using Ptr = std::shared_ptr<Profiler>;
|
||||
|
||||
private:
|
||||
//! Stage object
|
||||
struct Stage {
|
||||
//! Constructor
|
||||
explicit Stage(ailego::JsonObject *node) : node_(node) {}
|
||||
//! Stage node, which stored in JsonTree held by Profiler
|
||||
ailego::JsonObject *node_{nullptr};
|
||||
//! Stage latency, started when creating Stage object
|
||||
ailego::ElapsedTime latency_;
|
||||
};
|
||||
|
||||
public:
|
||||
//! Constructor
|
||||
explicit Profiler(bool enable = false) : enable_(enable) {
|
||||
if (enabled()) {
|
||||
root_.assign(ailego::JsonObject());
|
||||
}
|
||||
}
|
||||
|
||||
//! Check enabled
|
||||
bool enabled() const {
|
||||
return (enabled_debug() || enabled_trace());
|
||||
}
|
||||
|
||||
bool enabled_debug() const {
|
||||
return enable_;
|
||||
}
|
||||
|
||||
bool enabled_trace() const {
|
||||
return !trace_id_.empty();
|
||||
}
|
||||
|
||||
//! Start profiler
|
||||
void start() {
|
||||
if (enabled() && path_.empty()) {
|
||||
path_.emplace_back(Stage(&root_.as_object()));
|
||||
}
|
||||
}
|
||||
|
||||
//! Stop profiler
|
||||
void stop() {
|
||||
if (enabled()) {
|
||||
if (path_.size() == 1) {
|
||||
// Root always held in path_[0]
|
||||
close_stage();
|
||||
} else {
|
||||
LOG_WARN("There are stages have not been closed, stages[%zu]",
|
||||
path_.size());
|
||||
// Manually set latency to root, which should not be normal way
|
||||
root_["latency"] = path_.begin()->latency_.micro_seconds();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//! Open stage, start timer of stage
|
||||
int open_stage(const std::string &name) {
|
||||
if (enabled()) {
|
||||
if (path_.empty()) {
|
||||
LOG_ERROR("Profiler did not start yet. name[%s]", name.c_str());
|
||||
return PROXIMA_ZVEC_ERROR_CODE(RuntimeError);
|
||||
}
|
||||
if (name.empty()) {
|
||||
LOG_ERROR("Can't open stage with empty name");
|
||||
return PROXIMA_ZVEC_ERROR_CODE(RuntimeError);
|
||||
}
|
||||
ailego::JsonString key(name);
|
||||
ailego::JsonObject child;
|
||||
|
||||
current_path()->set(key, child); // add child
|
||||
path_.emplace_back(Stage(
|
||||
&((*current_path())[name.c_str()].as_object()))); // move to child
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
//! Close stage and stop timer of stage(represent by stage.latency)
|
||||
int close_stage() {
|
||||
if (enabled()) {
|
||||
if (path_.empty()) {
|
||||
LOG_ERROR("No available stage can be closed");
|
||||
return PROXIMA_ZVEC_ERROR_CODE(RuntimeError);
|
||||
}
|
||||
ailego::JsonValue latency(current()->latency_.micro_seconds());
|
||||
current_path()->set("latency", latency);
|
||||
path_.pop_back();
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
//! add value to profiler
|
||||
template <typename VALUE_TYPE>
|
||||
int add(const std::string &name, const VALUE_TYPE &v) {
|
||||
if (enabled()) {
|
||||
if (path_.empty()) {
|
||||
return PROXIMA_ZVEC_ERROR_CODE(RuntimeError);
|
||||
}
|
||||
|
||||
ailego::JsonString key(name);
|
||||
ailego::JsonValue value(v);
|
||||
current_path()->set(key, value);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
//! Serialize profiler to string(Json Format)
|
||||
std::string as_json_string() const {
|
||||
return enabled() ? root_.as_json_string().as_stl_string()
|
||||
: std::string("{}");
|
||||
}
|
||||
|
||||
|
||||
void set_trace_id(const std::string &trace_id) {
|
||||
trace_id_ = trace_id;
|
||||
if (enabled()) {
|
||||
root_.assign(ailego::JsonObject());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
const std::string &trace_id() const {
|
||||
return trace_id_;
|
||||
}
|
||||
|
||||
const ailego::JsonValue &root() const {
|
||||
return root_;
|
||||
}
|
||||
|
||||
private:
|
||||
Stage *current() {
|
||||
return path_.rbegin().operator->();
|
||||
}
|
||||
|
||||
ailego::JsonObject *current_path() {
|
||||
return current()->node_;
|
||||
}
|
||||
|
||||
private:
|
||||
//! enable flag
|
||||
bool enable_{false};
|
||||
|
||||
std::string trace_id_{};
|
||||
//! root handler
|
||||
ailego::JsonValue root_;
|
||||
|
||||
//! Depth-First paths
|
||||
std::vector<Stage> path_;
|
||||
};
|
||||
|
||||
//! Helper for latency
|
||||
class ScopedLatency {
|
||||
public:
|
||||
//! Constructor
|
||||
explicit ScopedLatency(const char *name, Profiler::Ptr profiler)
|
||||
: name_(name), profiler_(std::move(profiler)) {}
|
||||
|
||||
//! Destructor
|
||||
~ScopedLatency() {
|
||||
profiler_->add(name_, latency_.micro_seconds());
|
||||
}
|
||||
|
||||
private:
|
||||
//! Name of latency
|
||||
const char *name_{nullptr};
|
||||
|
||||
//! Timer handler
|
||||
ailego::ElapsedTime latency_;
|
||||
|
||||
//! Profiler handler
|
||||
Profiler::Ptr profiler_;
|
||||
};
|
||||
|
||||
} // namespace zvec
|
||||
@@ -0,0 +1,595 @@
|
||||
// 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 <ailego/logger/logger.h>
|
||||
#include <rocksdb/filter_policy.h>
|
||||
#include <rocksdb/statistics.h>
|
||||
#include <rocksdb/table.h>
|
||||
#include <rocksdb/utilities/checkpoint.h>
|
||||
#include "rocksdb_context.h"
|
||||
|
||||
|
||||
namespace zvec {
|
||||
|
||||
|
||||
Status RocksdbContext::create(
|
||||
const std::string &db_path,
|
||||
std::shared_ptr<rocksdb::MergeOperator> merge_op) {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
|
||||
if (db_) {
|
||||
LOG_ERROR("RocksDB[%s] is already opened", db_path_.c_str());
|
||||
return Status::PermissionDenied();
|
||||
}
|
||||
|
||||
if (auto s = validate_and_set_db_path(db_path, false); !s.ok()) {
|
||||
return s;
|
||||
}
|
||||
|
||||
create_opts_.create_if_missing = true;
|
||||
prepare_options(merge_op);
|
||||
|
||||
// Open RocksDB
|
||||
rocksdb::DB *db;
|
||||
if (auto s = rocksdb::DB::Open(create_opts_, db_path, &db); !s.ok()) {
|
||||
LOG_ERROR("Failed to create RocksDB[%s], code[%d], reason[%s]",
|
||||
db_path.c_str(), s.code(), s.ToString().c_str());
|
||||
return Status::InternalError();
|
||||
}
|
||||
|
||||
db_.reset(db);
|
||||
read_only_ = false;
|
||||
write_opts_.disableWAL = true;
|
||||
LOG_DEBUG("Created RocksDB[%s]", db_path.c_str());
|
||||
return Status::OK();
|
||||
}
|
||||
|
||||
|
||||
Status RocksdbContext::create(
|
||||
const std::string &db_path, const std::vector<std::string> &column_names,
|
||||
std::shared_ptr<rocksdb::MergeOperator> merge_op) {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
|
||||
if (db_) {
|
||||
LOG_ERROR("RocksDB[%s] is already opened", db_path_.c_str());
|
||||
return Status::PermissionDenied();
|
||||
}
|
||||
|
||||
if (auto s = validate_and_set_db_path(db_path, false); !s.ok()) {
|
||||
return s;
|
||||
}
|
||||
|
||||
create_opts_.create_if_missing = true;
|
||||
prepare_options(merge_op);
|
||||
|
||||
// Open RocksDB
|
||||
rocksdb::DB *db;
|
||||
rocksdb::Status s = rocksdb::DB::Open(create_opts_, db_path, &db);
|
||||
if (!s.ok()) {
|
||||
LOG_ERROR("Failed to create RocksDB[%s], code[%d], reason[%s]",
|
||||
db_path.c_str(), s.code(), s.ToString().c_str());
|
||||
return Status::InternalError();
|
||||
}
|
||||
db_.reset(db);
|
||||
|
||||
// Create column families
|
||||
bool has_default = false;
|
||||
for (auto const &column_name : column_names) {
|
||||
if (column_name == rocksdb::kDefaultColumnFamilyName) {
|
||||
cf_handles_.push_back(db->DefaultColumnFamily());
|
||||
has_default = true;
|
||||
continue;
|
||||
}
|
||||
rocksdb::ColumnFamilyHandle *cf_handle{nullptr};
|
||||
rocksdb::ColumnFamilyOptions cf_options(create_opts_);
|
||||
s = db->CreateColumnFamily(cf_options, column_name, &cf_handle);
|
||||
if (!s.ok()) {
|
||||
LOG_ERROR("Failed to create cf[%s] in RocksDB[%s], code[%d], reason[%s]",
|
||||
column_name.c_str(), db_path.c_str(), s.code(),
|
||||
s.ToString().c_str());
|
||||
delete_cf_handles();
|
||||
db->Close();
|
||||
db_.reset();
|
||||
return Status::InternalError();
|
||||
}
|
||||
cf_handles_.push_back(cf_handle);
|
||||
}
|
||||
if (!has_default) {
|
||||
cf_handles_.push_back(db->DefaultColumnFamily());
|
||||
}
|
||||
|
||||
read_only_ = false;
|
||||
write_opts_.disableWAL = true;
|
||||
LOG_DEBUG("Created RocksDB[%s]", db_path.c_str());
|
||||
return Status::OK();
|
||||
}
|
||||
|
||||
|
||||
Status RocksdbContext::open(const std::string &db_path, bool read_only,
|
||||
std::shared_ptr<rocksdb::MergeOperator> merge_op) {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
|
||||
if (db_) {
|
||||
LOG_ERROR("RocksDB[%s] is already opened", db_path_.c_str());
|
||||
return Status::PermissionDenied();
|
||||
}
|
||||
|
||||
if (auto s = validate_and_set_db_path(db_path, true); !s.ok()) {
|
||||
return s;
|
||||
}
|
||||
|
||||
create_opts_.create_if_missing = false;
|
||||
prepare_options(merge_op);
|
||||
|
||||
// Open RocksDB
|
||||
rocksdb::DB *db;
|
||||
rocksdb::Status s;
|
||||
if (read_only) {
|
||||
s = rocksdb::DB::OpenForReadOnly(create_opts_, db_path, &db);
|
||||
} else {
|
||||
s = rocksdb::DB::Open(create_opts_, db_path, &db);
|
||||
}
|
||||
if (!s.ok()) {
|
||||
LOG_ERROR("Failed to open RocksDB[%s], code[%d], reason[%s]",
|
||||
db_path.c_str(), s.code(), s.ToString().c_str());
|
||||
return Status::InternalError();
|
||||
}
|
||||
|
||||
db_.reset(db);
|
||||
read_only_ = read_only;
|
||||
write_opts_.disableWAL = true;
|
||||
LOG_DEBUG("Opened RocksDB[%s]", db_path.c_str());
|
||||
return Status::OK();
|
||||
}
|
||||
|
||||
|
||||
Status RocksdbContext::open(const std::string &db_path,
|
||||
const std::vector<std::string> &column_names,
|
||||
bool read_only,
|
||||
std::shared_ptr<rocksdb::MergeOperator> merge_op) {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
|
||||
if (db_) {
|
||||
LOG_ERROR("RocksDB[%s] is already opened", db_path_.c_str());
|
||||
return Status::PermissionDenied();
|
||||
}
|
||||
|
||||
if (auto s = validate_and_set_db_path(db_path, true); !s.ok()) {
|
||||
return s;
|
||||
}
|
||||
|
||||
create_opts_.create_if_missing = false;
|
||||
prepare_options(merge_op);
|
||||
|
||||
// Set up column families
|
||||
rocksdb::Status s;
|
||||
std::vector<std::string> existing_cf_names{};
|
||||
std::vector<rocksdb::ColumnFamilyDescriptor> cf_descriptors{};
|
||||
s = rocksdb::DB::ListColumnFamilies(create_opts_, db_path,
|
||||
&existing_cf_names);
|
||||
if (!s.ok()) {
|
||||
LOG_ERROR("Failed to list cf in RocksDB[%s], code[%d], reason[%s]",
|
||||
db_path.c_str(), s.code(), s.ToString().c_str());
|
||||
return Status::InternalError();
|
||||
}
|
||||
rocksdb::ColumnFamilyOptions cf_options(create_opts_);
|
||||
if (column_names.empty()) { // Get all column families from DB
|
||||
for (auto const &column_name : existing_cf_names) {
|
||||
cf_descriptors.emplace_back(column_name, cf_options);
|
||||
}
|
||||
} else {
|
||||
bool has_default = false;
|
||||
for (const auto &column_name : column_names) {
|
||||
if (std::find(existing_cf_names.begin(), existing_cf_names.end(),
|
||||
column_name) == existing_cf_names.end()) {
|
||||
LOG_ERROR("Column family[%s] does not exist in RocksDB[%s]",
|
||||
column_name.c_str(), db_path.c_str());
|
||||
return Status::InvalidArgument();
|
||||
}
|
||||
if (column_name == rocksdb::kDefaultColumnFamilyName) {
|
||||
has_default = true;
|
||||
}
|
||||
}
|
||||
if (read_only) {
|
||||
for (const auto &column_name : column_names) {
|
||||
cf_descriptors.emplace_back(column_name, cf_options);
|
||||
}
|
||||
if (!has_default) {
|
||||
cf_descriptors.emplace_back(rocksdb::kDefaultColumnFamilyName,
|
||||
cf_options);
|
||||
}
|
||||
} else { // Rocksdb must be opened with all column families in write mode
|
||||
for (auto const &column_name : existing_cf_names) {
|
||||
cf_descriptors.emplace_back(column_name, cf_options);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Open RocksDB
|
||||
rocksdb::DB *db;
|
||||
if (read_only) {
|
||||
s = rocksdb::DB::OpenForReadOnly(create_opts_, db_path, cf_descriptors,
|
||||
&cf_handles_, &db);
|
||||
} else {
|
||||
s = rocksdb::DB::Open(create_opts_, db_path, cf_descriptors, &cf_handles_,
|
||||
&db);
|
||||
}
|
||||
if (!s.ok()) {
|
||||
LOG_ERROR("Failed to open RocksDB[%s], code[%d], reason[%s]",
|
||||
db_path.c_str(), s.code(), s.ToString().c_str());
|
||||
return Status::InternalError();
|
||||
}
|
||||
|
||||
db_.reset(db);
|
||||
read_only_ = read_only;
|
||||
write_opts_.disableWAL = true;
|
||||
LOG_DEBUG("Opened RocksDB[%s]", db_path.c_str());
|
||||
return Status::OK();
|
||||
}
|
||||
|
||||
|
||||
Status RocksdbContext::validate_and_set_db_path(const std::string &db_path,
|
||||
bool should_exist) {
|
||||
if (db_path.empty()) {
|
||||
LOG_ERROR("RocksDB path cannot be empty");
|
||||
return Status::InvalidArgument();
|
||||
}
|
||||
|
||||
if (FILE::IsExist(db_path)) {
|
||||
if (!should_exist) {
|
||||
LOG_ERROR("RocksDB path[%s] already exists", db_path.c_str());
|
||||
return Status::InvalidArgument();
|
||||
}
|
||||
if (!FILE::IsDirectory(db_path)) {
|
||||
LOG_ERROR("RocksDB path[%s] is not a directory", db_path.c_str());
|
||||
return Status::InvalidArgument();
|
||||
}
|
||||
} else {
|
||||
if (should_exist) {
|
||||
LOG_ERROR("RocksDB path[%s] does not exist", db_path.c_str());
|
||||
return Status::NotFound();
|
||||
}
|
||||
}
|
||||
|
||||
db_path_ = db_path;
|
||||
return Status::OK();
|
||||
}
|
||||
|
||||
|
||||
void RocksdbContext::prepare_options(
|
||||
std::shared_ptr<rocksdb::MergeOperator> merge_op) {
|
||||
// Increase parallelism with default thread count (typically 16)
|
||||
create_opts_.IncreaseParallelism();
|
||||
|
||||
// Optimize for level-based compaction style with default setting
|
||||
create_opts_.OptimizeLevelStyleCompaction();
|
||||
|
||||
// TODO: enable compression?
|
||||
|
||||
// Setting this to 1 means that when a memtable is full, it will be flushed
|
||||
// to disk immediately rather than being merged with other memtables
|
||||
create_opts_.min_write_buffer_number_to_merge = 1;
|
||||
|
||||
// Set the block size for the arena memory allocator to 64KB, which controls
|
||||
// how much memory is allocated at a time for internal operations
|
||||
create_opts_.arena_block_size = 1024 * 64;
|
||||
|
||||
// Do not create LOG.old when reopen
|
||||
create_opts_.keep_log_file_num = 1;
|
||||
|
||||
// Warnings and errors only
|
||||
create_opts_.info_log_level = rocksdb::WARN_LEVEL;
|
||||
|
||||
rocksdb::BlockBasedTableOptions table_options;
|
||||
|
||||
// Turn on bloom filters
|
||||
table_options.filter_policy.reset(rocksdb::NewBloomFilterPolicy(10, false));
|
||||
|
||||
// Merge operator
|
||||
if (merge_op) {
|
||||
create_opts_.merge_operator = merge_op;
|
||||
create_opts_.max_successive_merges = 100;
|
||||
create_opts_.write_buffer_size = 8 << 20;
|
||||
}
|
||||
|
||||
// Create default cache
|
||||
table_options.block_cache = nullptr;
|
||||
|
||||
auto table_factory = NewBlockBasedTableFactory(table_options);
|
||||
create_opts_.table_factory.reset(table_factory);
|
||||
|
||||
// Enable statistics
|
||||
create_opts_.statistics = rocksdb::CreateDBStatistics();
|
||||
|
||||
// Disable external write buffer manager, let RocksDB manage it
|
||||
create_opts_.write_buffer_manager = nullptr;
|
||||
|
||||
// Reduce preallocation size for manifest file to 512KB to save disk space
|
||||
create_opts_.manifest_preallocation_size = 512 * 1024;
|
||||
|
||||
// Disable direct reads (use buffered I/O instead)
|
||||
create_opts_.use_direct_reads = false;
|
||||
}
|
||||
|
||||
|
||||
Status RocksdbContext::close() {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
|
||||
if (db_ == nullptr) {
|
||||
LOG_ERROR("RocksDB[%s] is not opened", db_path_.c_str());
|
||||
return Status::InternalError();
|
||||
}
|
||||
|
||||
if (!read_only_) {
|
||||
if (auto s = flush_unlocked(); !s.ok()) {
|
||||
LOG_ERROR("Failed to close RocksDB[%s] due to flush failure",
|
||||
db_path_.c_str());
|
||||
return s;
|
||||
}
|
||||
}
|
||||
|
||||
delete_cf_handles();
|
||||
|
||||
if (auto s = db_->Close(); s.ok()) {
|
||||
LOG_DEBUG("Closed RocksDB[%s]", db_path_.c_str());
|
||||
db_.reset();
|
||||
return Status::OK();
|
||||
} else {
|
||||
LOG_ERROR("Failed to close RocksDB[%s], code[%d], reason[%s]",
|
||||
db_path_.c_str(), s.code(), s.ToString().c_str());
|
||||
return Status::InternalError();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Status RocksdbContext::flush_unlocked() {
|
||||
if (read_only_) {
|
||||
LOG_ERROR("Cannot flush RocksDB[%s] in read-only mode", db_path_.c_str());
|
||||
return Status::PermissionDenied();
|
||||
}
|
||||
|
||||
for (const auto &cf : cf_handles_) {
|
||||
if (auto s = db_->Flush(flush_opts_, cf); !s.ok()) {
|
||||
LOG_ERROR("Failed to flush cf[%s] of RocksDB[%s], code[%d], reason[%s]",
|
||||
cf->GetName().c_str(), db_path_.c_str(), s.code(),
|
||||
s.ToString().c_str());
|
||||
return Status::InternalError();
|
||||
}
|
||||
}
|
||||
|
||||
if (auto s = db_->Flush(flush_opts_); s.ok()) {
|
||||
LOG_DEBUG("Flushed RocksDB[%s]", db_path_.c_str());
|
||||
return Status::OK();
|
||||
} else {
|
||||
LOG_ERROR("Failed to flush Rocksdb[%s], code[%d], reason[%s]",
|
||||
db_path_.c_str(), s.code(), s.ToString().c_str());
|
||||
return Status::InternalError();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Status RocksdbContext::flush() {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
return flush_unlocked();
|
||||
}
|
||||
|
||||
|
||||
Status RocksdbContext::create_checkpoint(const std::string &checkpoint_dir) {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
|
||||
rocksdb::Checkpoint *cp{nullptr};
|
||||
if (auto s = rocksdb::Checkpoint::Create(db_.get(), &cp); !s.ok()) {
|
||||
LOG_ERROR(
|
||||
"Failed to create a checkpoint object of Rocksdb[%s], code[%d], "
|
||||
"reason[%s]",
|
||||
db_path_.c_str(), s.code(), s.ToString().c_str());
|
||||
return Status::InternalError();
|
||||
}
|
||||
|
||||
if (auto s = cp->CreateCheckpoint(checkpoint_dir); s.ok()) {
|
||||
LOG_DEBUG("Created a checkpoint of Rocksdb[%s] to [%s]", db_path_.c_str(),
|
||||
checkpoint_dir.c_str());
|
||||
delete cp;
|
||||
return Status::OK();
|
||||
} else {
|
||||
LOG_ERROR(
|
||||
"Failed to create a checkpoint of Rocksdb[%s], code[%d], reason[%s]",
|
||||
db_path_.c_str(), s.code(), s.ToString().c_str());
|
||||
delete cp;
|
||||
return Status::InternalError();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
rocksdb::ColumnFamilyHandle *RocksdbContext::get_cf(
|
||||
const std::string &cf_name) {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
for (auto cf_handle : cf_handles_) {
|
||||
if (cf_handle->GetName() == cf_name) {
|
||||
return cf_handle;
|
||||
}
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
|
||||
Status RocksdbContext::create_cf(const std::string &cf_name) {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
|
||||
if (cf_name == rocksdb::kDefaultColumnFamilyName) {
|
||||
LOG_ERROR("Forbidden to create default cf in RocksDB[%s]",
|
||||
db_path_.c_str());
|
||||
return Status::InvalidArgument();
|
||||
}
|
||||
|
||||
for (auto cf_handle : cf_handles_) {
|
||||
if (cf_handle->GetName() == cf_name) {
|
||||
LOG_ERROR("Column family[%s] already exists in RocksDB[%s]",
|
||||
cf_name.c_str(), db_path_.c_str());
|
||||
return Status::InvalidArgument();
|
||||
}
|
||||
}
|
||||
|
||||
rocksdb::ColumnFamilyHandle *cf_handle{nullptr};
|
||||
auto s = db_->CreateColumnFamily(rocksdb::ColumnFamilyOptions(create_opts_),
|
||||
cf_name, &cf_handle);
|
||||
if (s.ok()) {
|
||||
cf_handles_.push_back(cf_handle);
|
||||
LOG_DEBUG("Created cf[%s] in RocksDB[%s]", cf_name.c_str(),
|
||||
db_path_.c_str());
|
||||
return Status::OK();
|
||||
} else {
|
||||
LOG_ERROR("Failed to create cf[%s] in RocksDB[%s], code[%d], reason[%s]",
|
||||
cf_name.c_str(), db_path_.c_str(), s.code(),
|
||||
s.ToString().c_str());
|
||||
return Status::InternalError();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Status RocksdbContext::drop_cf(const std::string &cf_name) {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
|
||||
if (cf_name == rocksdb::kDefaultColumnFamilyName) {
|
||||
LOG_ERROR("Forbidden to drop default cf in RocksDB[%s]", db_path_.c_str());
|
||||
return Status::InvalidArgument();
|
||||
}
|
||||
|
||||
auto it = std::find_if(cf_handles_.begin(), cf_handles_.end(),
|
||||
[&cf_name](rocksdb::ColumnFamilyHandle *handle) {
|
||||
return handle->GetName() == cf_name;
|
||||
});
|
||||
if (it == cf_handles_.end()) {
|
||||
LOG_WARN("Failed to find column family[%s] in RocksDB[%s]", cf_name.c_str(),
|
||||
db_path_.c_str());
|
||||
return Status::OK();
|
||||
}
|
||||
|
||||
auto s = db_->DropColumnFamily(*it);
|
||||
if (s.ok()) {
|
||||
delete *it;
|
||||
cf_handles_.erase(it);
|
||||
LOG_DEBUG("Dropped cf[%s] in RocksDB[%s]", cf_name.c_str(),
|
||||
db_path_.c_str());
|
||||
return Status::OK();
|
||||
} else {
|
||||
LOG_ERROR("Failed to drop cf[%s] in RocksDB[%s], code[%d], reason[%s]",
|
||||
cf_name.c_str(), db_path_.c_str(), s.code(),
|
||||
s.ToString().c_str());
|
||||
return Status::InternalError();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Status RocksdbContext::reset_cf(const std::string &cf_name) {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
|
||||
if (cf_name == rocksdb::kDefaultColumnFamilyName) {
|
||||
LOG_ERROR("Forbidden to reset default cf in RocksDB[%s]", db_path_.c_str());
|
||||
return Status::InvalidArgument();
|
||||
}
|
||||
|
||||
rocksdb::ColumnFamilyHandle *cf_handle{nullptr};
|
||||
size_t index;
|
||||
for (size_t i = 0; i < cf_handles_.size(); ++i) {
|
||||
if (cf_handles_[i]->GetName() == cf_name) {
|
||||
cf_handle = cf_handles_[i];
|
||||
index = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (cf_handle == nullptr) {
|
||||
LOG_ERROR("Column family[%s] does not exist in RocksDB[%s]",
|
||||
cf_name.c_str(), db_path_.c_str());
|
||||
return Status::InvalidArgument();
|
||||
}
|
||||
|
||||
auto options = db_->GetOptions(cf_handle);
|
||||
auto s = db_->DropColumnFamily(cf_handle);
|
||||
if (!s.ok()) {
|
||||
LOG_ERROR("Failed to drop cf[%s] in RocksDB[%s], code[%d], reason[%s]",
|
||||
cf_name.c_str(), db_path_.c_str(), s.code(),
|
||||
s.ToString().c_str());
|
||||
return Status::InternalError();
|
||||
}
|
||||
delete cf_handle;
|
||||
|
||||
rocksdb::ColumnFamilyHandle *new_cf_handle{nullptr};
|
||||
s = db_->CreateColumnFamily(options, cf_name, &new_cf_handle);
|
||||
if (s.ok()) {
|
||||
cf_handles_[index] = new_cf_handle;
|
||||
LOG_DEBUG("Reset cf[%s] in RocksDB[%s]", cf_name.c_str(), db_path_.c_str());
|
||||
return Status::OK();
|
||||
} else {
|
||||
LOG_ERROR("Failed to create cf[%s] in RocksDB[%s], code[%d], reason[%s]",
|
||||
cf_name.c_str(), db_path_.c_str(), s.code(),
|
||||
s.ToString().c_str());
|
||||
return Status::InternalError();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
void RocksdbContext::delete_cf_handles() {
|
||||
for (auto cf : cf_handles_) {
|
||||
db_->DestroyColumnFamilyHandle(cf);
|
||||
}
|
||||
cf_handles_.clear();
|
||||
}
|
||||
|
||||
|
||||
Status RocksdbContext::compact() {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
|
||||
for (auto cf : cf_handles_) {
|
||||
auto s = db_->CompactRange(compact_range_opts_, cf, nullptr, nullptr);
|
||||
if (!s.ok()) {
|
||||
LOG_ERROR("Failed to compact cf[%s] in RocksDB[%s], code[%d], reason[%s]",
|
||||
cf->GetName().c_str(), db_path_.c_str(), s.code(),
|
||||
s.ToString().c_str());
|
||||
}
|
||||
}
|
||||
auto s = db_->CompactRange(compact_range_opts_, nullptr, nullptr);
|
||||
if (s.ok()) {
|
||||
LOG_DEBUG("Compacted RocksDB[%s]", db_path_.c_str());
|
||||
return Status::OK();
|
||||
} else {
|
||||
LOG_ERROR("Failed to compact RocksDB[%s], code[%d], reason[%s]",
|
||||
db_path_.c_str(), s.code(), s.ToString().c_str());
|
||||
return Status::InternalError();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
size_t RocksdbContext::sst_file_size() {
|
||||
uint64_t int_num = 0;
|
||||
if (db_->GetIntProperty("rocksdb.live-sst-files-size", &int_num)) {
|
||||
return int_num;
|
||||
} else {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
size_t RocksdbContext::count() {
|
||||
uint64_t int_num = 0;
|
||||
if (db_->GetIntProperty("rocksdb.estimate-num-keys", &int_num)) {
|
||||
return int_num;
|
||||
} else {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
} // namespace zvec
|
||||
@@ -0,0 +1,121 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
|
||||
#pragma once
|
||||
|
||||
|
||||
#include <ailego/io/file.h>
|
||||
#include <rocksdb/db.h>
|
||||
#include "status.h"
|
||||
|
||||
|
||||
namespace zvec {
|
||||
|
||||
|
||||
// A very thin wrapper around RocksDB
|
||||
struct RocksdbContext {
|
||||
public:
|
||||
std::unique_ptr<rocksdb::DB> db_{nullptr};
|
||||
std::string db_path_;
|
||||
bool read_only_;
|
||||
std::vector<rocksdb::ColumnFamilyHandle *> cf_handles_;
|
||||
rocksdb::Options create_opts_;
|
||||
rocksdb::WriteOptions write_opts_;
|
||||
rocksdb::ReadOptions read_opts_;
|
||||
rocksdb::FlushOptions flush_opts_;
|
||||
rocksdb::CompactRangeOptions compact_range_opts_;
|
||||
std::mutex mutex_;
|
||||
|
||||
|
||||
public:
|
||||
// Create a Rocksdb instance
|
||||
Status create(const std::string &db_path,
|
||||
std::shared_ptr<rocksdb::MergeOperator> merge_op = nullptr);
|
||||
|
||||
|
||||
// Create a Rocksdb instance
|
||||
Status create(const std::string &db_path,
|
||||
const std::vector<std::string> &column_names,
|
||||
std::shared_ptr<rocksdb::MergeOperator> merge_op = nullptr);
|
||||
|
||||
|
||||
// Open an existing Rocksdb instance
|
||||
Status open(const std::string &db_path, bool read_only = false,
|
||||
std::shared_ptr<rocksdb::MergeOperator> merge_op = nullptr);
|
||||
|
||||
|
||||
// Open an existing Rocksdb instance
|
||||
Status open(const std::string &db_path,
|
||||
const std::vector<std::string> &column_names,
|
||||
bool read_only = false,
|
||||
std::shared_ptr<rocksdb::MergeOperator> merge_op = nullptr);
|
||||
|
||||
|
||||
// Close and flush data if needed
|
||||
Status close();
|
||||
|
||||
|
||||
// Flush data
|
||||
Status flush();
|
||||
|
||||
|
||||
// Create a checkpoint
|
||||
Status create_checkpoint(const std::string &checkpoint_dir);
|
||||
|
||||
|
||||
// Get a column family
|
||||
rocksdb::ColumnFamilyHandle *get_cf(const std::string &cf_name);
|
||||
|
||||
|
||||
// Create a column family
|
||||
Status create_cf(const std::string &cf_name);
|
||||
|
||||
|
||||
// Drop a column family
|
||||
Status drop_cf(const std::string &cf_name);
|
||||
|
||||
|
||||
// Reset a column family
|
||||
Status reset_cf(const std::string &cf_name);
|
||||
|
||||
|
||||
// Compact db
|
||||
Status compact();
|
||||
|
||||
|
||||
// Get the size of the SST files
|
||||
size_t sst_file_size();
|
||||
|
||||
|
||||
// Get the estimated number of keys in the database
|
||||
size_t count();
|
||||
|
||||
|
||||
private:
|
||||
using FILE = ailego::File;
|
||||
|
||||
|
||||
Status validate_and_set_db_path(const std::string &db_path,
|
||||
bool should_exist);
|
||||
|
||||
void prepare_options(std::shared_ptr<rocksdb::MergeOperator> merge_op);
|
||||
|
||||
Status flush_unlocked();
|
||||
|
||||
void delete_cf_handles();
|
||||
};
|
||||
|
||||
|
||||
} // namespace zvec
|
||||
@@ -0,0 +1,56 @@
|
||||
// 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 "status.h"
|
||||
#include <unordered_map>
|
||||
#include <ailego/utility/string_helper.h>
|
||||
|
||||
namespace zvec {
|
||||
|
||||
const char *GetDefaultMessage(StatusCode code) {
|
||||
static const std::unordered_map<StatusCode, const char *> kMessages = {
|
||||
{StatusCode::OK, "OK"},
|
||||
{StatusCode::NOT_FOUND, "Not found"},
|
||||
{StatusCode::ALREADY_EXISTS, "Already exists"},
|
||||
{StatusCode::INVALID_ARGUMENT, "Invalid argument"},
|
||||
{StatusCode::PERMISSION_DENIED, "Permission denied"},
|
||||
{StatusCode::FAILED_PRECONDITION, "Failed precondition"},
|
||||
{StatusCode::RESOURCE_EXHAUSTED, "Resource exhausted"},
|
||||
{StatusCode::UNAVAILABLE, "Unavailable"},
|
||||
{StatusCode::INTERNAL_ERROR, "Internal error"},
|
||||
{StatusCode::NOT_SUPPORTED, "Not supported"},
|
||||
{StatusCode::UNKNOWN, "Unknown error"}};
|
||||
auto it = kMessages.find(code);
|
||||
return it != kMessages.end() ? it->second : "Unknown status code";
|
||||
}
|
||||
|
||||
// Implementation of operator<<
|
||||
std::ostream &operator<<(std::ostream &os, const Status &s) {
|
||||
if (s.ok()) {
|
||||
os << "OK";
|
||||
} else {
|
||||
os << "Status(" << GetDefaultMessage(s.code()) << ", " << s.message()
|
||||
<< ")";
|
||||
}
|
||||
return os;
|
||||
}
|
||||
|
||||
// Implementation of comparison
|
||||
bool Status::operator==(const Status &other) const noexcept {
|
||||
if (code_ != other.code_) return false;
|
||||
if (code_ == StatusCode::OK) return true;
|
||||
return msg_ == other.msg_;
|
||||
}
|
||||
|
||||
} // namespace zvec
|
||||
@@ -0,0 +1,181 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
#pragma once
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
#include <ailego/pattern/expected.hpp>
|
||||
#include <ailego/utility/string_helper.h>
|
||||
|
||||
namespace zvec {
|
||||
|
||||
class Status;
|
||||
template <typename T>
|
||||
using Result = tl::expected<T, Status>;
|
||||
|
||||
std::ostream &operator<<(std::ostream &os, const Status &s);
|
||||
|
||||
/**
|
||||
* @brief Enumeration of common error codes.
|
||||
*/
|
||||
enum class StatusCode {
|
||||
OK = 0,
|
||||
NOT_FOUND,
|
||||
ALREADY_EXISTS,
|
||||
INVALID_ARGUMENT,
|
||||
PERMISSION_DENIED,
|
||||
FAILED_PRECONDITION,
|
||||
RESOURCE_EXHAUSTED,
|
||||
UNAVAILABLE,
|
||||
INTERNAL_ERROR,
|
||||
NOT_SUPPORTED,
|
||||
UNKNOWN
|
||||
};
|
||||
|
||||
// Helper: get default message for code
|
||||
const char *GetDefaultMessage(StatusCode code);
|
||||
|
||||
/**
|
||||
* @class Status
|
||||
* @brief Represents the result of an operation: success or failure with
|
||||
* message.
|
||||
*
|
||||
* This class is used to return error information from functions without using
|
||||
* exceptions. It stores a status code and an optional error message.
|
||||
*
|
||||
* @note This class is thread-compatible: const methods can be called from
|
||||
* multiple threads.
|
||||
*/
|
||||
class Status {
|
||||
public:
|
||||
/// @brief Default constructor: OK status
|
||||
Status() noexcept : code_(StatusCode::OK) {}
|
||||
|
||||
/// @brief Construct a failed status with code and message
|
||||
Status(StatusCode code, const std::string &msg) : code_(code), msg_(msg) {
|
||||
ensure_not_ok(code);
|
||||
}
|
||||
|
||||
/// @brief Construct a failed status with code and rvalue message
|
||||
Status(StatusCode code, std::string &&msg)
|
||||
: code_(code), msg_(std::move(msg)) {
|
||||
ensure_not_ok(code);
|
||||
}
|
||||
|
||||
/// @brief Copy constructor
|
||||
Status(const Status &) = default;
|
||||
|
||||
/// @brief Copy assignment
|
||||
Status &operator=(const Status &) = default;
|
||||
|
||||
/// @brief Move constructor
|
||||
Status(Status &&) = default;
|
||||
|
||||
/// @brief Move assignment
|
||||
Status &operator=(Status &&) = default;
|
||||
|
||||
/// @brief Destructor
|
||||
~Status() = default;
|
||||
|
||||
/// @brief Check if the status is OK (no error)
|
||||
bool ok() const noexcept {
|
||||
return code_ == StatusCode::OK;
|
||||
}
|
||||
|
||||
/// @brief Get the status code
|
||||
StatusCode code() const noexcept {
|
||||
return code_;
|
||||
}
|
||||
|
||||
/// @brief Get the error message (empty if OK)
|
||||
const std::string &message() const noexcept {
|
||||
return msg_;
|
||||
}
|
||||
|
||||
/// @brief Get C-style string (safe because msg_ owns the string)
|
||||
const char *c_str() const noexcept {
|
||||
return msg_.c_str();
|
||||
}
|
||||
|
||||
/// @brief Comparison operators
|
||||
bool operator==(const Status &other) const noexcept;
|
||||
bool operator!=(const Status &other) const noexcept {
|
||||
return !(*this == other);
|
||||
}
|
||||
|
||||
/// @brief Factory: Success
|
||||
static Status OK() noexcept {
|
||||
return Status();
|
||||
}
|
||||
|
||||
/// @brief Factory: Invalid argument
|
||||
template <typename... Args>
|
||||
static Status InvalidArgument(Args &&...args) {
|
||||
return Status(StatusCode::INVALID_ARGUMENT,
|
||||
concat(std::forward<Args>(args)...));
|
||||
}
|
||||
|
||||
/// @brief Factory: Not found
|
||||
template <typename... Args>
|
||||
static Status NotFound(Args &&...args) {
|
||||
return Status(StatusCode::NOT_FOUND, concat(std::forward<Args>(args)...));
|
||||
}
|
||||
|
||||
/// @brief Factory: Already exists
|
||||
template <typename... Args>
|
||||
static Status AlreadyExists(Args &&...args) {
|
||||
return Status(StatusCode::ALREADY_EXISTS,
|
||||
concat(std::forward<Args>(args)...));
|
||||
}
|
||||
|
||||
/// @brief Factory: Internal error
|
||||
template <typename... Args>
|
||||
static Status InternalError(Args &&...args) {
|
||||
return Status(StatusCode::INTERNAL_ERROR,
|
||||
concat(std::forward<Args>(args)...));
|
||||
}
|
||||
|
||||
/// @brief Factory: Permission denied
|
||||
template <typename... Args>
|
||||
static Status PermissionDenied(Args &&...args) {
|
||||
return Status(StatusCode::PERMISSION_DENIED,
|
||||
concat(std::forward<Args>(args)...));
|
||||
}
|
||||
|
||||
/// @brief Factory: Not supported
|
||||
template <typename... Args>
|
||||
static Status NotSupported(Args &&...args) {
|
||||
return Status(StatusCode::NOT_SUPPORTED,
|
||||
concat(std::forward<Args>(args)...));
|
||||
}
|
||||
|
||||
// Add more factories as needed...
|
||||
|
||||
private:
|
||||
/// @brief Ensure non-OK status has non-empty message (optional)
|
||||
static void ensure_not_ok(StatusCode /*code*/) noexcept {
|
||||
// Optional: assert(code == StatusCode::OK || "non-OK status should have
|
||||
// message")
|
||||
}
|
||||
|
||||
/// @brief Helper: concatenate any number of arguments into a string
|
||||
template <typename... Args>
|
||||
static std::string concat(Args &&...args) {
|
||||
return ailego::StringHelper::Concat(std::forward<Args>(args)...);
|
||||
}
|
||||
|
||||
StatusCode code_;
|
||||
std::string msg_;
|
||||
};
|
||||
|
||||
} // namespace zvec
|
||||
@@ -0,0 +1,201 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
#pragma once
|
||||
|
||||
#include <ailego/logger/logger.h>
|
||||
#include "error_code.h"
|
||||
|
||||
using idx_t = uint64_t;
|
||||
|
||||
#define PROXIMA_DISALLOW_COPY_AND_ASSIGN(TypeName) \
|
||||
TypeName(const TypeName &) = delete; \
|
||||
TypeName &operator=(const TypeName &) = delete;
|
||||
|
||||
|
||||
#define COLLECTION_FORMAT " collection[%s] "
|
||||
|
||||
#define CLOG_DEBUG(format, ...) \
|
||||
LOG_DEBUG(format COLLECTION_FORMAT, ##__VA_ARGS__, collection_name().c_str())
|
||||
|
||||
#define CLOG_INFO(format, ...) \
|
||||
LOG_INFO(format COLLECTION_FORMAT, ##__VA_ARGS__, collection_name().c_str())
|
||||
|
||||
#define CLOG_WARN(format, ...) \
|
||||
LOG_WARN(format COLLECTION_FORMAT, ##__VA_ARGS__, collection_name().c_str())
|
||||
|
||||
#define CLOG_ERROR(format, ...) \
|
||||
LOG_ERROR(format COLLECTION_FORMAT, ##__VA_ARGS__, collection_name().c_str())
|
||||
|
||||
#define CLOG_FATAL(format, ...) \
|
||||
LOG_FATAL(format COLLECTION_FORMAT, ##__VA_ARGS__, collection_name().c_str())
|
||||
|
||||
#define ELOG_ERROR(format, ...) \
|
||||
LOG_ERROR(format " errno[%s] ", ##__VA_ARGS__, std::strerror(errno))
|
||||
|
||||
#define WAL_FORMAT " wal_path_[%s] "
|
||||
|
||||
#define WLOG_DEBUG(format, ...) \
|
||||
LOG_DEBUG(format WAL_FORMAT, ##__VA_ARGS__, wal_path_.c_str())
|
||||
|
||||
#define WLOG_INFO(format, ...) \
|
||||
LOG_INFO(format WAL_FORMAT, ##__VA_ARGS__, wal_path_.c_str())
|
||||
|
||||
|
||||
#define WLOG_WARN(format, ...) \
|
||||
LOG_WARN(format WAL_FORMAT, ##__VA_ARGS__, wal_path_.c_str())
|
||||
|
||||
#define WLOG_ERROR(format, ...) \
|
||||
LOG_ERROR(format WAL_FORMAT, ##__VA_ARGS__, wal_path_.c_str())
|
||||
|
||||
#define WLOG_FATAL(format, ...) \
|
||||
LOG_FATAL(format WAL_FORMAT, ##__VA_ARGS__, wal_path_.c_str())
|
||||
|
||||
#define SEGMENT_FORMAT " segment[%zu] collection[%s] "
|
||||
|
||||
#define SLOG_DEBUG(format, ...) \
|
||||
LOG_DEBUG(format SEGMENT_FORMAT, ##__VA_ARGS__, (size_t)segment_id(), \
|
||||
collection_name().c_str())
|
||||
|
||||
#define SLOG_INFO(format, ...) \
|
||||
LOG_INFO(format SEGMENT_FORMAT, ##__VA_ARGS__, (size_t)segment_id(), \
|
||||
collection_name().c_str())
|
||||
|
||||
#define SLOG_WARN(format, ...) \
|
||||
LOG_WARN(format SEGMENT_FORMAT, ##__VA_ARGS__, (size_t)segment_id(), \
|
||||
collection_name().c_str())
|
||||
|
||||
#define SLOG_ERROR(format, ...) \
|
||||
LOG_ERROR(format SEGMENT_FORMAT, ##__VA_ARGS__, (size_t)segment_id(), \
|
||||
collection_name().c_str())
|
||||
|
||||
#define SLOG_FATAL(format, ...) \
|
||||
LOG_FATAL(format SEGMENT_FORMAT, ##__VA_ARGS__, (size_t)segment_id(), \
|
||||
collection_name().c_str())
|
||||
|
||||
#define COLUMN_FORMAT " column[%s] segment[%zu] collection[%s] "
|
||||
|
||||
#define LLOG_DEBUG(format, ...) \
|
||||
LOG_DEBUG(format COLUMN_FORMAT, ##__VA_ARGS__, column_name().c_str(), \
|
||||
(size_t)segment_id(), collection_name().c_str())
|
||||
|
||||
#define LLOG_INFO(format, ...) \
|
||||
LOG_INFO(format COLUMN_FORMAT, ##__VA_ARGS__, column_name().c_str(), \
|
||||
(size_t)segment_id(), collection_name().c_str())
|
||||
|
||||
#define LLOG_WARN(format, ...) \
|
||||
LOG_WARN(format COLUMN_FORMAT, ##__VA_ARGS__, column_name().c_str(), \
|
||||
(size_t)segment_id(), collection_name().c_str())
|
||||
|
||||
#define LLOG_ERROR(format, ...) \
|
||||
LOG_ERROR(format COLUMN_FORMAT, ##__VA_ARGS__, column_name().c_str(), \
|
||||
(size_t)segment_id(), collection_name().c_str())
|
||||
|
||||
#define LLOG_FATAL(format, ...) \
|
||||
LOG_FATAL(format COLUMN_FORMAT, ##__VA_ARGS__, column_name().c_str(), \
|
||||
(size_t)segment_id(), collection_name().c_str())
|
||||
|
||||
#define CHECK_STATUS(status, expect) \
|
||||
if (status != expect) { \
|
||||
LOG_ERROR("Check status failed. status[%d] expect[%d]", status, expect); \
|
||||
return PROXIMA_ZVEC_ERROR_CODE(StatusError); \
|
||||
}
|
||||
|
||||
#define CHECK_STATUS_CLOSURE(status, expect) \
|
||||
if (status != expect) { \
|
||||
LOG_ERROR("Check status failed. status[%d] expect[%d]", status, expect); \
|
||||
done->set_code(PROXIMA_ZVEC_ERROR_CODE(StatusError)); \
|
||||
return; \
|
||||
}
|
||||
|
||||
#define CHECK_RETURN(ret, expect_ret) \
|
||||
if (ret != expect_ret) { \
|
||||
return ret; \
|
||||
}
|
||||
|
||||
#define CHECK_RETURN_WITH_LOG(ret, expect_ret, format, ...) \
|
||||
if (ret != expect_ret) { \
|
||||
LOG_ERROR(format, ##__VA_ARGS__); \
|
||||
return ret; \
|
||||
}
|
||||
|
||||
#define CHECK_RETURN_WITH_CLOG(ret, expect_ret, format, ...) \
|
||||
if (ret != expect_ret) { \
|
||||
CLOG_ERROR(format, ##__VA_ARGS__); \
|
||||
return ret; \
|
||||
}
|
||||
|
||||
#define CHECK_RETURN_WITH_SLOG(ret, expect_ret, format, ...) \
|
||||
if (ret != expect_ret) { \
|
||||
SLOG_ERROR(format, ##__VA_ARGS__); \
|
||||
return ret; \
|
||||
}
|
||||
|
||||
#define CHECK_RETURN_WITH_LLOG(ret, expect_ret, format, ...) \
|
||||
if (ret != expect_ret) { \
|
||||
LLOG_ERROR(format, ##__VA_ARGS__); \
|
||||
return ret; \
|
||||
}
|
||||
|
||||
#define CHECK_DESTROY_RETURN_STATUS(status, expect) \
|
||||
if (status != expect) { \
|
||||
LOG_ERROR("Collection[%s] is already destroyed.", \
|
||||
schema_->name().c_str()); \
|
||||
return Status::InvalidArgument("collection is already destroyed."); \
|
||||
}
|
||||
|
||||
#define CHECK_DESTROY_RETURN_STATUS_EXPECTED(status, expect) \
|
||||
if (status != expect) { \
|
||||
LOG_ERROR("Collection[%s] is already destroyed.", \
|
||||
schema_->name().c_str()); \
|
||||
return tl::make_unexpected( \
|
||||
Status::InvalidArgument("collection is already destroyed.")); \
|
||||
}
|
||||
|
||||
#define CHECK_RETURN_STATUS(status) \
|
||||
if (!status.ok()) { \
|
||||
return status; \
|
||||
}
|
||||
|
||||
#define CHECK_RETURN_STATUS_EXPECTED(status) \
|
||||
if (!status.ok()) { \
|
||||
return tl::make_unexpected(status); \
|
||||
}
|
||||
|
||||
#define CHECK_COLLECTION_READONLY_RETURN_STATUS \
|
||||
CHECK_READONLY_RETURN_STATUS(Collection)
|
||||
|
||||
#define CHECK_SEGMENT_READONLY_RETURN_STATUS \
|
||||
CHECK_READONLY_RETURN_STATUS(Segment)
|
||||
|
||||
#define CHECK_READONLY_RETURN_STATUS(type) \
|
||||
if (options_.read_only_) { \
|
||||
return Status::InvalidArgument(#type \
|
||||
" is " \
|
||||
"opened in read-only " \
|
||||
"mode"); \
|
||||
}
|
||||
|
||||
#define CHECK_COLLECTION_READONLY_RETURN_STATUS_EXPECTED \
|
||||
CHECK_READONLY_RETURN_STATUS_EXPECTED(Collection)
|
||||
|
||||
#define CHECK_SEGMENT_READONLY_RETURN_STATUS_EXPECTED \
|
||||
CHECK_READONLY_RETURN_STATUS_EXPECTED(Segment)
|
||||
|
||||
#define CHECK_READONLY_RETURN_STATUS_EXPECTED(type) \
|
||||
if (options_.read_only_) { \
|
||||
return tl::make_unexpected(Status::InvalidArgument(#type \
|
||||
" is " \
|
||||
"opened in read-only " \
|
||||
"mode")); \
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
// 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"
|
||||
|
||||
namespace zvec {
|
||||
|
||||
std::string indent(int level) {
|
||||
return std::string(level * 2, ' ');
|
||||
}
|
||||
|
||||
} // namespace zvec
|
||||
@@ -0,0 +1,19 @@
|
||||
// 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 <string>
|
||||
|
||||
namespace zvec {
|
||||
std::string indent(int level);
|
||||
|
||||
} // namespace zvec
|
||||
@@ -0,0 +1,16 @@
|
||||
include(${PROJECT_ROOT_DIR}/cmake/bazel.cmake)
|
||||
include(${PROJECT_ROOT_DIR}/cmake/option.cmake)
|
||||
|
||||
cc_library(
|
||||
NAME zvec_index STATIC STRICT
|
||||
SRCS *.cc segment/*.cc column/vector_column/*.cc column/inverted_column/*.cc storage/*.cc storage/wal/*.cc common/*.cc
|
||||
LIBS zvec_common
|
||||
zvec_proto
|
||||
rocksdb
|
||||
core_interface
|
||||
Arrow::arrow_static
|
||||
Arrow::arrow_compute
|
||||
Arrow::arrow_dataset
|
||||
INCS . ${CMAKE_SOURCE_DIR}/src
|
||||
VERSION "${PROXIMA_ZVEC_VERSION}"
|
||||
)
|
||||
@@ -0,0 +1,25 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <memory>
|
||||
|
||||
namespace zvec {
|
||||
class ColumnIndexer {
|
||||
public:
|
||||
using Ptr = std::shared_ptr<ColumnIndexer>;
|
||||
};
|
||||
|
||||
} // namespace zvec
|
||||
@@ -0,0 +1,68 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
#pragma once
|
||||
|
||||
#include <memory>
|
||||
#include "db/common/typedef.h"
|
||||
#include "db/index/column/vector_column/vector_column_params.h"
|
||||
|
||||
namespace zvec {
|
||||
|
||||
class IndexResults {
|
||||
public:
|
||||
using Ptr = std::shared_ptr<IndexResults>;
|
||||
class Iterator {
|
||||
public:
|
||||
virtual ~Iterator() = default;
|
||||
|
||||
virtual idx_t doc_id() const = 0;
|
||||
|
||||
virtual float score() const = 0;
|
||||
|
||||
virtual void next() = 0;
|
||||
|
||||
virtual bool valid() const = 0;
|
||||
|
||||
virtual const std::string &group_id() const {
|
||||
return kEmpty;
|
||||
}
|
||||
|
||||
virtual const vector_column_params::VectorData vector() const {
|
||||
return vector_column_params::VectorData{};
|
||||
}
|
||||
|
||||
bool is_sparse() const {
|
||||
return is_sparse_;
|
||||
}
|
||||
bool set_is_sparse(bool is_sparse) {
|
||||
is_sparse_ = is_sparse;
|
||||
return true;
|
||||
}
|
||||
|
||||
private:
|
||||
bool is_sparse_{false};
|
||||
inline static const std::string kEmpty{""};
|
||||
};
|
||||
using IteratorUPtr = std::unique_ptr<IndexResults::Iterator>;
|
||||
|
||||
public:
|
||||
virtual ~IndexResults() = default;
|
||||
|
||||
virtual size_t count() const = 0;
|
||||
|
||||
virtual IteratorUPtr create_iterator() = 0;
|
||||
};
|
||||
|
||||
|
||||
} // namespace zvec
|
||||
@@ -0,0 +1,382 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
|
||||
#pragma once
|
||||
|
||||
|
||||
#include <string>
|
||||
#include <ailego/logger/logger.h>
|
||||
#include <roaring/roaring.h>
|
||||
#include "db/common/constants.h"
|
||||
#include "db/common/status.h"
|
||||
#include "db/index/common/type.h"
|
||||
|
||||
|
||||
namespace zvec {
|
||||
|
||||
|
||||
/*
|
||||
*
|
||||
* This class provides encoding/decoding functionality for inverted index data.
|
||||
*
|
||||
*
|
||||
* RocksDB stores key-value pairs as byte strings. Therefore, all data types
|
||||
* must be converted to a string format for storage.
|
||||
*
|
||||
* To ensure correct lexicographic sorting of numeric values (integers and
|
||||
* floating-point numbers), we need to transform them so that their byte
|
||||
* representation sorts in the same order as their numerical values.
|
||||
*
|
||||
*
|
||||
* The codec also manages storage of mapped document IDs, using either list or
|
||||
* bitmap structures depending on the data size for optimal storage efficiency.
|
||||
*
|
||||
*/
|
||||
class InvertedIndexCodec {
|
||||
public:
|
||||
static std::string Encode(const std::string &term, DataType type) {
|
||||
switch (type) {
|
||||
case DataType::INT32:
|
||||
case DataType::INT64: {
|
||||
auto result = term;
|
||||
convert_to_big_endian(result.data(), result.size());
|
||||
// For signed, reverse sign bit, set positive to 1, negative to 0
|
||||
result[0] ^= 0x80;
|
||||
return result;
|
||||
}
|
||||
case DataType::UINT32:
|
||||
case DataType::UINT64: {
|
||||
auto result = term;
|
||||
convert_to_big_endian(result.data(), result.size());
|
||||
return result;
|
||||
}
|
||||
case DataType::FLOAT:
|
||||
case DataType::DOUBLE: {
|
||||
auto result = term;
|
||||
convert_to_big_endian(result.data(), result.size());
|
||||
// If float is negative, negate each byte; else reverse sign bit
|
||||
if ((result[0] & 0x80) > 0) {
|
||||
for (size_t i = 0; i < result.size(); i++) {
|
||||
result[i] = ~result[i];
|
||||
}
|
||||
} else {
|
||||
result[0] ^= 0x80;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
default:
|
||||
return term;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
static std::string Encode(const std::string_view &term, DataType type) {
|
||||
switch (type) {
|
||||
case DataType::INT32:
|
||||
case DataType::INT64: {
|
||||
std::string result(term);
|
||||
convert_to_big_endian(result.data(), result.size());
|
||||
// For signed, reverse sign bit, set positive to 1, negative to 0
|
||||
result[0] ^= 0x80;
|
||||
return result;
|
||||
}
|
||||
case DataType::UINT32:
|
||||
case DataType::UINT64: {
|
||||
std::string result(term);
|
||||
convert_to_big_endian(result.data(), result.size());
|
||||
return result;
|
||||
}
|
||||
case DataType::FLOAT:
|
||||
case DataType::DOUBLE: {
|
||||
std::string result(term);
|
||||
convert_to_big_endian(result.data(), result.size());
|
||||
// If float is negative, negate each byte; else reverse sign bit
|
||||
if ((result[0] & 0x80) > 0) {
|
||||
for (size_t i = 0; i < result.size(); i++) {
|
||||
result[i] = ~result[i];
|
||||
}
|
||||
} else {
|
||||
result[0] ^= 0x80;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
default:
|
||||
return std::string(term);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
static std::string Encode(bool value) {
|
||||
if (value) {
|
||||
return "true";
|
||||
} else {
|
||||
return "false";
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
static std::string Encode_Reversed(const std::string &term) {
|
||||
std::string reversed = term;
|
||||
std::reverse(reversed.begin(), reversed.end());
|
||||
return reversed;
|
||||
}
|
||||
|
||||
|
||||
// Format of range key:
|
||||
// [range_begin_key][separator_byte][range_end_key][range_begin_key_size]
|
||||
static void Decode_Range_Key(const char *range_key_ptr, size_t range_key_size,
|
||||
char **range_begin_pos,
|
||||
size_t *range_begin_key_size,
|
||||
char **range_end_pos,
|
||||
size_t *range_end_key_size) {
|
||||
*range_begin_key_size =
|
||||
*(uint64_t *)(range_key_ptr + (range_key_size - sizeof(uint64_t)));
|
||||
*range_begin_pos = (char *)range_key_ptr;
|
||||
|
||||
*range_end_key_size =
|
||||
range_key_size - sizeof(uint64_t) - (*range_begin_key_size) - 1;
|
||||
*range_end_pos = (char *)(range_key_ptr + (*range_begin_key_size) + 1);
|
||||
}
|
||||
|
||||
|
||||
// Return negative number if s1 < s2, positive number if s1 > s2, 0 if equal
|
||||
static int CMP(const char *s1, size_t s1_len, const char *s2, size_t s2_len) {
|
||||
size_t min_len = std::min(s1_len, s2_len);
|
||||
int r = memcmp(s1, s2, min_len);
|
||||
if (r == 0) {
|
||||
if (s1_len < s2_len)
|
||||
r = -1;
|
||||
else if (s1_len > s2_len)
|
||||
r = +1;
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
|
||||
static bool Has_Prefix(const char *value, size_t value_len,
|
||||
const char *prefix, size_t prefix_len) {
|
||||
if (value_len < prefix_len) {
|
||||
return false;
|
||||
}
|
||||
return memcmp(value, prefix, prefix_len) == 0;
|
||||
}
|
||||
|
||||
|
||||
static Status Serialize(roaring_bitmap_t *bitmap, std::string *out) {
|
||||
if (!bitmap) {
|
||||
LOG_ERROR("Invalid bitmap pointer");
|
||||
return Status::InvalidArgument();
|
||||
}
|
||||
if (!out) {
|
||||
LOG_ERROR("Invalid output pointer");
|
||||
return Status::InvalidArgument();
|
||||
}
|
||||
out->clear();
|
||||
|
||||
uint64_t count = roaring_bitmap_get_cardinality(bitmap);
|
||||
if (count == 0) {
|
||||
LOG_ERROR("Bitmap is empty");
|
||||
return Status::InternalError();
|
||||
} else if (count > INVERT_ID_LIST_SIZE_THRESHOLD) {
|
||||
return serialize_bitmap(bitmap, out);
|
||||
} else {
|
||||
return serialize_docid_list(bitmap, out);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
static Status Deserialize(const char *data, size_t size,
|
||||
roaring_bitmap_t **bitmap) {
|
||||
if (!data || size == 0) {
|
||||
LOG_ERROR("Input data is invalid");
|
||||
return Status::InvalidArgument();
|
||||
}
|
||||
|
||||
unsigned char header = data[0];
|
||||
if (header > INVERT_ID_LIST_SIZE_THRESHOLD) {
|
||||
LOG_ERROR("Invalid header found in inverted data");
|
||||
return Status::InternalError();
|
||||
}
|
||||
|
||||
if (header == 0) { // This is a bitmap
|
||||
*bitmap = roaring_bitmap_portable_deserialize_safe(data + 1, size - 1);
|
||||
if (*bitmap) {
|
||||
return Status::OK();
|
||||
} else {
|
||||
LOG_ERROR("Failed to deserialize bitmap");
|
||||
return Status::InternalError();
|
||||
}
|
||||
}
|
||||
|
||||
// This is a id list
|
||||
if ((size - 1) != header * sizeof(uint32_t)) {
|
||||
LOG_ERROR("Failed to deserialize docid_list");
|
||||
return Status::InternalError();
|
||||
}
|
||||
*bitmap = roaring_bitmap_create();
|
||||
if (*bitmap == nullptr) {
|
||||
LOG_ERROR("Failed to create bitmap");
|
||||
return Status::InternalError();
|
||||
}
|
||||
for (size_t i = 1; i < size; i += sizeof(uint32_t)) {
|
||||
roaring_bitmap_add(*bitmap,
|
||||
*reinterpret_cast<const uint32_t *>(data + i));
|
||||
}
|
||||
return Status::OK();
|
||||
}
|
||||
|
||||
|
||||
static Status Merge_OR(const char *data, size_t size, bool lazy,
|
||||
roaring_bitmap_t *bitmap) {
|
||||
if (!data || size == 0) {
|
||||
LOG_ERROR("Input data is invalid");
|
||||
return Status::InvalidArgument();
|
||||
}
|
||||
|
||||
unsigned char header = data[0];
|
||||
if (header > INVERT_ID_LIST_SIZE_THRESHOLD) {
|
||||
LOG_ERROR("Invalid header found in inverted data");
|
||||
return Status::InternalError();
|
||||
}
|
||||
|
||||
if (header == 0) { // This is a bitmap
|
||||
auto bitmap_other = roaring_bitmap_portable_deserialize_frozen(data + 1);
|
||||
if (!bitmap_other) {
|
||||
LOG_ERROR("Failed to deserialize bitmap");
|
||||
return Status::InternalError();
|
||||
}
|
||||
if (lazy) {
|
||||
roaring_bitmap_lazy_or_inplace(bitmap, bitmap_other, true);
|
||||
} else {
|
||||
roaring_bitmap_or_inplace(bitmap, bitmap_other);
|
||||
}
|
||||
roaring_bitmap_free(bitmap_other);
|
||||
return Status::OK();
|
||||
}
|
||||
|
||||
// This is a id list
|
||||
if ((size - 1) != header * sizeof(uint32_t)) {
|
||||
LOG_ERROR("Failed to deserialize docid_list");
|
||||
return Status::InternalError();
|
||||
}
|
||||
auto doc_list = reinterpret_cast<const uint32_t *>(data + 1);
|
||||
for (size_t i = 0; i < header; ++i) {
|
||||
roaring_bitmap_add(bitmap, doc_list[i]);
|
||||
}
|
||||
return Status::OK();
|
||||
}
|
||||
|
||||
|
||||
static Status Merge_AND(const char *data, size_t size,
|
||||
roaring_bitmap_t *bitmap) {
|
||||
if (!data || size == 0) {
|
||||
LOG_ERROR("Input data is invalid");
|
||||
return Status::InvalidArgument();
|
||||
}
|
||||
|
||||
unsigned char header = data[0];
|
||||
if (header > INVERT_ID_LIST_SIZE_THRESHOLD) {
|
||||
LOG_ERROR("Invalid header found in inverted data");
|
||||
return Status::InternalError();
|
||||
}
|
||||
|
||||
if (header == 0) { // This is a bitmap
|
||||
auto bitmap_other = roaring_bitmap_portable_deserialize_frozen(data + 1);
|
||||
if (!bitmap_other) {
|
||||
LOG_ERROR("Failed to deserialize bitmap");
|
||||
return Status::InternalError();
|
||||
}
|
||||
roaring_bitmap_and_inplace(bitmap, bitmap_other);
|
||||
roaring_bitmap_free(bitmap_other);
|
||||
return Status::OK();
|
||||
}
|
||||
|
||||
// This is a id list
|
||||
if ((size - 1) != header * sizeof(uint32_t)) {
|
||||
LOG_ERROR("Failed to deserialize docid_list");
|
||||
return Status::InternalError();
|
||||
}
|
||||
auto doc_list = reinterpret_cast<const uint32_t *>(data + 1);
|
||||
uint32_t tmp = 0;
|
||||
for (size_t i = 0; i < header; ++i) {
|
||||
tmp |= roaring_bitmap_contains(bitmap, doc_list[i]) << i;
|
||||
}
|
||||
roaring_bitmap_clear(bitmap);
|
||||
for (size_t i = 0; i < header; ++i) {
|
||||
if (tmp & (1 << i)) {
|
||||
roaring_bitmap_add(bitmap, doc_list[i]);
|
||||
}
|
||||
}
|
||||
return Status::OK();
|
||||
}
|
||||
|
||||
|
||||
private:
|
||||
static void convert_to_big_endian(char *in, size_t size) {
|
||||
static const bool isBigEndianSystem = []() {
|
||||
int i = 0x1243;
|
||||
char *ch = (char *)&i;
|
||||
return (*ch == 0x12);
|
||||
}();
|
||||
|
||||
if (isBigEndianSystem) {
|
||||
return;
|
||||
}
|
||||
|
||||
char *p = in;
|
||||
for (size_t i = 0; i < size / 2; ++i) {
|
||||
std::swap(p[i], p[size - i - 1]);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
static Status serialize_bitmap(const roaring_bitmap_t *bitmap,
|
||||
std::string *out) {
|
||||
size_t bitmap_size = roaring_bitmap_portable_size_in_bytes(bitmap);
|
||||
out->resize(1 + bitmap_size);
|
||||
|
||||
// Set the first byte with value 0, indicating the data is a bitmap
|
||||
(*out)[0] = static_cast<char>(0);
|
||||
size_t written_size = roaring_bitmap_portable_serialize(
|
||||
bitmap, const_cast<char *>(out->data()) + 1);
|
||||
if (written_size == bitmap_size) {
|
||||
return Status::OK();
|
||||
} else {
|
||||
LOG_ERROR("Failed to serialize bitmap");
|
||||
return Status::InternalError();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
static Status serialize_docid_list(const roaring_bitmap_t *bitmap,
|
||||
std::string *out) {
|
||||
auto doc_count = roaring_bitmap_get_cardinality(bitmap);
|
||||
out->reserve(1 + doc_count * sizeof(uint32_t));
|
||||
// Adds a single byte at the beginning indicating the count of document IDs
|
||||
out->append(1, static_cast<unsigned char>(doc_count));
|
||||
|
||||
auto iter = roaring_create_iterator(bitmap);
|
||||
while (iter->has_value) {
|
||||
out->append(reinterpret_cast<const char *>(&(iter->current_value)),
|
||||
sizeof(uint32_t));
|
||||
roaring_advance_uint32_iterator(iter);
|
||||
}
|
||||
roaring_free_uint32_iterator(iter);
|
||||
return Status::OK();
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
} // namespace zvec
|
||||
@@ -0,0 +1,435 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
|
||||
#pragma once
|
||||
|
||||
|
||||
#include <ailego/pattern/expected.hpp>
|
||||
#include "db/common/concurrent_roaring_bitmap.h"
|
||||
#include "db/common/rocksdb_context.h"
|
||||
#include "db/index/common/schema.h"
|
||||
#include "inverted_codec.h"
|
||||
#include "inverted_doc_range.h"
|
||||
#include "inverted_search_result.h"
|
||||
|
||||
|
||||
namespace zvec {
|
||||
|
||||
|
||||
//
|
||||
// An inverted column indexer manages document-term indexing in two states:
|
||||
// 1. Streaming:
|
||||
// - allows insertion of new terms and indexing of document-term pairs
|
||||
// 2. Sealed:
|
||||
// - read-only, no further writes permitted
|
||||
// - statistical index generated for optimized search performance
|
||||
//
|
||||
//
|
||||
// InvertedColumnIndexer requires document IDs to be sequential integers
|
||||
// starting from 0 without any gaps.
|
||||
// While documents can be inserted in any order, the complete sequence from 0 to
|
||||
// max id must be present before sealing the index.
|
||||
//
|
||||
// Multiple inverted column indexers share the same RocksDB instance but each
|
||||
// indexer uses its own RocksDB column families within that shared RocksDB
|
||||
// instance. This design allows for efficient resource utilization while
|
||||
// maintaining data separation between different columns.
|
||||
//
|
||||
class InvertedColumnIndexer {
|
||||
public:
|
||||
using Ptr = std::shared_ptr<InvertedColumnIndexer>;
|
||||
|
||||
|
||||
static Ptr CreateAndOpen(const std::string &collection_name,
|
||||
const FieldSchema &field, RocksdbContext &context,
|
||||
bool read_only = false);
|
||||
|
||||
|
||||
virtual ~InvertedColumnIndexer();
|
||||
|
||||
|
||||
protected:
|
||||
explicit InvertedColumnIndexer(const std::string &collection_name,
|
||||
const FieldSchema &field,
|
||||
RocksdbContext &context, bool read_only)
|
||||
: collection_name_(collection_name),
|
||||
field_(field),
|
||||
path_(context.db_path_),
|
||||
ctx_(context),
|
||||
read_only_(read_only) {};
|
||||
|
||||
InvertedColumnIndexer(const InvertedColumnIndexer &) = delete;
|
||||
InvertedColumnIndexer(InvertedColumnIndexer &&) = delete;
|
||||
InvertedColumnIndexer &operator=(const InvertedColumnIndexer &) = delete;
|
||||
InvertedColumnIndexer &operator=(InvertedColumnIndexer &&) = delete;
|
||||
|
||||
|
||||
// TODO: for ut, remove this
|
||||
InvertedColumnIndexer(RocksdbContext &ctx) : ctx_(ctx) {}
|
||||
|
||||
|
||||
public:
|
||||
/*!
|
||||
* \brief Search for documents matching the given value and operation
|
||||
* \param value The value to compare against (e.g., "5", "10")
|
||||
* \param op The comparison operation (e.g., EQ, GT, LT)
|
||||
* \return Pointer to search results containing matching documents
|
||||
*/
|
||||
virtual InvertedSearchResult::Ptr search(const std::string &value,
|
||||
CompareOp op) const;
|
||||
|
||||
|
||||
/*!
|
||||
* \brief Search for documents matching multiple values
|
||||
* \param values List of values to compare against (e.g., {"5", "10", "15"})
|
||||
* \param comp_op The comparison operation to apply (e.g., CONTAIN_ANY)
|
||||
* \return Pointer to search results containing matching documents
|
||||
*/
|
||||
virtual InvertedSearchResult::Ptr multi_search(
|
||||
const std::vector<std::string> &values, CompareOp op) const;
|
||||
|
||||
|
||||
/*!
|
||||
* \brief Search for documents matching array length
|
||||
* \param len The array length value to compare against
|
||||
* \param op The comparison operation to apply (e.g., EQ)
|
||||
* \return Pointer to search results containing matching documents
|
||||
*/
|
||||
virtual InvertedSearchResult::Ptr search_array_len(uint32_t len,
|
||||
CompareOp op) const;
|
||||
|
||||
|
||||
/*!
|
||||
* \brief Search for documents that have null values
|
||||
* \return Pointer to search results containing matching documents
|
||||
*/
|
||||
virtual InvertedSearchResult::Ptr search_null() const;
|
||||
|
||||
|
||||
/*!
|
||||
* \brief Search for documents that have non-null values
|
||||
* \return Pointer to search results containing matching documents
|
||||
*/
|
||||
virtual InvertedSearchResult::Ptr search_non_null() const;
|
||||
|
||||
|
||||
/*!
|
||||
* \brief Evaluate the ratio of matching documents compared to total documents
|
||||
* \param value The value to compare against (e.g., "5", "10")
|
||||
* \param op The comparison operation (e.g., EQ, GT, LT)
|
||||
* \param total_size Pointer to store the total number of documents
|
||||
* \param range_size Pointer to store the number of matching documents
|
||||
* \return Status indicating success or failure of the evaluation
|
||||
*/
|
||||
virtual Status evaluate_ratio(const std::string &value, CompareOp op,
|
||||
uint64_t *total_size,
|
||||
uint64_t *range_size) const;
|
||||
|
||||
|
||||
/*!
|
||||
* \brief Insert a document-term pair into the inverted index
|
||||
* \param id The document ID to insert
|
||||
* \param value The string-encoded representation of the value to index. This
|
||||
* parameter may contain either a single value or an array of
|
||||
* values depending on the field type. The underlying data type
|
||||
* might differ from std::string - the string serves as a generic
|
||||
* serialization buffer for the actual typed data.
|
||||
* \return Status indicating success or failure of the insert operation
|
||||
*/
|
||||
Status insert(uint32_t id, const std::string &value);
|
||||
|
||||
|
||||
/*!
|
||||
* \brief Insert a document with multiple strings into the inverted index
|
||||
* \param id The document ID to insert
|
||||
* \param values Multiple string values to index
|
||||
* \return Status indicating success or failure of the insert operation
|
||||
*/
|
||||
Status insert(uint32_t id, const std::vector<std::string> &values);
|
||||
|
||||
|
||||
/*!
|
||||
* \brief Insert a document with a boolean value into the inverted index
|
||||
* \param id The document ID to insert
|
||||
* \param value The boolean value to index
|
||||
* \return Status indicating success or failure of the insert operation
|
||||
*/
|
||||
Status insert(uint32_t id, bool value);
|
||||
|
||||
|
||||
/*!
|
||||
* \brief Insert a document with multiple booleans into the inverted index
|
||||
* \param id The document ID to insert
|
||||
* \param value Multiple boolean values to index
|
||||
* \return Status indicating success or failure of the insert operation
|
||||
*/
|
||||
Status insert(uint32_t id, const std::vector<bool> &values);
|
||||
|
||||
|
||||
/*!
|
||||
* \brief Insert a document with null value into the inverted index
|
||||
* \param id The document ID to insert
|
||||
* \return Status indicating success or failure of the insert operation
|
||||
*/
|
||||
Status insert_null(uint32_t id);
|
||||
|
||||
|
||||
/*!
|
||||
* \brief Serialize special values, e.g., null-value bitmap and max doc id
|
||||
* \return Status indicating success or failure of the serialization
|
||||
*/
|
||||
Status flush_special_values();
|
||||
|
||||
|
||||
/*!
|
||||
* \brief Seal the index and generate statistical indexes
|
||||
* \return Status indicating success or failure of the operation
|
||||
*/
|
||||
Status seal();
|
||||
|
||||
|
||||
/*!
|
||||
* \brief Check if the index is sealed
|
||||
* \return True if the index is sealed, false otherwise
|
||||
*/
|
||||
inline bool is_sealed() const {
|
||||
return sealed_;
|
||||
}
|
||||
|
||||
|
||||
/*!
|
||||
* \brief Drop the index storage
|
||||
* \return Status indicating success or failure of the operation
|
||||
*/
|
||||
Status drop_storage();
|
||||
|
||||
|
||||
/*!
|
||||
* \brief Get the name of the corresponding collection
|
||||
* \return The name of the corresponding collection
|
||||
*/
|
||||
inline const std::string &collection_name() const {
|
||||
return collection_name_;
|
||||
}
|
||||
|
||||
|
||||
inline const std::string ID() const {
|
||||
return "InvertedColumnIndexer[collection:" + collection_name_ +
|
||||
"|field:" + field_.name() + "|path:'" + path_ + "']";
|
||||
}
|
||||
|
||||
|
||||
private:
|
||||
using Slice = rocksdb::Slice;
|
||||
using PinnableSlice = rocksdb::PinnableSlice;
|
||||
|
||||
|
||||
Status open();
|
||||
|
||||
inline std::string encode(const std::string &term) const {
|
||||
return InvertedIndexCodec::Encode(term, field_.element_data_type());
|
||||
}
|
||||
|
||||
inline std::vector<std::string> encode_array(const std::string &terms) const {
|
||||
std::vector<std::string> result{};
|
||||
size_t s = field_.element_data_size();
|
||||
if (s == 0) {
|
||||
return result;
|
||||
}
|
||||
size_t num_terms = terms.size() / s;
|
||||
result.reserve(num_terms);
|
||||
for (size_t i = 0; i < num_terms; ++i) {
|
||||
std::string_view sv(terms.data() + (i * s), s);
|
||||
result.emplace_back(
|
||||
InvertedIndexCodec::Encode(sv, field_.element_data_type()));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
inline std::vector<std::string> encode(
|
||||
const std::vector<std::string> &terms) const {
|
||||
std::vector<std::string> result;
|
||||
result.reserve(terms.size());
|
||||
for (auto &term : terms) {
|
||||
result.emplace_back(encode(term));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
inline std::string encode(bool value) {
|
||||
return InvertedIndexCodec::Encode(value);
|
||||
}
|
||||
|
||||
inline std::string encode_reversed(const std::string &term) const {
|
||||
return InvertedIndexCodec::Encode_Reversed(term);
|
||||
}
|
||||
|
||||
inline int cmp(const char *s1, size_t s1_len, const char *s2,
|
||||
size_t s2_len) const {
|
||||
return InvertedIndexCodec::CMP(s1, s1_len, s2, s2_len);
|
||||
}
|
||||
|
||||
inline bool cmp_lt(const char *s1, size_t s1_len, const char *s2,
|
||||
size_t s2_len, bool include_eq) const {
|
||||
int ret = InvertedIndexCodec::CMP(s1, s1_len, s2, s2_len);
|
||||
return (include_eq && ret <= 0) || (!include_eq && ret < 0);
|
||||
}
|
||||
|
||||
inline bool has_prefix(const char *value, size_t value_len,
|
||||
const char *prefix, size_t prefix_len) const {
|
||||
return InvertedIndexCodec::Has_Prefix(value, value_len, prefix, prefix_len);
|
||||
}
|
||||
|
||||
inline void update_max_id(uint32_t id) {
|
||||
uint32_t expected_id = max_id_.load();
|
||||
while (expected_id < id &&
|
||||
!max_id_.compare_exchange_weak(expected_id, id)) {
|
||||
;
|
||||
}
|
||||
}
|
||||
|
||||
inline Status estimate_range_ratio(const std::string &term, CompareOp op,
|
||||
uint64_t *total_count,
|
||||
uint64_t *matching_count) const;
|
||||
|
||||
inline bool range_covers_most_values(const std::string &term,
|
||||
CompareOp op) const;
|
||||
|
||||
inline roaring_bitmap_t *flip_bitmap(roaring_bitmap_t *bitmap) const;
|
||||
|
||||
Result<roaring_bitmap_t *> get_bitmap_eq(const std::string &term) const;
|
||||
|
||||
Result<roaring_bitmap_t *> get_bitmap_contain(
|
||||
const std::vector<std::string> &terms, bool is_any) const;
|
||||
|
||||
Result<roaring_bitmap_t *> get_bitmap_ne(const std::string &term) const;
|
||||
|
||||
Result<roaring_bitmap_t *> get_bitmap_not_contain(
|
||||
const std::vector<std::string> &terms, bool is_any) const;
|
||||
|
||||
Result<roaring_bitmap_t *> get_bitmap_lt(const std::string &term,
|
||||
bool include_eq) const;
|
||||
|
||||
Result<roaring_bitmap_t *> get_bitmap_gt(const std::string &term,
|
||||
bool include_eq) const;
|
||||
|
||||
Result<roaring_bitmap_t *> get_bitmap_array_len_eq(uint32_t len) const;
|
||||
|
||||
Result<roaring_bitmap_t *> get_bitmap_array_len_ne(uint32_t len) const;
|
||||
|
||||
Result<roaring_bitmap_t *> get_bitmap_array_len_lt(uint32_t len,
|
||||
bool include_eq) const;
|
||||
|
||||
Result<roaring_bitmap_t *> get_bitmap_array_len_gt(uint32_t len,
|
||||
bool include_eq) const;
|
||||
|
||||
Result<roaring_bitmap_t *> get_bitmap_like(std::string term) const;
|
||||
|
||||
Result<roaring_bitmap_t *> get_bitmap_prefix(const std::string &term) const;
|
||||
|
||||
Result<roaring_bitmap_t *> get_bitmap_suffix(const std::string &term) const;
|
||||
|
||||
Result<roaring_bitmap_t *> get_bitmap_null() const;
|
||||
|
||||
Result<roaring_bitmap_t *> get_bitmap_non_null() const;
|
||||
|
||||
rocksdb::Status index_array_len(uint32_t id, uint32_t len);
|
||||
|
||||
Status generate_statistical_indexes();
|
||||
|
||||
|
||||
private:
|
||||
inline std::string cf_name_terms() const {
|
||||
return field_.name() + INVERT_SUFFIX_TERMS;
|
||||
};
|
||||
|
||||
inline std::string cf_name_reversed_terms() const {
|
||||
return field_.name() + INVERT_SUFFIX_REVERSED_TERMS;
|
||||
};
|
||||
|
||||
inline std::string cf_name_array_len() const {
|
||||
return field_.name() + INVERT_SUFFIX_ARRAY_LEN;
|
||||
};
|
||||
|
||||
inline std::string cf_name_ranges() const {
|
||||
return field_.name() + INVERT_SUFFIX_RANGES;
|
||||
};
|
||||
|
||||
inline std::string cf_name_cdf() const {
|
||||
return INVERT_CDF;
|
||||
};
|
||||
|
||||
inline std::string key_max_id() const {
|
||||
return field_.name() + INVERT_KEY_MAX_ID;
|
||||
};
|
||||
|
||||
inline std::string key_null() const {
|
||||
return field_.name() + INVERT_KEY_NULL;
|
||||
};
|
||||
|
||||
inline std::string key_sealed() const {
|
||||
return field_.name() + INVERT_KEY_SEALED;
|
||||
};
|
||||
|
||||
inline bool allow_range_optimization(const FieldSchema &field) const {
|
||||
bool not_allowed =
|
||||
field.is_array_type() || field.data_type() == DataType::BOOL;
|
||||
return !not_allowed;
|
||||
}
|
||||
|
||||
inline bool allow_extended_wildcard(const FieldSchema &field) const {
|
||||
return field.data_type() == DataType::STRING;
|
||||
}
|
||||
|
||||
|
||||
private:
|
||||
const std::string collection_name_{};
|
||||
const FieldSchema field_{};
|
||||
const std::string path_{};
|
||||
|
||||
|
||||
// Column families:
|
||||
// 1. cf_terms_: Inverted index for terms
|
||||
// 2. cf_reversed_terms_: Inverted index for reversed terms
|
||||
// 3. cf_array_len_: Inverted index for array length
|
||||
// 4. cf_ranges_: Range index
|
||||
// 5. cf_cdf_: Cumulative distribution function
|
||||
// 6. default cf: Stores special values
|
||||
// - null-value bitmap
|
||||
// - max id
|
||||
// - is_sealed
|
||||
//
|
||||
// Some column families are optional and may be nullptr.
|
||||
// For example, cf_ranges_ is nullptr when the indexer is not sealed (range
|
||||
// index not yet generated) or when range optimization is explicitly disabled.
|
||||
RocksdbContext &ctx_;
|
||||
rocksdb::ColumnFamilyHandle *cf_terms_{nullptr};
|
||||
rocksdb::ColumnFamilyHandle *cf_reversed_terms_{nullptr};
|
||||
rocksdb::ColumnFamilyHandle *cf_array_len_{nullptr};
|
||||
rocksdb::ColumnFamilyHandle *cf_ranges_{nullptr};
|
||||
rocksdb::ColumnFamilyHandle *cf_cdf_{nullptr};
|
||||
|
||||
|
||||
bool read_only_{false};
|
||||
bool sealed_{false};
|
||||
bool enable_range_optimization_{false};
|
||||
bool enable_extended_wildcard_{false};
|
||||
std::atomic<uint32_t> max_id_{0};
|
||||
ConcurrentRoaringBitmap32 null_bitmap_{};
|
||||
SegmentDocRangeStat::Ptr doc_range_stat_{nullptr};
|
||||
};
|
||||
|
||||
|
||||
}; // namespace zvec
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,207 @@
|
||||
// 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 <ailego/pattern/defer.h>
|
||||
#include "inverted_column_indexer.h"
|
||||
|
||||
|
||||
namespace zvec {
|
||||
|
||||
|
||||
InvertedColumnIndexer::~InvertedColumnIndexer() {
|
||||
LOG_INFO("Closed %s", ID().c_str());
|
||||
}
|
||||
|
||||
|
||||
Status InvertedColumnIndexer::open() {
|
||||
if (field_.index_type() != IndexType::INVERT) {
|
||||
return Status::InvalidArgument();
|
||||
}
|
||||
auto params =
|
||||
std::dynamic_pointer_cast<InvertIndexParams>(field_.index_params());
|
||||
enable_range_optimization_ =
|
||||
allow_range_optimization(field_) && params->enable_range_optimization();
|
||||
enable_extended_wildcard_ =
|
||||
allow_extended_wildcard(field_) && params->enable_extended_wildcard();
|
||||
|
||||
rocksdb::Status s;
|
||||
std::string value{};
|
||||
|
||||
cf_terms_ = ctx_.get_cf(cf_name_terms());
|
||||
if (!cf_terms_) {
|
||||
LOG_ERROR("Failed to get cf_terms for %s", ID().c_str());
|
||||
return Status::InternalError();
|
||||
}
|
||||
|
||||
if (field_.is_array_type()) {
|
||||
cf_array_len_ = ctx_.get_cf(cf_name_array_len());
|
||||
if (!cf_array_len_) {
|
||||
LOG_ERROR("Failed to get cf_array_len for %s", ID().c_str());
|
||||
return Status::InternalError();
|
||||
}
|
||||
}
|
||||
|
||||
if (enable_range_optimization_) {
|
||||
cf_ranges_ = ctx_.get_cf(cf_name_ranges());
|
||||
if (!cf_ranges_) {
|
||||
LOG_ERROR("Failed to get cf_ranges for %s", ID().c_str());
|
||||
return Status::InternalError();
|
||||
}
|
||||
cf_cdf_ = ctx_.get_cf(cf_name_cdf());
|
||||
if (!cf_cdf_) {
|
||||
LOG_ERROR("Failed to get cf_cdf for %s", ID().c_str());
|
||||
return Status::InternalError();
|
||||
}
|
||||
s = ctx_.db_->Get(ctx_.read_opts_, cf_cdf_, field_.name(), &value);
|
||||
if (s.ok()) {
|
||||
doc_range_stat_ = SegmentDocRangeStat::Create(value);
|
||||
if (!doc_range_stat_) {
|
||||
LOG_ERROR("Failed to create doc range stats from %s", ID().c_str());
|
||||
return Status::InternalError();
|
||||
}
|
||||
} else if (s.code() != rocksdb::Status::kNotFound) {
|
||||
LOG_ERROR("Failed to retrieve cdf from %s", ID().c_str());
|
||||
return Status::InternalError();
|
||||
}
|
||||
}
|
||||
|
||||
if (enable_extended_wildcard_) {
|
||||
cf_reversed_terms_ = ctx_.get_cf(cf_name_reversed_terms());
|
||||
if (!cf_reversed_terms_) {
|
||||
LOG_ERROR("Failed to get cf_reversed_terms for %s", ID().c_str());
|
||||
return Status::InternalError();
|
||||
}
|
||||
}
|
||||
|
||||
// Get max id if exists
|
||||
s = ctx_.db_->Get(ctx_.read_opts_, key_max_id(), &value);
|
||||
if (s.ok()) {
|
||||
try {
|
||||
max_id_ = std::stoul(value);
|
||||
} catch (const std::exception &e) {
|
||||
LOG_ERROR("Failed to parse max id from %s for %s, exception[%s]",
|
||||
value.c_str(), ID().c_str(), e.what());
|
||||
return Status::InternalError();
|
||||
}
|
||||
} else if (s.code() != rocksdb::Status::kNotFound) {
|
||||
LOG_ERROR("Failed to retrieve max id from %s", ID().c_str());
|
||||
return Status::InternalError();
|
||||
}
|
||||
|
||||
// Get null bitmap if exists
|
||||
s = ctx_.db_->Get(ctx_.read_opts_, key_null(), &value);
|
||||
if (s.ok()) {
|
||||
if (auto status = null_bitmap_.deserialize(value); !status.ok()) {
|
||||
LOG_ERROR("Failed to deserialize null bitmap from %s", ID().c_str());
|
||||
return status;
|
||||
}
|
||||
} else if (s.code() != rocksdb::Status::kNotFound) {
|
||||
LOG_ERROR("Failed to retrieve null bitmap from %s", ID().c_str());
|
||||
return Status::InternalError();
|
||||
}
|
||||
|
||||
// Get indexer state
|
||||
s = ctx_.db_->Get(ctx_.read_opts_, key_sealed(), &value);
|
||||
if (s.ok()) {
|
||||
sealed_ = true;
|
||||
read_only_ = true;
|
||||
} else if (s.code() == rocksdb::Status::kNotFound) {
|
||||
sealed_ = false;
|
||||
} else {
|
||||
LOG_ERROR("Failed to retrieve indexer state from %s", ID().c_str());
|
||||
return Status::InternalError();
|
||||
}
|
||||
|
||||
LOG_INFO("Opened %s", ID().c_str());
|
||||
return Status::OK();
|
||||
}
|
||||
|
||||
|
||||
InvertedColumnIndexer::Ptr InvertedColumnIndexer::CreateAndOpen(
|
||||
const std::string &collection_name, const FieldSchema &field,
|
||||
RocksdbContext &context, bool read_only) {
|
||||
auto ptr =
|
||||
new InvertedColumnIndexer(collection_name, field, context, read_only);
|
||||
auto indexer = std::shared_ptr<InvertedColumnIndexer>(ptr);
|
||||
if (indexer->open().ok()) {
|
||||
return indexer;
|
||||
} else {
|
||||
return nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Status InvertedColumnIndexer::drop_storage() {
|
||||
Status s = Status::OK();
|
||||
rocksdb::Status rs;
|
||||
AILEGO_DEFER([&]() {
|
||||
if (s.ok()) {
|
||||
LOG_INFO("Dropped storage of %s", ID().c_str());
|
||||
} else {
|
||||
LOG_ERROR("Failed to drop storage of %s", ID().c_str());
|
||||
}
|
||||
});
|
||||
|
||||
if (s = ctx_.drop_cf(cf_name_terms()); !s.ok()) {
|
||||
return s;
|
||||
}
|
||||
if (field_.is_array_type()) {
|
||||
if (s = ctx_.drop_cf(cf_name_array_len()); !s.ok()) {
|
||||
return s;
|
||||
}
|
||||
}
|
||||
if (enable_range_optimization_) {
|
||||
if (s = ctx_.drop_cf(cf_name_ranges()); !s.ok()) {
|
||||
return s;
|
||||
}
|
||||
rs = ctx_.db_->Delete(ctx_.write_opts_, cf_cdf_, field_.name());
|
||||
if (!rs.ok()) {
|
||||
LOG_ERROR("Failed to delete cdf of %s", ID().c_str());
|
||||
s = Status::InternalError();
|
||||
return s;
|
||||
}
|
||||
}
|
||||
if (enable_extended_wildcard_) {
|
||||
if (s = ctx_.drop_cf(cf_name_reversed_terms()); !s.ok()) {
|
||||
return s;
|
||||
}
|
||||
}
|
||||
|
||||
rs = ctx_.db_->Delete(ctx_.write_opts_, key_max_id());
|
||||
if (!rs.ok()) {
|
||||
LOG_ERROR("Failed to delete max_id of %s", ID().c_str());
|
||||
s = Status::InternalError();
|
||||
return s;
|
||||
}
|
||||
|
||||
rs = ctx_.db_->Delete(ctx_.write_opts_, key_null());
|
||||
if (!rs.ok()) {
|
||||
LOG_ERROR("Failed to delete null bitmap of %s", ID().c_str());
|
||||
s = Status::InternalError();
|
||||
return s;
|
||||
}
|
||||
|
||||
rs = ctx_.db_->Delete(ctx_.write_opts_, key_sealed());
|
||||
if (!rs.ok()) {
|
||||
LOG_ERROR("Failed to delete indexer state of %s", ID().c_str());
|
||||
s = Status::InternalError();
|
||||
return s;
|
||||
}
|
||||
|
||||
return s;
|
||||
}
|
||||
|
||||
|
||||
} // namespace zvec
|
||||
@@ -0,0 +1,466 @@
|
||||
// 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 <ailego/encoding/json.h>
|
||||
#include <ailego/pattern/defer.h>
|
||||
#include "inverted_codec.h"
|
||||
#include "inverted_column_indexer.h"
|
||||
|
||||
|
||||
namespace zvec {
|
||||
|
||||
|
||||
Status InvertedColumnIndexer::insert(uint32_t id, const std::string &value) {
|
||||
if (read_only_) {
|
||||
return Status::PermissionDenied();
|
||||
}
|
||||
|
||||
std::string encoded_id = std::string{1}.append(
|
||||
reinterpret_cast<const char *>(&id), sizeof(uint32_t));
|
||||
|
||||
rocksdb::Status s;
|
||||
AILEGO_DEFER([&]() {
|
||||
if (!s.ok()) {
|
||||
LOG_ERROR("Failed to insert terms of id[%u] to %s, code[%d], reason[%s]",
|
||||
id, ID().c_str(), s.code(), s.ToString().c_str());
|
||||
}
|
||||
});
|
||||
|
||||
if (field_.is_array_type()) {
|
||||
std::vector<std::string> encoded_values = encode_array(value);
|
||||
std::sort(encoded_values.begin(), encoded_values.end());
|
||||
rocksdb::WriteBatch write_batch;
|
||||
for (auto encoded_value : encoded_values) {
|
||||
s = write_batch.Merge(cf_terms_, encoded_value, encoded_id);
|
||||
if (!s.ok()) {
|
||||
return Status::InternalError();
|
||||
}
|
||||
}
|
||||
if (s = ctx_.db_->Write(ctx_.write_opts_, &write_batch); !s.ok()) {
|
||||
return Status::InternalError();
|
||||
}
|
||||
if (s = index_array_len(id, encoded_values.size()); !s.ok()) {
|
||||
return Status::InternalError();
|
||||
}
|
||||
} else {
|
||||
std::string encoded_value = encode(value);
|
||||
s = ctx_.db_->Merge(ctx_.write_opts_, cf_terms_, encoded_value, encoded_id);
|
||||
if (!s.ok()) {
|
||||
return Status::InternalError();
|
||||
}
|
||||
if (cf_reversed_terms_) {
|
||||
s = ctx_.db_->Merge(ctx_.write_opts_, cf_reversed_terms_,
|
||||
encode_reversed(value), encoded_id);
|
||||
if (!s.ok()) {
|
||||
return Status::InternalError();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
update_max_id(id);
|
||||
return Status::OK();
|
||||
}
|
||||
|
||||
|
||||
Status InvertedColumnIndexer::insert(uint32_t id,
|
||||
const std::vector<std::string> &values) {
|
||||
if (read_only_) {
|
||||
return Status::PermissionDenied();
|
||||
}
|
||||
|
||||
std::string encoded_id = std::string{1}.append(
|
||||
reinterpret_cast<const char *>(&id), sizeof(uint32_t));
|
||||
auto encoded_values = encode(values);
|
||||
|
||||
rocksdb::Status s;
|
||||
AILEGO_DEFER([&]() {
|
||||
if (!s.ok()) {
|
||||
LOG_ERROR("Failed to insert terms of id[%u] to %s, code[%d], reason[%s]",
|
||||
id, ID().c_str(), s.code(), s.ToString().c_str());
|
||||
}
|
||||
});
|
||||
|
||||
if (s = index_array_len(id, encoded_values.size()); !s.ok()) {
|
||||
return Status::InternalError();
|
||||
}
|
||||
|
||||
std::sort(encoded_values.begin(), encoded_values.end());
|
||||
rocksdb::WriteBatch write_batch;
|
||||
for (auto encoded_value : encoded_values) {
|
||||
s = write_batch.Merge(cf_terms_, encoded_value, encoded_id);
|
||||
if (!s.ok()) {
|
||||
return Status::InternalError();
|
||||
}
|
||||
}
|
||||
s = ctx_.db_->Write(ctx_.write_opts_, &write_batch);
|
||||
if (s.ok()) {
|
||||
update_max_id(id);
|
||||
return Status::OK();
|
||||
} else {
|
||||
return Status::InternalError();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Status InvertedColumnIndexer::insert(uint32_t id, bool value) {
|
||||
if (read_only_) {
|
||||
return Status::PermissionDenied();
|
||||
}
|
||||
|
||||
std::string encoded_id = std::string{1}.append(
|
||||
reinterpret_cast<const char *>(&id), sizeof(uint32_t));
|
||||
std::string encoded_value = encode(value);
|
||||
|
||||
auto s =
|
||||
ctx_.db_->Merge(ctx_.write_opts_, cf_terms_, encoded_value, encoded_id);
|
||||
if (s.ok()) {
|
||||
update_max_id(id);
|
||||
return Status::OK();
|
||||
} else {
|
||||
LOG_ERROR("Failed to insert terms of id[%u] to %s, code[%d], reason[%s]",
|
||||
id, ID().c_str(), s.code(), s.ToString().c_str());
|
||||
return Status::InternalError();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Status InvertedColumnIndexer::insert(uint32_t id,
|
||||
const std::vector<bool> &values) {
|
||||
if (read_only_) {
|
||||
return Status::PermissionDenied();
|
||||
}
|
||||
|
||||
std::string encoded_id = std::string{1}.append(
|
||||
reinterpret_cast<const char *>(&id), sizeof(uint32_t));
|
||||
|
||||
rocksdb::Status rs;
|
||||
if (rs = index_array_len(id, values.size()); !rs.ok()) {
|
||||
LOG_ERROR("Failed to index array length for %s", ID().c_str());
|
||||
return Status::InternalError();
|
||||
}
|
||||
|
||||
bool has_true = false;
|
||||
bool has_false = false;
|
||||
for (bool value : values) {
|
||||
if (value) {
|
||||
has_true = true;
|
||||
} else {
|
||||
has_false = true;
|
||||
}
|
||||
}
|
||||
|
||||
rocksdb::WriteBatch write_batch;
|
||||
if (has_true) {
|
||||
write_batch.Merge(cf_terms_, encode(true), encoded_id);
|
||||
}
|
||||
if (has_false) {
|
||||
write_batch.Merge(cf_terms_, encode(false), encoded_id);
|
||||
}
|
||||
rs = ctx_.db_->Write(ctx_.write_opts_, &write_batch);
|
||||
if (rs.ok()) {
|
||||
update_max_id(id);
|
||||
return Status::OK();
|
||||
} else {
|
||||
LOG_ERROR("Failed to insert terms of id[%u] to %s, code[%d], reason[%s]",
|
||||
id, ID().c_str(), rs.code(), rs.ToString().c_str());
|
||||
return Status::InternalError();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Status InvertedColumnIndexer::insert_null(uint32_t id) {
|
||||
if (read_only_) {
|
||||
return Status::PermissionDenied();
|
||||
}
|
||||
null_bitmap_.add(id);
|
||||
update_max_id(id);
|
||||
return Status::OK();
|
||||
}
|
||||
|
||||
|
||||
Status InvertedColumnIndexer::flush_special_values() {
|
||||
if (read_only_) {
|
||||
return Status::PermissionDenied();
|
||||
}
|
||||
|
||||
std::string value;
|
||||
if (null_bitmap_.cardinality() != 0) {
|
||||
if (!null_bitmap_.serialize(&value).ok()) {
|
||||
LOG_ERROR("Failed to serialize null bitmap");
|
||||
return Status::InternalError();
|
||||
}
|
||||
auto s = ctx_.db_->Put(ctx_.write_opts_, key_null(), value);
|
||||
if (!s.ok()) {
|
||||
LOG_ERROR("Failed to insert null bitmap to %s, code[%d], reason[%s]",
|
||||
ID().c_str(), s.code(), s.ToString().c_str());
|
||||
return Status::InternalError();
|
||||
}
|
||||
}
|
||||
|
||||
auto s =
|
||||
ctx_.db_->Put(ctx_.write_opts_, key_max_id(), std::to_string(max_id_));
|
||||
if (s.ok()) {
|
||||
LOG_DEBUG("Special values flushed to %s", ID().c_str());
|
||||
return Status::OK();
|
||||
} else {
|
||||
LOG_ERROR("Failed to insert max_id to %s, code[%d], reason[%s]",
|
||||
ID().c_str(), s.code(), s.ToString().c_str());
|
||||
return Status::InternalError();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
rocksdb::Status InvertedColumnIndexer::index_array_len(uint32_t id,
|
||||
uint32_t len) {
|
||||
if (!cf_array_len_) {
|
||||
LOG_ERROR("%s doesn't support array length index", ID().c_str());
|
||||
return rocksdb::Status::NotSupported();
|
||||
}
|
||||
|
||||
std::string encoded_id = std::string{1}.append(
|
||||
reinterpret_cast<const char *>(&id), sizeof(uint32_t));
|
||||
std::string encoded_len = InvertedIndexCodec::Encode(
|
||||
std::string((char *)&len, sizeof(uint32_t)), DataType::UINT32);
|
||||
|
||||
return ctx_.db_->Merge(ctx_.write_opts_, cf_array_len_, encoded_len,
|
||||
encoded_id);
|
||||
}
|
||||
|
||||
|
||||
Status InvertedColumnIndexer::generate_statistical_indexes() {
|
||||
if (read_only_) {
|
||||
return Status::PermissionDenied();
|
||||
}
|
||||
if (!enable_range_optimization_) {
|
||||
return Status::PermissionDenied();
|
||||
}
|
||||
|
||||
if (!ctx_.reset_cf(cf_name_ranges()).ok()) {
|
||||
// Reset the range index in case it is corrupted
|
||||
LOG_ERROR("Failed to reset range index");
|
||||
return Status::InternalError();
|
||||
}
|
||||
cf_ranges_ = ctx_.get_cf(cf_name_ranges());
|
||||
if (!cf_ranges_) {
|
||||
LOG_ERROR("Failed to get column families for %s", ID().c_str());
|
||||
return Status::InternalError();
|
||||
}
|
||||
|
||||
// TODO: make them configurable
|
||||
const uint32_t num_range_slot = 1000;
|
||||
const uint32_t num_cdf_slot = 100;
|
||||
|
||||
const uint32_t num_doc_per_range_slot = (max_id_ + 1) / num_range_slot;
|
||||
const uint32_t num_doc_per_cdf_slot = (max_id_ + 1) / num_cdf_slot;
|
||||
|
||||
// Iterator for terms in the inverted index
|
||||
auto iter_term = ctx_.db_->NewIterator(ctx_.read_opts_, cf_terms_);
|
||||
iter_term->SeekToFirst();
|
||||
AILEGO_DEFER([&]() { delete iter_term; });
|
||||
|
||||
size_t doc_count = 0, term_count = 0;
|
||||
Status s;
|
||||
rocksdb::Status rs;
|
||||
|
||||
// Range tracking variables
|
||||
std::string range_begin_key{""}, range_end_key{""};
|
||||
size_t range_slot_doc_count{0};
|
||||
size_t num_range_slot_created = 0;
|
||||
roaring_bitmap_t *bitmap_range = roaring_bitmap_create();
|
||||
if (bitmap_range == nullptr) {
|
||||
LOG_ERROR("Failed to create bitmap");
|
||||
return Status::InternalError();
|
||||
}
|
||||
AILEGO_DEFER([&]() { roaring_bitmap_free(bitmap_range); });
|
||||
|
||||
// Function to create a range slot
|
||||
auto create_range_slot = [&]() -> Status {
|
||||
std::string range_key = range_begin_key;
|
||||
range_key.append(1, '\0'); // Separator byte
|
||||
range_key.append(range_end_key.data(), range_end_key.size());
|
||||
uint64_t range_key_begin_size = range_begin_key.size();
|
||||
range_key.append((char *)&range_key_begin_size, sizeof(uint64_t));
|
||||
std::string range_value_str;
|
||||
s = InvertedIndexCodec::Serialize(bitmap_range, &range_value_str);
|
||||
if (!s.ok()) {
|
||||
LOG_ERROR("Failed to serialize bitmap");
|
||||
return Status::InternalError();
|
||||
}
|
||||
rs =
|
||||
ctx_.db_->Put(ctx_.write_opts_, cf_ranges_, range_key, range_value_str);
|
||||
if (!rs.ok()) {
|
||||
LOG_ERROR("Failed to put range slot: %s", rs.ToString().c_str());
|
||||
return Status::InternalError();
|
||||
}
|
||||
num_range_slot_created++;
|
||||
return Status::OK();
|
||||
};
|
||||
|
||||
// CDF tracking variables
|
||||
ailego::JsonArray cdf_json_array;
|
||||
size_t cdf_slot_doc_count = 0;
|
||||
|
||||
// Function to create a CDF slot
|
||||
auto create_cdf_slot = [&]() {
|
||||
ailego::JsonObject json_obj;
|
||||
json_obj.set(ailego::JsonString("key").encode(),
|
||||
ailego::JsonString(iter_term->key().ToString()).encode());
|
||||
json_obj.set(ailego::JsonString("doc_count").encode(),
|
||||
ailego::JsonValue(doc_count));
|
||||
cdf_json_array.push(json_obj);
|
||||
};
|
||||
|
||||
// Is the current slot initialized?
|
||||
bool range_slot_initialized{false}, cdf_slot_initialized{false};
|
||||
|
||||
|
||||
// Scan
|
||||
roaring_bitmap_t *bitmap_cur{nullptr};
|
||||
AILEGO_DEFER([&]() {
|
||||
if (bitmap_cur) {
|
||||
roaring_bitmap_free(bitmap_cur);
|
||||
}
|
||||
});
|
||||
|
||||
while (iter_term->Valid()) {
|
||||
term_count++;
|
||||
s = InvertedIndexCodec::Deserialize(iter_term->value().data(),
|
||||
iter_term->value().size(), &bitmap_cur);
|
||||
if (!s.ok()) {
|
||||
LOG_ERROR("Failed to deserialize bitmap for term[%s] from %s",
|
||||
iter_term->key().ToString().c_str(), ID().c_str());
|
||||
return Status::InternalError();
|
||||
}
|
||||
// The count of documents for the current term
|
||||
auto term_doc_count = roaring_bitmap_get_cardinality(bitmap_cur);
|
||||
doc_count += term_doc_count;
|
||||
|
||||
// Range
|
||||
if (!range_slot_initialized) {
|
||||
range_slot_initialized = true;
|
||||
range_slot_doc_count = 0;
|
||||
range_begin_key = iter_term->key().ToString();
|
||||
roaring_bitmap_clear(bitmap_range);
|
||||
}
|
||||
range_end_key = iter_term->key().ToString();
|
||||
range_slot_doc_count += term_doc_count;
|
||||
roaring_bitmap_or_inplace(bitmap_range, bitmap_cur);
|
||||
if (range_slot_doc_count >= num_doc_per_range_slot) {
|
||||
if (create_range_slot().ok()) {
|
||||
range_slot_initialized = false;
|
||||
} else {
|
||||
return Status::InternalError();
|
||||
}
|
||||
}
|
||||
|
||||
// CDF
|
||||
if (!cdf_slot_initialized) {
|
||||
cdf_slot_initialized = true;
|
||||
cdf_slot_doc_count = 0;
|
||||
}
|
||||
cdf_slot_doc_count += term_doc_count;
|
||||
if (cdf_slot_doc_count >= num_doc_per_cdf_slot) {
|
||||
create_cdf_slot();
|
||||
cdf_slot_initialized = false;
|
||||
}
|
||||
|
||||
roaring_bitmap_free(bitmap_cur);
|
||||
bitmap_cur = nullptr;
|
||||
iter_term->Next();
|
||||
}
|
||||
|
||||
|
||||
// Finalize
|
||||
if (range_slot_initialized) {
|
||||
if (!create_range_slot().ok()) {
|
||||
return Status::InternalError();
|
||||
}
|
||||
}
|
||||
if (num_range_slot_created >= term_count) {
|
||||
LOG_DEBUG(
|
||||
"Drop range index in %s, range_slot_count[%ld] vs term_count[%ld].",
|
||||
ID().c_str(), num_range_slot_created, term_count);
|
||||
if (!ctx_.reset_cf(cf_name_ranges()).ok()) {
|
||||
LOG_ERROR("Failed to drop range index");
|
||||
return Status::InternalError();
|
||||
}
|
||||
cf_ranges_ = ctx_.get_cf(cf_name_ranges());
|
||||
if (!cf_ranges_) {
|
||||
LOG_ERROR("Failed to get cf_ranges for %s", ID().c_str());
|
||||
return Status::InternalError();
|
||||
}
|
||||
}
|
||||
|
||||
if (cdf_slot_initialized) {
|
||||
iter_term->SeekToLast();
|
||||
create_cdf_slot();
|
||||
}
|
||||
ailego::JsonObject cdf_json_obj;
|
||||
cdf_json_obj.set("field_value_histogram", cdf_json_array);
|
||||
cdf_json_obj.set("total_doc_count", ailego::JsonValue(doc_count));
|
||||
ailego::JsonValue cdf_json(std::move(cdf_json_obj));
|
||||
rs = ctx_.db_->Put(ctx_.write_opts_, cf_cdf_, field_.name(),
|
||||
cdf_json.as_json_string().as_stl_string());
|
||||
if (!rs.ok()) {
|
||||
LOG_ERROR("Failed to insert CDF of field[%s] to %s, code[%d], reason[%s]",
|
||||
field_.name().c_str(), ID().c_str(), rs.code(),
|
||||
rs.ToString().c_str());
|
||||
return Status::InternalError();
|
||||
}
|
||||
|
||||
doc_range_stat_ =
|
||||
SegmentDocRangeStat::Create(cdf_json.as_json_string().as_stl_string());
|
||||
if (!doc_range_stat_) {
|
||||
LOG_ERROR("Failed to create doc range stats from %s", ID().c_str());
|
||||
return Status::InternalError();
|
||||
}
|
||||
|
||||
LOG_INFO("Generated statistical indexes in %s", ID().c_str());
|
||||
return Status::OK();
|
||||
}
|
||||
|
||||
|
||||
Status InvertedColumnIndexer::seal() {
|
||||
if (read_only_) {
|
||||
return Status::PermissionDenied();
|
||||
}
|
||||
|
||||
Status status = flush_special_values();
|
||||
if (!status.ok()) {
|
||||
LOG_ERROR("Failed to flush special values to %s", ID().c_str());
|
||||
return status;
|
||||
}
|
||||
|
||||
if (enable_range_optimization_) {
|
||||
status = generate_statistical_indexes();
|
||||
if (!status.ok()) {
|
||||
LOG_ERROR("Failed to generate statistical indexes in %s", ID().c_str());
|
||||
return status;
|
||||
}
|
||||
}
|
||||
|
||||
auto rs = ctx_.db_->Put(ctx_.write_opts_, key_sealed(), "sealed");
|
||||
if (rs.ok()) {
|
||||
sealed_ = true;
|
||||
read_only_ = true;
|
||||
return Status::OK();
|
||||
} else {
|
||||
LOG_ERROR("Failed to seal %s", ID().c_str());
|
||||
return Status::InternalError();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
} // namespace zvec
|
||||
@@ -0,0 +1,127 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
|
||||
#pragma once
|
||||
|
||||
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <ailego/encoding/json/mod_json_plus.h>
|
||||
#include <ailego/logger/logger.h>
|
||||
#include "db/index/common/type.h"
|
||||
|
||||
|
||||
namespace zvec {
|
||||
|
||||
|
||||
struct DocRange {
|
||||
std::string key_{""};
|
||||
size_t doc_count_{0};
|
||||
|
||||
DocRange() {}
|
||||
|
||||
DocRange(const std::string &key, int count) : key_(key), doc_count_(count) {}
|
||||
|
||||
bool operator<(const std::string &key) const {
|
||||
return key_ < key;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
class SegmentDocRangeStat {
|
||||
public:
|
||||
using Ptr = std::shared_ptr<SegmentDocRangeStat>;
|
||||
|
||||
|
||||
SegmentDocRangeStat(std::vector<DocRange> &&doc_ranges,
|
||||
uint64_t total_doc_count)
|
||||
: doc_ranges_(std::move(doc_ranges)), total_doc_count_(total_doc_count) {
|
||||
std::sort(
|
||||
doc_ranges_.begin(), doc_ranges_.end(),
|
||||
[](const DocRange &a, const DocRange &b) { return a.key_ < b.key_; });
|
||||
}
|
||||
|
||||
|
||||
static Ptr Create(const std::string &stat_json_str) {
|
||||
ailego::JsonValue stat_json_value;
|
||||
ailego::JsonParser parser;
|
||||
if (!parser.parse(stat_json_str.c_str(), &stat_json_value)) {
|
||||
LOG_ERROR("Failed to parse json string");
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
ailego::JsonObject stat_json_obj = stat_json_value.as_object();
|
||||
ailego::JsonArray stat_json_array;
|
||||
if (!stat_json_obj.get("field_value_histogram", &stat_json_array)) {
|
||||
LOG_ERROR("Failed to get histogram");
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
ailego::JsonValue stat_total_doc_count;
|
||||
if (!stat_json_obj.get("total_doc_count", &stat_total_doc_count)) {
|
||||
LOG_ERROR("Failed to get total doc count");
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
std::vector<DocRange> doc_ranges;
|
||||
for (auto it = stat_json_array.begin(); it != stat_json_array.end(); ++it) {
|
||||
ailego::JsonString stat_key;
|
||||
ailego::JsonValue stat_doc_count;
|
||||
if (!it->as_object().get("key", &stat_key)) {
|
||||
LOG_ERROR("Failed to get key");
|
||||
return nullptr;
|
||||
}
|
||||
if (!it->as_object().get("doc_count", &stat_doc_count)) {
|
||||
LOG_ERROR("Failed to get doc count");
|
||||
return nullptr;
|
||||
}
|
||||
doc_ranges.emplace_back(stat_key.decode().as_stl_string(),
|
||||
stat_doc_count.as_integer());
|
||||
}
|
||||
|
||||
return std::make_shared<SegmentDocRangeStat>(
|
||||
std::move(doc_ranges), stat_total_doc_count.as_integer());
|
||||
}
|
||||
|
||||
|
||||
void evaluate_ratio(const std::string &value, CompareOp op,
|
||||
uint64_t *total_size, uint64_t *range_size) const {
|
||||
if (doc_ranges_.size() == 0) {
|
||||
*range_size = 0;
|
||||
*total_size = total_doc_count_;
|
||||
}
|
||||
|
||||
// Is greater than?
|
||||
bool is_gt = (op == CompareOp::GT) || (op == CompareOp::GE);
|
||||
|
||||
auto it = std::lower_bound(doc_ranges_.begin(), doc_ranges_.end(), value);
|
||||
|
||||
if (it == doc_ranges_.end()) {
|
||||
*range_size = is_gt ? 0 : total_doc_count_;
|
||||
} else {
|
||||
*range_size = is_gt ? total_doc_count_ - it->doc_count_ : it->doc_count_;
|
||||
}
|
||||
*total_size = total_doc_count_;
|
||||
}
|
||||
|
||||
|
||||
private:
|
||||
std::vector<DocRange> doc_ranges_;
|
||||
uint64_t total_doc_count_;
|
||||
};
|
||||
|
||||
|
||||
} // namespace zvec
|
||||
@@ -0,0 +1,267 @@
|
||||
// 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 "inverted_indexer.h"
|
||||
#include <ailego/encoding/json.h>
|
||||
#include "inverted_rocksdb_merger.h"
|
||||
|
||||
|
||||
namespace zvec {
|
||||
|
||||
|
||||
Status InvertedIndexer::open(bool create_dir_if_missing, bool read_only) {
|
||||
std::vector<std::string> cf_names{}; // Column families
|
||||
for (const auto &field : fields_) {
|
||||
if (field.index_type() != IndexType::INVERT) {
|
||||
LOG_ERROR("Field[%s] is not an inverted field", field.name().c_str());
|
||||
return Status::InvalidArgument();
|
||||
}
|
||||
auto params =
|
||||
std::dynamic_pointer_cast<InvertIndexParams>(field.index_params());
|
||||
cf_names.emplace_back(field.name() + INVERT_SUFFIX_TERMS);
|
||||
if (field.is_array_type()) {
|
||||
cf_names.emplace_back(field.name() + INVERT_SUFFIX_ARRAY_LEN);
|
||||
}
|
||||
if (allow_range_optimization(field) &&
|
||||
params->enable_range_optimization()) {
|
||||
cf_names.emplace_back(field.name() + INVERT_SUFFIX_RANGES);
|
||||
}
|
||||
if (allow_extended_wildcard(field) && params->enable_extended_wildcard()) {
|
||||
cf_names.emplace_back(field.name() + INVERT_SUFFIX_REVERSED_TERMS);
|
||||
}
|
||||
}
|
||||
cf_names.emplace_back(INVERT_CDF);
|
||||
|
||||
Status s;
|
||||
if (FILE::IsExist(working_dir_)) {
|
||||
if (!FILE::IsDirectory(working_dir_)) {
|
||||
LOG_ERROR("InvertedIndexer path[%s] is not a directory",
|
||||
working_dir_.c_str());
|
||||
return Status::InvalidArgument();
|
||||
}
|
||||
s = rocksdb_context_.open(working_dir_, cf_names, read_only,
|
||||
std::make_shared<InvertedRocksdbValueMerger>());
|
||||
} else {
|
||||
if (!create_dir_if_missing) {
|
||||
LOG_ERROR("InvertedIndexer path[%s] does not exist",
|
||||
working_dir_.c_str());
|
||||
return Status::NotFound();
|
||||
}
|
||||
s = rocksdb_context_.create(working_dir_, cf_names,
|
||||
std::make_shared<InvertedRocksdbValueMerger>());
|
||||
}
|
||||
|
||||
if (!s.ok()) {
|
||||
LOG_ERROR("Failed to open %s", ID().c_str());
|
||||
return s;
|
||||
}
|
||||
|
||||
for (const auto &field : fields_) {
|
||||
auto column_indexer = InvertedColumnIndexer::CreateAndOpen(
|
||||
collection_name_, field, rocksdb_context_, read_only);
|
||||
if (column_indexer == nullptr) {
|
||||
LOG_ERROR("Failed to create InvertedColumnIndexer[%s]",
|
||||
field.name().c_str());
|
||||
return Status::InternalError();
|
||||
}
|
||||
indexers_.emplace(field.name(), std::move(column_indexer));
|
||||
}
|
||||
|
||||
LOG_INFO("Opened %s", ID().c_str());
|
||||
return s;
|
||||
}
|
||||
|
||||
|
||||
Status InvertedIndexer::flush() {
|
||||
for (auto &[_, indexer] : indexers_) {
|
||||
if (indexer->is_sealed()) {
|
||||
continue;
|
||||
}
|
||||
if (!indexer->flush_special_values().ok()) {
|
||||
LOG_ERROR("Failed to flush %s", indexer->ID().c_str());
|
||||
return Status::InternalError();
|
||||
}
|
||||
}
|
||||
|
||||
auto s = rocksdb_context_.flush();
|
||||
if (s.ok()) {
|
||||
LOG_INFO("Flushed %s", ID().c_str());
|
||||
} else {
|
||||
LOG_ERROR("Failed to flush %s", ID().c_str());
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
|
||||
Status InvertedIndexer::create_snapshot(const std::string &snapshot_dir) {
|
||||
Status s;
|
||||
if (s = flush(); !s.ok()) {
|
||||
LOG_ERROR("Failed to flush %s during creating a snapshot", ID().c_str());
|
||||
return s;
|
||||
}
|
||||
|
||||
if (s = rocksdb_context_.create_checkpoint(snapshot_dir); s.ok()) {
|
||||
LOG_INFO("Created snapshot[%s] of %s", snapshot_dir.c_str(), ID().c_str());
|
||||
} else {
|
||||
LOG_ERROR("Failed to create snapshot[%s] of %s", snapshot_dir.c_str(),
|
||||
ID().c_str());
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
|
||||
Status InvertedIndexer::seal() {
|
||||
Status s;
|
||||
for (const auto &[_, indexer] : indexers_) {
|
||||
if (indexer->is_sealed()) {
|
||||
continue;
|
||||
}
|
||||
if (s = indexer->seal(); !s.ok()) {
|
||||
LOG_ERROR("Failed to seal %s", indexer->ID().c_str());
|
||||
}
|
||||
}
|
||||
|
||||
if (s = flush(); !s.ok()) {
|
||||
LOG_ERROR("Failed to flush %s during sealing", ID().c_str());
|
||||
return s;
|
||||
}
|
||||
|
||||
if (s = rocksdb_context_.compact(); s.ok()) {
|
||||
LOG_INFO("Sealed %s", ID().c_str());
|
||||
} else {
|
||||
LOG_ERROR("Failed to compact %s during sealing", ID().c_str());
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
|
||||
Status InvertedIndexer::create_column_indexer(const FieldSchema &field) {
|
||||
if (field.index_type() != IndexType::INVERT) {
|
||||
return Status::InvalidArgument();
|
||||
}
|
||||
auto it = std::find_if(fields_.begin(), fields_.end(),
|
||||
[&field](FieldSchema &cur_field) {
|
||||
return cur_field.name() == field.name();
|
||||
});
|
||||
if (it != fields_.end()) {
|
||||
LOG_ERROR("InvertedColumnIndexer[%s] already exists in %s",
|
||||
field.name().c_str(), ID().c_str());
|
||||
return Status::InvalidArgument();
|
||||
}
|
||||
auto params =
|
||||
std::dynamic_pointer_cast<InvertIndexParams>(field.index_params());
|
||||
|
||||
Status s;
|
||||
bool cf_terms_created{false};
|
||||
bool cf_array_len_created{false};
|
||||
bool cf_ranges_created{false};
|
||||
bool cf_reversed_terms_created{false};
|
||||
AILEGO_DEFER([&]() {
|
||||
if (s.ok()) {
|
||||
LOG_INFO("Created a new InvertedColumnIndexer[%s] in %s",
|
||||
field.name().c_str(), ID().c_str());
|
||||
} else {
|
||||
if (cf_terms_created) {
|
||||
rocksdb_context_.drop_cf(field.name() + INVERT_SUFFIX_TERMS);
|
||||
}
|
||||
if (cf_array_len_created) {
|
||||
rocksdb_context_.drop_cf(field.name() + INVERT_SUFFIX_ARRAY_LEN);
|
||||
}
|
||||
if (cf_ranges_created) {
|
||||
rocksdb_context_.drop_cf(field.name() + INVERT_SUFFIX_RANGES);
|
||||
}
|
||||
if (cf_reversed_terms_created) {
|
||||
rocksdb_context_.drop_cf(field.name() + INVERT_SUFFIX_REVERSED_TERMS);
|
||||
}
|
||||
LOG_ERROR("Failed to create InvertedColumnIndexer[%s] in %s",
|
||||
field.name().c_str(), ID().c_str());
|
||||
}
|
||||
});
|
||||
|
||||
s = rocksdb_context_.create_cf(field.name() + INVERT_SUFFIX_TERMS);
|
||||
if (s.ok()) {
|
||||
cf_terms_created = true;
|
||||
} else {
|
||||
return s;
|
||||
}
|
||||
if (field.is_array_type()) {
|
||||
s = rocksdb_context_.create_cf(field.name() + INVERT_SUFFIX_ARRAY_LEN);
|
||||
if (s.ok()) {
|
||||
cf_array_len_created = true;
|
||||
} else {
|
||||
return s;
|
||||
}
|
||||
}
|
||||
if (allow_range_optimization(field) && params->enable_range_optimization()) {
|
||||
s = rocksdb_context_.create_cf(field.name() + INVERT_SUFFIX_RANGES);
|
||||
if (s.ok()) {
|
||||
cf_ranges_created = true;
|
||||
} else {
|
||||
return s;
|
||||
}
|
||||
}
|
||||
if (allow_extended_wildcard(field) && params->enable_extended_wildcard()) {
|
||||
s = rocksdb_context_.create_cf(field.name() + INVERT_SUFFIX_REVERSED_TERMS);
|
||||
if (s.ok()) {
|
||||
cf_reversed_terms_created = true;
|
||||
} else {
|
||||
return s;
|
||||
}
|
||||
}
|
||||
|
||||
auto column_indexer = InvertedColumnIndexer::CreateAndOpen(
|
||||
collection_name_, field, rocksdb_context_);
|
||||
if (column_indexer) {
|
||||
fields_.emplace_back(field);
|
||||
indexers_.emplace(field.name(), std::move(column_indexer));
|
||||
s = Status::OK();
|
||||
} else {
|
||||
s = Status::InternalError();
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
|
||||
Status InvertedIndexer::remove_column_indexer(const std::string &field_name) {
|
||||
auto it = std::find_if(fields_.begin(), fields_.end(),
|
||||
[&field_name](FieldSchema &cur_field) {
|
||||
return cur_field.name() == field_name;
|
||||
});
|
||||
auto column_indexer = (*this)[field_name];
|
||||
if (it == fields_.end() && !column_indexer) {
|
||||
LOG_ERROR("InvertedColumnIndexer[%s] doesn't exists in %s",
|
||||
field_name.c_str(), ID().c_str());
|
||||
return Status::NotFound();
|
||||
}
|
||||
if (it == fields_.end() || !column_indexer) {
|
||||
LOG_ERROR("%s is in corrupted state", ID().c_str());
|
||||
return Status::InternalError();
|
||||
}
|
||||
|
||||
if (auto s = column_indexer->drop_storage(); !s.ok()) {
|
||||
LOG_ERROR("Failed to remove InvertedColumnIndexer[%s] in %s",
|
||||
field_name.c_str(), ID().c_str());
|
||||
return s;
|
||||
}
|
||||
|
||||
fields_.erase(it);
|
||||
indexers_.erase(field_name);
|
||||
LOG_INFO("Removed InvertedColumnIndexer[%s] in %s", field_name.c_str(),
|
||||
ID().c_str());
|
||||
return Status::OK();
|
||||
}
|
||||
|
||||
|
||||
} // namespace zvec
|
||||
@@ -0,0 +1,119 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
|
||||
#pragma once
|
||||
|
||||
|
||||
#include <rocksdb/utilities/checkpoint.h>
|
||||
#include "inverted_column_indexer.h"
|
||||
|
||||
|
||||
namespace zvec {
|
||||
|
||||
|
||||
class InvertedIndexer {
|
||||
public:
|
||||
using Ptr = std::shared_ptr<InvertedIndexer>;
|
||||
|
||||
|
||||
explicit InvertedIndexer(const std::string &collection_name,
|
||||
const std::string &working_dir,
|
||||
const std::vector<FieldSchema> &fields)
|
||||
: collection_name_(collection_name),
|
||||
working_dir_(working_dir),
|
||||
fields_(fields) {};
|
||||
|
||||
|
||||
virtual ~InvertedIndexer() {
|
||||
rocksdb_context_.close();
|
||||
LOG_INFO("Closed %s", ID().c_str());
|
||||
}
|
||||
|
||||
|
||||
static Ptr CreateAndOpen(const std::string &collection_name,
|
||||
const std::string &working_dir,
|
||||
const bool create_dir_if_missing,
|
||||
const std::vector<FieldSchema> &fields,
|
||||
bool read_only) {
|
||||
Ptr indexer =
|
||||
std::make_shared<InvertedIndexer>(collection_name, working_dir, fields);
|
||||
if (indexer->open(create_dir_if_missing, read_only).ok()) {
|
||||
return indexer;
|
||||
} else {
|
||||
return nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
InvertedColumnIndexer::Ptr operator[](const std::string &field_name) {
|
||||
auto it = indexers_.find(field_name);
|
||||
if (it != indexers_.end()) {
|
||||
return it->second;
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
|
||||
Status flush();
|
||||
|
||||
Status create_snapshot(const std::string &snapshot_dir);
|
||||
|
||||
Status seal();
|
||||
|
||||
Status create_column_indexer(const FieldSchema &field);
|
||||
|
||||
Status remove_column_indexer(const std::string &field_name);
|
||||
|
||||
inline std::string collection() const {
|
||||
return collection_name_;
|
||||
}
|
||||
|
||||
inline std::string working_dir() const {
|
||||
return working_dir_;
|
||||
}
|
||||
|
||||
inline const std::string ID() const {
|
||||
return "InvertedIndexer[collection:" + collection_name_ + "|path:'" +
|
||||
working_dir_ + "']";
|
||||
}
|
||||
|
||||
|
||||
private:
|
||||
using FILE = ailego::File;
|
||||
|
||||
Status open(bool create_dir_if_missing, bool read_only);
|
||||
|
||||
inline bool allow_range_optimization(const FieldSchema &field) const {
|
||||
bool not_allowed =
|
||||
field.is_array_type() || field.data_type() == DataType::BOOL;
|
||||
return !not_allowed;
|
||||
}
|
||||
|
||||
inline bool allow_extended_wildcard(const FieldSchema &field) const {
|
||||
return field.data_type() == DataType::STRING;
|
||||
}
|
||||
|
||||
|
||||
private:
|
||||
const std::string collection_name_;
|
||||
const std::string working_dir_;
|
||||
std::vector<FieldSchema> fields_;
|
||||
|
||||
std::unordered_map<std::string, InvertedColumnIndexer::Ptr> indexers_;
|
||||
RocksdbContext rocksdb_context_{};
|
||||
};
|
||||
|
||||
|
||||
} // namespace zvec
|
||||
@@ -0,0 +1,115 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
|
||||
#pragma once
|
||||
|
||||
|
||||
#include <ailego/pattern/defer.h>
|
||||
#include <rocksdb/merge_operator.h>
|
||||
#include "inverted_codec.h"
|
||||
|
||||
|
||||
namespace zvec {
|
||||
|
||||
|
||||
class InvertedRocksdbValueMerger : public rocksdb::MergeOperator {
|
||||
public:
|
||||
virtual bool FullMergeV2(const MergeOperationInput &merge_in,
|
||||
MergeOperationOutput *merge_out) const override {
|
||||
if (merge_in.existing_value == nullptr &&
|
||||
merge_in.operand_list.size() == 1) {
|
||||
merge_out->new_value = std::string(merge_in.operand_list[0].data(),
|
||||
merge_in.operand_list[0].size());
|
||||
return true;
|
||||
}
|
||||
|
||||
merge_out->new_value.clear();
|
||||
|
||||
Status s;
|
||||
roaring_bitmap_t *bitmap{nullptr};
|
||||
if (merge_in.existing_value != nullptr) {
|
||||
s = InvertedIndexCodec::Deserialize(merge_in.existing_value->data(),
|
||||
merge_in.existing_value->size(),
|
||||
&bitmap);
|
||||
if (!s.ok()) {
|
||||
LOG_ERROR("Failed to deserialize existing value");
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
bitmap = roaring_bitmap_create();
|
||||
if (!bitmap) {
|
||||
LOG_ERROR("Failed to create bitmap");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
AILEGO_DEFER([&]() { roaring_bitmap_free(bitmap); });
|
||||
|
||||
for (const rocksdb::Slice &m : merge_in.operand_list) {
|
||||
s = InvertedIndexCodec::Merge_OR(m.data(), m.size(), true, bitmap);
|
||||
if (!s.ok()) {
|
||||
LOG_ERROR("Failed to merge bitmap");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
roaring_bitmap_repair_after_lazy(bitmap);
|
||||
|
||||
s = InvertedIndexCodec::Serialize(bitmap, &(merge_out->new_value));
|
||||
if (s.ok()) {
|
||||
return true;
|
||||
} else {
|
||||
LOG_ERROR("Failed to serialize bitmap");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
virtual bool PartialMerge(const rocksdb::Slice & /*key*/,
|
||||
const rocksdb::Slice &left_operand,
|
||||
const rocksdb::Slice &right_operand,
|
||||
std::string *new_value,
|
||||
rocksdb::Logger * /*logger*/) const override {
|
||||
roaring_bitmap_t *bitmap{nullptr};
|
||||
auto s = InvertedIndexCodec::Deserialize(left_operand.data(),
|
||||
left_operand.size(), &bitmap);
|
||||
if (!s.ok()) {
|
||||
LOG_ERROR("Failed to deserialize existing value");
|
||||
return false;
|
||||
}
|
||||
AILEGO_DEFER([&]() { roaring_bitmap_free(bitmap); });
|
||||
|
||||
s = InvertedIndexCodec::Merge_OR(right_operand.data(), right_operand.size(),
|
||||
false, bitmap);
|
||||
if (!s.ok()) {
|
||||
LOG_ERROR("Failed to merge bitmap");
|
||||
return false;
|
||||
}
|
||||
|
||||
s = InvertedIndexCodec::Serialize(bitmap, new_value);
|
||||
if (s.ok()) {
|
||||
return true;
|
||||
} else {
|
||||
LOG_ERROR("Failed to serialize bitmap");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
const char *Name() const override {
|
||||
return "InvertedRocksdbValueMerger";
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
} // namespace zvec
|
||||
@@ -0,0 +1,199 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
|
||||
#pragma once
|
||||
|
||||
|
||||
#include <roaring/roaring.h>
|
||||
#include "db/common/constants.h"
|
||||
#include "db/index/column/common/index_results.h"
|
||||
|
||||
|
||||
namespace zvec {
|
||||
|
||||
|
||||
class InvertedSearchResult
|
||||
: public IndexResults,
|
||||
public std::enable_shared_from_this<InvertedSearchResult> {
|
||||
public:
|
||||
using Ptr = std::shared_ptr<InvertedSearchResult>;
|
||||
|
||||
|
||||
class Filter : public IndexFilter {
|
||||
public:
|
||||
explicit Filter(std::shared_ptr<const InvertedSearchResult> result)
|
||||
: result_(std::move(result)) {};
|
||||
|
||||
bool is_filtered(uint64_t id) const override {
|
||||
return !result_->contains(id);
|
||||
}
|
||||
|
||||
private:
|
||||
const std::shared_ptr<const InvertedSearchResult> result_{};
|
||||
};
|
||||
|
||||
|
||||
const IndexFilter::Ptr make_filter() const {
|
||||
return bitmap_ ? std::make_shared<Filter>(shared_from_this()) : nullptr;
|
||||
}
|
||||
|
||||
|
||||
explicit InvertedSearchResult() {}
|
||||
|
||||
|
||||
explicit InvertedSearchResult(roaring_bitmap_t *bitmap) : bitmap_(bitmap) {}
|
||||
|
||||
|
||||
~InvertedSearchResult() {
|
||||
destroy_bitmap();
|
||||
}
|
||||
|
||||
|
||||
InvertedSearchResult(const InvertedSearchResult &) = delete;
|
||||
InvertedSearchResult(InvertedSearchResult &&) = delete;
|
||||
InvertedSearchResult &operator=(const InvertedSearchResult &) = delete;
|
||||
InvertedSearchResult &operator=(InvertedSearchResult &&) = delete;
|
||||
|
||||
|
||||
bool contains(uint32_t id) const {
|
||||
if (bitmap_) {
|
||||
return roaring_bitmap_contains(bitmap_, id);
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
size_t count() const override {
|
||||
if (bitmap_) {
|
||||
return roaring_bitmap_get_cardinality(bitmap_);
|
||||
} else {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
class InvertedIndexIterator : public Iterator {
|
||||
public:
|
||||
explicit InvertedIndexIterator(
|
||||
std::shared_ptr<const InvertedSearchResult> result)
|
||||
: result_(result) {
|
||||
if (result_->bitmap_) {
|
||||
iter_ = roaring_create_iterator(result_->bitmap_);
|
||||
}
|
||||
}
|
||||
|
||||
virtual ~InvertedIndexIterator() {
|
||||
if (iter_) {
|
||||
roaring_free_uint32_iterator(iter_);
|
||||
}
|
||||
}
|
||||
|
||||
virtual idx_t doc_id() const {
|
||||
if (!iter_) {
|
||||
return INVALID_DOC_ID;
|
||||
}
|
||||
if (iter_->has_value) {
|
||||
return iter_->current_value;
|
||||
} else {
|
||||
return INVALID_DOC_ID;
|
||||
}
|
||||
}
|
||||
|
||||
virtual float score() const {
|
||||
return 0.0f;
|
||||
}
|
||||
|
||||
virtual void next() {
|
||||
if (iter_ && iter_->has_value) {
|
||||
roaring_advance_uint32_iterator(iter_);
|
||||
}
|
||||
}
|
||||
|
||||
virtual bool valid() const {
|
||||
return iter_ ? iter_->has_value : false;
|
||||
}
|
||||
|
||||
private:
|
||||
const std::shared_ptr<const InvertedSearchResult> result_{};
|
||||
roaring_uint32_iterator_t *iter_{nullptr};
|
||||
};
|
||||
|
||||
|
||||
IteratorUPtr create_iterator() override {
|
||||
return std::make_unique<InvertedIndexIterator>(shared_from_this());
|
||||
}
|
||||
|
||||
|
||||
void extract_ids(std::vector<uint32_t> *ids) const {
|
||||
if (!ids) {
|
||||
LOG_ERROR("Failed to extract ids: ids pointer is null");
|
||||
return;
|
||||
}
|
||||
if (!bitmap_) {
|
||||
return;
|
||||
}
|
||||
|
||||
ids->reserve(static_cast<size_t>(count()));
|
||||
roaring_uint32_iterator_t *iter = roaring_create_iterator(bitmap_);
|
||||
while (iter->has_value) {
|
||||
ids->push_back(iter->current_value);
|
||||
roaring_advance_uint32_iterator(iter);
|
||||
}
|
||||
roaring_free_uint32_iterator(iter);
|
||||
}
|
||||
|
||||
|
||||
void set_and_own_bitmap(roaring_bitmap_t *bitmap) {
|
||||
destroy_bitmap();
|
||||
bitmap_ = bitmap;
|
||||
}
|
||||
|
||||
|
||||
void destroy_bitmap() {
|
||||
if (bitmap_) {
|
||||
roaring_bitmap_free(bitmap_);
|
||||
bitmap_ = nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
void AND(const InvertedSearchResult &other) {
|
||||
if (!bitmap_ || !other.bitmap_) {
|
||||
destroy_bitmap();
|
||||
} else {
|
||||
roaring_bitmap_and_inplace(bitmap_, other.bitmap_);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
void OR(const InvertedSearchResult &other) {
|
||||
if (!other.bitmap_) {
|
||||
return;
|
||||
}
|
||||
if (!bitmap_) {
|
||||
bitmap_ = roaring_bitmap_copy(other.bitmap_);
|
||||
return;
|
||||
}
|
||||
roaring_bitmap_or_inplace(bitmap_, other.bitmap_);
|
||||
}
|
||||
|
||||
|
||||
private:
|
||||
roaring_bitmap_t *bitmap_{nullptr};
|
||||
};
|
||||
|
||||
|
||||
} // namespace zvec
|
||||
@@ -0,0 +1,227 @@
|
||||
// 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 "combined_vector_column_indexer.h"
|
||||
#include <algorithm>
|
||||
#include <cstdint>
|
||||
|
||||
namespace zvec {
|
||||
|
||||
CombinedVectorColumnIndexer::CombinedVectorColumnIndexer(
|
||||
const std::vector<VectorColumnIndexer::Ptr> &indexers,
|
||||
const std::vector<VectorColumnIndexer::Ptr> &normal_indexers,
|
||||
const FieldSchema &field_schema, const SegmentMeta &segment_meta,
|
||||
std::vector<BlockMeta> blocks, MetricType metric_type, bool is_quantized)
|
||||
: field_schema_(field_schema),
|
||||
indexers_(std::move(indexers)),
|
||||
normal_indexers_(std::move(normal_indexers)),
|
||||
blocks_(std::move(blocks)),
|
||||
metric_type_(metric_type),
|
||||
is_quantized_(is_quantized) {
|
||||
if (segment_meta.has_writing_forward_block()) {
|
||||
if (is_quantized_) {
|
||||
BlockMeta quant_block = segment_meta.writing_forward_block().value();
|
||||
quant_block.set_type(BlockType::VECTOR_INDEX_QUANTIZE);
|
||||
blocks_.push_back(std::move(quant_block));
|
||||
} else {
|
||||
BlockMeta block = segment_meta.writing_forward_block().value();
|
||||
block.set_type(BlockType::VECTOR_INDEX);
|
||||
blocks_.push_back(std::move(block));
|
||||
}
|
||||
}
|
||||
|
||||
min_doc_id_ = segment_meta.min_doc_id();
|
||||
}
|
||||
|
||||
|
||||
Result<IndexResults::Ptr> CombinedVectorColumnIndexer::Search(
|
||||
const vector_column_params::VectorData &vector_data,
|
||||
const vector_column_params::QueryParams &query_params) {
|
||||
core::IndexDocumentList doc_list;
|
||||
std::vector<std::string> reverted_vector_list;
|
||||
std::vector<std::string> reverted_sparse_values_list;
|
||||
int block_offset = 0;
|
||||
|
||||
auto q_params = query_params.query_params;
|
||||
for (size_t i = 0; i < indexers_.size(); ++i) {
|
||||
auto &block_meta = blocks_[i];
|
||||
zvec::Result<zvec::IndexResults::Ptr> result{nullptr};
|
||||
if (q_params && q_params->is_using_refiner()) {
|
||||
if (normal_indexers_.size() != indexers_.size()) {
|
||||
return tl::make_unexpected(Status::InvalidArgument(
|
||||
"normal indexers size[", normal_indexers_.size(),
|
||||
"] not match indexers size[", indexers_.size(), "]"));
|
||||
}
|
||||
// query_params of HNSW doesn't have scale_factor
|
||||
float scale_factor{};
|
||||
if (q_params->type() == IndexType::FLAT) {
|
||||
scale_factor = std::dynamic_pointer_cast<FlatQueryParams>(q_params)
|
||||
->scale_factor();
|
||||
} else if (q_params->type() == IndexType::IVF) {
|
||||
scale_factor =
|
||||
std::dynamic_pointer_cast<IVFQueryParams>(q_params)->scale_factor();
|
||||
}
|
||||
vector_column_params::QueryParams modified_query_params{
|
||||
query_params.data_type,
|
||||
query_params.dimension,
|
||||
query_params.topk,
|
||||
query_params.filter,
|
||||
query_params.fetch_vector,
|
||||
query_params.query_params,
|
||||
query_params.group_by
|
||||
? std::make_unique<vector_column_params::GroupByParams>(
|
||||
query_params.group_by->group_topk,
|
||||
query_params.group_by->group_count,
|
||||
query_params.group_by->group_by)
|
||||
: nullptr,
|
||||
query_params.bf_pks,
|
||||
std::shared_ptr<vector_column_params::RefinerParam>(
|
||||
new vector_column_params::RefinerParam{scale_factor,
|
||||
normal_indexers_[i]}),
|
||||
query_params.extra_params};
|
||||
result = indexers_[i]->Search(vector_data, modified_query_params);
|
||||
} else {
|
||||
result = indexers_[i]->Search(vector_data, query_params);
|
||||
}
|
||||
|
||||
if (!result) {
|
||||
return tl::make_unexpected(result.error());
|
||||
}
|
||||
|
||||
auto index_results = result.value();
|
||||
VectorIndexResults *vector_index_results =
|
||||
dynamic_cast<VectorIndexResults *>(index_results.get());
|
||||
|
||||
const auto &sub_docs = vector_index_results->docs();
|
||||
for (size_t j = 0; j < sub_docs.size(); ++j) {
|
||||
auto doc = sub_docs[j];
|
||||
doc.set_index(block_offset + sub_docs[j].index());
|
||||
doc_list.emplace_back(std::move(doc));
|
||||
}
|
||||
block_offset += block_meta.doc_count_;
|
||||
|
||||
auto &&temp_vector_list = vector_index_results->reverted_vector_list();
|
||||
reverted_vector_list.insert(
|
||||
reverted_vector_list.end(),
|
||||
std::make_move_iterator(temp_vector_list.begin()),
|
||||
std::make_move_iterator(temp_vector_list.end()));
|
||||
|
||||
auto &&temp_sparse_list =
|
||||
vector_index_results->reverted_sparse_values_list();
|
||||
reverted_sparse_values_list.insert(
|
||||
reverted_sparse_values_list.end(),
|
||||
std::make_move_iterator(temp_sparse_list.begin()),
|
||||
std::make_move_iterator(temp_sparse_list.end()));
|
||||
}
|
||||
|
||||
if (doc_list.empty()) {
|
||||
// return empty result
|
||||
return std::make_unique<VectorIndexResults>(
|
||||
field_schema_.is_sparse_vector(), std::move(doc_list),
|
||||
std::move(reverted_vector_list),
|
||||
std::move(reverted_sparse_values_list));
|
||||
}
|
||||
|
||||
std::vector<size_t> indices(doc_list.size());
|
||||
std::iota(indices.begin(), indices.end(), 0);
|
||||
|
||||
std::sort(indices.begin(), indices.end(),
|
||||
[this, &doc_list](size_t lhs, size_t rhs) {
|
||||
const auto &lhs_doc = doc_list[lhs];
|
||||
const auto &rhs_doc = doc_list[rhs];
|
||||
|
||||
if (this->metric_type_ == MetricType::L2) {
|
||||
return lhs_doc.score() < rhs_doc.score();
|
||||
} else if (this->metric_type_ == MetricType::IP) {
|
||||
return lhs_doc.score() > rhs_doc.score();
|
||||
} else if (this->metric_type_ == MetricType::COSINE) {
|
||||
return lhs_doc.score() < rhs_doc.score();
|
||||
} else {
|
||||
// default
|
||||
return lhs_doc.score() < rhs_doc.score();
|
||||
}
|
||||
});
|
||||
|
||||
// doc_list
|
||||
std::vector<core::IndexDocument> sorted_doc_list(doc_list.size());
|
||||
for (size_t i = 0; i < indices.size(); ++i) {
|
||||
sorted_doc_list[i] = std::move(doc_list[indices[i]]);
|
||||
}
|
||||
doc_list = std::move(sorted_doc_list);
|
||||
|
||||
// reverted_vector_list
|
||||
if (!reverted_vector_list.empty()) {
|
||||
std::vector<std::string> sorted_reverted_vector_list(
|
||||
reverted_vector_list.size());
|
||||
for (size_t i = 0; i < indices.size(); ++i) {
|
||||
if (indices[i] < reverted_vector_list.size()) {
|
||||
sorted_reverted_vector_list[i] =
|
||||
std::move(reverted_vector_list[indices[i]]);
|
||||
}
|
||||
}
|
||||
reverted_vector_list = std::move(sorted_reverted_vector_list);
|
||||
}
|
||||
|
||||
// reverted_sparse_values_list
|
||||
if (!reverted_sparse_values_list.empty()) {
|
||||
std::vector<std::string> sorted_reverted_sparse_vector_list(
|
||||
reverted_sparse_values_list.size());
|
||||
for (size_t i = 0; i < indices.size(); ++i) {
|
||||
if (indices[i] < reverted_sparse_values_list.size()) {
|
||||
sorted_reverted_sparse_vector_list[i] =
|
||||
std::move(reverted_sparse_values_list[indices[i]]);
|
||||
}
|
||||
}
|
||||
reverted_sparse_values_list = std::move(sorted_reverted_sparse_vector_list);
|
||||
}
|
||||
|
||||
// truncate to topk
|
||||
if (doc_list.size() > query_params.topk) doc_list.resize(query_params.topk);
|
||||
if (reverted_vector_list.size() > query_params.topk)
|
||||
reverted_vector_list.resize(query_params.topk);
|
||||
if (reverted_sparse_values_list.size() > query_params.topk)
|
||||
reverted_sparse_values_list.resize(query_params.topk);
|
||||
|
||||
return std::make_unique<VectorIndexResults>(
|
||||
field_schema_.is_sparse_vector(), std::move(doc_list),
|
||||
std::move(reverted_vector_list), std::move(reverted_sparse_values_list));
|
||||
}
|
||||
|
||||
Result<vector_column_params::VectorDataBuffer>
|
||||
CombinedVectorColumnIndexer::Fetch(uint32_t segment_doc_id) const {
|
||||
int32_t target_block_doc_id = -1;
|
||||
size_t target_block_idx = 0;
|
||||
|
||||
uint32_t block_offset = 0;
|
||||
for (size_t i = 0; i < blocks_.size(); ++i) {
|
||||
auto &block_meta = blocks_[i];
|
||||
if (block_offset <= segment_doc_id &&
|
||||
segment_doc_id < block_offset + block_meta.doc_count_) {
|
||||
target_block_doc_id = segment_doc_id - block_offset;
|
||||
target_block_idx = i;
|
||||
break;
|
||||
}
|
||||
block_offset += block_meta.doc_count_;
|
||||
}
|
||||
|
||||
if (target_block_doc_id == -1) {
|
||||
LOG_ERROR("Can't find block for doc_id[%u]", segment_doc_id);
|
||||
return tl::make_unexpected(
|
||||
Status::NotFound("Can't find block for doc_id:", segment_doc_id));
|
||||
}
|
||||
|
||||
auto indexer = indexers_[target_block_idx];
|
||||
return indexer->Fetch(target_block_doc_id);
|
||||
}
|
||||
|
||||
} // namespace zvec
|
||||
@@ -0,0 +1,60 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
#pragma once
|
||||
|
||||
#include <memory>
|
||||
#include <vector>
|
||||
#include "vector_column_indexer.h"
|
||||
#include "vector_column_params.h"
|
||||
#include "vector_index_results.h"
|
||||
|
||||
namespace zvec {
|
||||
|
||||
class CombinedVectorColumnIndexer {
|
||||
public:
|
||||
using Ptr = std::shared_ptr<CombinedVectorColumnIndexer>;
|
||||
|
||||
explicit CombinedVectorColumnIndexer(
|
||||
const std::vector<VectorColumnIndexer::Ptr> &indexers,
|
||||
const std::vector<VectorColumnIndexer::Ptr> &normal_indexers,
|
||||
const FieldSchema &field_schema, const SegmentMeta &segment_meta,
|
||||
std::vector<BlockMeta> blocks, MetricType metric_type,
|
||||
bool is_quantized = false);
|
||||
|
||||
virtual ~CombinedVectorColumnIndexer() = default;
|
||||
|
||||
virtual Result<IndexResults::Ptr> Search(
|
||||
const vector_column_params::VectorData &vector_data,
|
||||
const vector_column_params::QueryParams &query_params);
|
||||
|
||||
// doc_id is segment local id
|
||||
virtual Result<vector_column_params::VectorDataBuffer> Fetch(
|
||||
uint32_t segment_doc_id) const;
|
||||
|
||||
// for ut
|
||||
protected:
|
||||
CombinedVectorColumnIndexer() = default;
|
||||
|
||||
|
||||
private:
|
||||
FieldSchema field_schema_;
|
||||
std::vector<VectorColumnIndexer::Ptr> indexers_;
|
||||
std::vector<VectorColumnIndexer::Ptr> normal_indexers_;
|
||||
std::vector<BlockMeta> blocks_;
|
||||
MetricType metric_type_{MetricType::UNDEFINED};
|
||||
bool is_quantized_{false};
|
||||
uint64_t min_doc_id_{0};
|
||||
};
|
||||
|
||||
} // namespace zvec
|
||||
@@ -0,0 +1,349 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
#pragma once
|
||||
|
||||
#include <memory>
|
||||
#include <ailego/pattern/expected.hpp>
|
||||
#include "core/interface/index.h"
|
||||
#include "db/common/status.h"
|
||||
#include "db/index/common/doc.h"
|
||||
#include "db/index/common/query_params.h"
|
||||
#include "vector_column_indexer.h"
|
||||
#include "vector_column_params.h"
|
||||
|
||||
|
||||
namespace zvec {
|
||||
// TODO: rename file extension
|
||||
class ProximaEngineHelper {
|
||||
public:
|
||||
static Result<vector_column_params::VectorDataBuffer>
|
||||
move_from_engine_vector_buffer(
|
||||
const core_interface::VectorDataBuffer &&vector_data_buffer,
|
||||
bool is_sparse) {
|
||||
if (is_sparse) {
|
||||
auto sparse_vector_buffer = std::get<core_interface::SparseVectorBuffer>(
|
||||
vector_data_buffer.vector_buffer);
|
||||
return vector_column_params::VectorDataBuffer{
|
||||
vector_column_params::SparseVectorBuffer{
|
||||
std::move(sparse_vector_buffer.indices),
|
||||
std::move(sparse_vector_buffer.values)}};
|
||||
}
|
||||
auto dense_vector_buffer = std::get<core_interface::DenseVectorBuffer>(
|
||||
vector_data_buffer.vector_buffer);
|
||||
return vector_column_params::VectorDataBuffer{
|
||||
vector_column_params::DenseVectorBuffer{
|
||||
std::move(dense_vector_buffer.data)}};
|
||||
}
|
||||
|
||||
static Result<vector_column_params::VectorData> convert_from_engine_vector(
|
||||
const core_interface::VectorData &vector_data, bool is_sparse) {
|
||||
if (is_sparse) {
|
||||
auto engine_vector =
|
||||
std::get<core_interface::SparseVector>(vector_data.vector);
|
||||
return vector_column_params::VectorData{
|
||||
vector_column_params::SparseVector{engine_vector.count,
|
||||
engine_vector.indices,
|
||||
engine_vector.values}};
|
||||
}
|
||||
auto engine_vector =
|
||||
std::get<core_interface::DenseVector>(vector_data.vector);
|
||||
return vector_column_params::VectorData{
|
||||
vector_column_params::DenseVector{engine_vector.data}};
|
||||
}
|
||||
|
||||
// convert to engine vector
|
||||
static Result<core_interface::VectorData> convert_to_engine_vector(
|
||||
const vector_column_params::VectorData &vector_data, bool is_sparse) {
|
||||
if (is_sparse) {
|
||||
auto db_vector =
|
||||
std::get<vector_column_params::SparseVector>(vector_data.vector);
|
||||
auto engine_vector = core_interface::SparseVector{
|
||||
db_vector.count, const_cast<void *>(db_vector.indices),
|
||||
const_cast<void *>(db_vector.values)};
|
||||
return core_interface::VectorData{engine_vector};
|
||||
}
|
||||
|
||||
auto db_vector =
|
||||
std::get<vector_column_params::DenseVector>(vector_data.vector);
|
||||
auto engine_vector =
|
||||
core_interface::DenseVector{const_cast<void *>(db_vector.data)};
|
||||
return core_interface::VectorData{engine_vector};
|
||||
}
|
||||
|
||||
// convert_filter
|
||||
static std::shared_ptr<core_interface::IndexFilter> convert_to_engine_filter(
|
||||
const IndexFilter *filter) {
|
||||
auto engine_filter = std::make_shared<core_interface::IndexFilter>();
|
||||
if (filter != nullptr) {
|
||||
engine_filter->set(
|
||||
[filter](uint64_t id) { return filter->is_filtered(id); });
|
||||
}
|
||||
return engine_filter;
|
||||
}
|
||||
|
||||
private:
|
||||
template <typename EngineQueryParamType>
|
||||
static Result<std::unique_ptr<EngineQueryParamType>>
|
||||
_build_common_query_param(
|
||||
const vector_column_params::QueryParams &db_query_params) {
|
||||
auto engine_query_param = std::make_unique<EngineQueryParamType>();
|
||||
engine_query_param->topk = db_query_params.topk;
|
||||
engine_query_param->fetch_vector = db_query_params.fetch_vector;
|
||||
|
||||
engine_query_param->filter =
|
||||
convert_to_engine_filter(db_query_params.filter);
|
||||
|
||||
if (db_query_params.query_params) {
|
||||
engine_query_param->radius = db_query_params.query_params->radius();
|
||||
engine_query_param->is_linear = db_query_params.query_params->is_linear();
|
||||
}
|
||||
if (db_query_params.refiner_param) {
|
||||
engine_query_param->refiner_param =
|
||||
std::make_shared<core_interface::RefinerParam>(
|
||||
core_interface::RefinerParam{
|
||||
.scale_factor_ = db_query_params.refiner_param->scale_factor_,
|
||||
.reference_index =
|
||||
db_query_params.refiner_param->reference_indexer->index});
|
||||
}
|
||||
|
||||
return engine_query_param;
|
||||
}
|
||||
|
||||
public:
|
||||
static Result<std::unique_ptr<core_interface::BaseIndexQueryParam>>
|
||||
convert_to_engine_query_param(
|
||||
const FieldSchema &field_schema,
|
||||
const vector_column_params::QueryParams &query_params) {
|
||||
if (!field_schema.index_params()) {
|
||||
return tl::make_unexpected(Status::InvalidArgument("nullptr"));
|
||||
}
|
||||
switch (field_schema.index_params()->type()) {
|
||||
case IndexType::FLAT: {
|
||||
// auto db_index_params =
|
||||
// dynamic_cast<const FlatIndexParams
|
||||
// *>(field_schema.index_params());
|
||||
auto flat_query_param_result =
|
||||
_build_common_query_param<core_interface::FlatQueryParam>(
|
||||
query_params);
|
||||
if (!flat_query_param_result.has_value()) {
|
||||
return tl::make_unexpected(Status::InvalidArgument(
|
||||
"failed to build query param: " +
|
||||
flat_query_param_result.error().message()));
|
||||
}
|
||||
return std::move(flat_query_param_result.value());
|
||||
}
|
||||
|
||||
case IndexType::HNSW: {
|
||||
auto hnsw_query_param_result =
|
||||
_build_common_query_param<core_interface::HNSWQueryParam>(
|
||||
query_params);
|
||||
if (!hnsw_query_param_result.has_value()) {
|
||||
return tl::make_unexpected(Status::InvalidArgument(
|
||||
"failed to build query param: " +
|
||||
hnsw_query_param_result.error().message()));
|
||||
}
|
||||
auto &hnsw_query_param = hnsw_query_param_result.value();
|
||||
if (query_params.query_params) {
|
||||
auto db_hnsw_query_params = dynamic_cast<const HnswQueryParams *>(
|
||||
query_params.query_params.get());
|
||||
hnsw_query_param->ef_search = db_hnsw_query_params->ef();
|
||||
}
|
||||
return std::move(hnsw_query_param);
|
||||
}
|
||||
|
||||
case IndexType::IVF: {
|
||||
auto ivf_query_param_result =
|
||||
_build_common_query_param<core_interface::IVFQueryParam>(
|
||||
query_params);
|
||||
if (!ivf_query_param_result.has_value()) {
|
||||
return tl::make_unexpected(Status::InvalidArgument(
|
||||
"failed to build query param: " +
|
||||
ivf_query_param_result.error().message()));
|
||||
}
|
||||
auto &ivf_query_param = ivf_query_param_result.value();
|
||||
if (query_params.query_params) {
|
||||
auto db_ivf_query_params = dynamic_cast<const IVFQueryParams *>(
|
||||
query_params.query_params.get());
|
||||
ivf_query_param->nprobe = db_ivf_query_params->nprobe();
|
||||
}
|
||||
return std::move(ivf_query_param);
|
||||
}
|
||||
default:
|
||||
return tl::make_unexpected(Status::InvalidArgument("not supported"));
|
||||
}
|
||||
}
|
||||
|
||||
static Result<core_interface::MetricType> convert_to_engine_metric_type(
|
||||
MetricType metric_type) {
|
||||
switch (metric_type) {
|
||||
case MetricType::MIPSL2:
|
||||
return core_interface::MetricType::kMIPSL2sq;
|
||||
case MetricType::IP:
|
||||
return core_interface::MetricType::kInnerProduct;
|
||||
case MetricType::L2:
|
||||
return core_interface::MetricType::kL2sq;
|
||||
case MetricType::COSINE:
|
||||
return core_interface::MetricType::kCosine;
|
||||
default:
|
||||
return tl::make_unexpected(
|
||||
Status::InvalidArgument("unsupported metric type"));
|
||||
}
|
||||
}
|
||||
|
||||
static Result<core_interface::QuantizerType> convert_to_engine_quantize_type(
|
||||
QuantizeType quantize_type) {
|
||||
switch (quantize_type) {
|
||||
case QuantizeType::UNDEFINED:
|
||||
return core_interface::QuantizerType::kNone;
|
||||
case QuantizeType::FP16:
|
||||
return core_interface::QuantizerType::kFP16;
|
||||
case QuantizeType::INT8:
|
||||
return core_interface::QuantizerType::kInt8;
|
||||
case QuantizeType::INT4:
|
||||
return core_interface::QuantizerType::kInt4;
|
||||
default:
|
||||
return tl::make_unexpected(
|
||||
Status::InvalidArgument("unsupported quantize type"));
|
||||
}
|
||||
}
|
||||
|
||||
static Result<core_interface::DataType> convert_to_engine_data_type(
|
||||
DataType data_type) {
|
||||
switch (data_type) {
|
||||
case DataType::VECTOR_FP32:
|
||||
case DataType::SPARSE_VECTOR_FP32:
|
||||
return core_interface::DataType::DT_FP32;
|
||||
|
||||
case DataType::VECTOR_FP16:
|
||||
case DataType::SPARSE_VECTOR_FP16:
|
||||
return core_interface::DataType::DT_FP16;
|
||||
|
||||
case DataType::VECTOR_INT8:
|
||||
return core_interface::DataType::DT_INT8;
|
||||
|
||||
default:
|
||||
return tl::make_unexpected(
|
||||
Status::InvalidArgument("unsupported data type"));
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
template <typename DBIndexParamType, typename IndexParamBuilderType>
|
||||
static Result<std::shared_ptr<IndexParamBuilderType>>
|
||||
_build_common_index_param(const FieldSchema &field_schema) {
|
||||
auto db_index_params = dynamic_cast<const DBIndexParamType *>(
|
||||
field_schema.index_params().get());
|
||||
auto index_param_builder = std::make_shared<IndexParamBuilderType>();
|
||||
|
||||
// db will ensure the id is consecutive
|
||||
index_param_builder->WithUseIDMap(false);
|
||||
|
||||
index_param_builder->WithIsSparse(field_schema.is_sparse_vector())
|
||||
.WithDimension(field_schema.dimension());
|
||||
if (auto data_type_result =
|
||||
convert_to_engine_data_type(field_schema.data_type());
|
||||
data_type_result.has_value()) {
|
||||
index_param_builder->WithDataType(data_type_result.value());
|
||||
} else {
|
||||
return tl::make_unexpected(
|
||||
Status::InvalidArgument("unsupported data type"));
|
||||
}
|
||||
if (auto metric_type_result =
|
||||
convert_to_engine_metric_type(db_index_params->metric_type());
|
||||
metric_type_result.has_value()) {
|
||||
index_param_builder->WithMetricType(metric_type_result.value());
|
||||
} else {
|
||||
return tl::make_unexpected(
|
||||
Status::InvalidArgument("unsupported metric type"));
|
||||
}
|
||||
if (auto quantize_type =
|
||||
convert_to_engine_quantize_type(db_index_params->quantize_type());
|
||||
quantize_type.has_value()) {
|
||||
index_param_builder->WithQuantizerParam(
|
||||
core_interface::QuantizerParam(quantize_type.value()));
|
||||
} else {
|
||||
return tl::make_unexpected(
|
||||
Status::InvalidArgument("unsupported quantize type"));
|
||||
}
|
||||
return index_param_builder;
|
||||
}
|
||||
|
||||
public:
|
||||
static Result<core_interface::BaseIndexParam::Pointer>
|
||||
convert_to_engine_index_param(const FieldSchema &field_schema) {
|
||||
if (!field_schema.index_params()) {
|
||||
return tl::make_unexpected(
|
||||
Status::InvalidArgument("field_schema.index_params nullptr"));
|
||||
}
|
||||
|
||||
switch (field_schema.index_params()->type()) {
|
||||
case IndexType::FLAT: {
|
||||
auto index_param_builder =
|
||||
_build_common_index_param<FlatIndexParams,
|
||||
core_interface::FlatIndexParamBuilder>(
|
||||
field_schema);
|
||||
if (!index_param_builder.has_value()) {
|
||||
return tl::make_unexpected(
|
||||
Status::InvalidArgument("failed to build index param: " +
|
||||
index_param_builder.error().message()));
|
||||
}
|
||||
return index_param_builder.value()->Build();
|
||||
}
|
||||
|
||||
case IndexType::HNSW: {
|
||||
auto index_param_builder_result =
|
||||
_build_common_index_param<HnswIndexParams,
|
||||
core_interface::HNSWIndexParamBuilder>(
|
||||
field_schema);
|
||||
if (!index_param_builder_result.has_value()) {
|
||||
return tl::make_unexpected(Status::InvalidArgument(
|
||||
"failed to build index param: " +
|
||||
index_param_builder_result.error().message()));
|
||||
}
|
||||
auto index_param_builder = index_param_builder_result.value();
|
||||
|
||||
auto db_index_params = dynamic_cast<const HnswIndexParams *>(
|
||||
field_schema.index_params().get());
|
||||
index_param_builder->WithM(db_index_params->m());
|
||||
index_param_builder->WithEFConstruction(
|
||||
db_index_params->ef_construction());
|
||||
|
||||
return index_param_builder->Build();
|
||||
}
|
||||
|
||||
case IndexType::IVF: {
|
||||
auto index_param_builder_result = _build_common_index_param<
|
||||
IVFIndexParams, core_interface::IVFIndexParamBuilder>(field_schema);
|
||||
if (!index_param_builder_result.has_value()) {
|
||||
return tl::make_unexpected(Status::InvalidArgument(
|
||||
"failed to build index param: " +
|
||||
index_param_builder_result.error().message()));
|
||||
}
|
||||
auto index_param_builder = index_param_builder_result.value();
|
||||
|
||||
auto db_index_params = dynamic_cast<const IVFIndexParams *>(
|
||||
field_schema.index_params().get());
|
||||
index_param_builder->WithNList(db_index_params->n_list());
|
||||
index_param_builder->WithNiters(db_index_params->n_iters());
|
||||
index_param_builder->WithUseSoar(db_index_params->use_soar());
|
||||
|
||||
return index_param_builder->Build();
|
||||
}
|
||||
|
||||
default:
|
||||
return tl::make_unexpected(Status::InvalidArgument("not supported"));
|
||||
}
|
||||
}
|
||||
};
|
||||
}; // namespace zvec
|
||||
@@ -0,0 +1,207 @@
|
||||
// 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 "vector_column_indexer.h"
|
||||
#include "ailego/pattern/expected.hpp"
|
||||
#include "db/common/status.h"
|
||||
#include "engine_helper.hpp"
|
||||
|
||||
|
||||
namespace zvec {
|
||||
|
||||
Status VectorColumnIndexer::Open(
|
||||
const vector_column_params::ReadOptions &read_options) {
|
||||
if (index != nullptr) {
|
||||
return Status::InvalidArgument("Index already opened");
|
||||
}
|
||||
|
||||
// TODO: pass read_options to proxima index
|
||||
if (engine_name_ == "proxima") {
|
||||
return CreateProximaIndex(read_options);
|
||||
} else {
|
||||
return Status::InvalidArgument("Engine name not supported");
|
||||
}
|
||||
}
|
||||
|
||||
Status VectorColumnIndexer::CreateProximaIndex(
|
||||
const vector_column_params::ReadOptions &read_options) {
|
||||
auto index_param_result =
|
||||
ProximaEngineHelper::convert_to_engine_index_param(field_schema_);
|
||||
if (!index_param_result.has_value()) {
|
||||
return Status::InvalidArgument(index_param_result.error().message());
|
||||
}
|
||||
auto &index_param = index_param_result.value();
|
||||
|
||||
index = core_interface::IndexFactory::CreateAndInitIndex(*index_param);
|
||||
if (index == nullptr) {
|
||||
return Status::InternalError("Failed to create index");
|
||||
}
|
||||
|
||||
auto storage_type =
|
||||
read_options.use_mmap
|
||||
? core_interface::StorageOptions::StorageType::kMMAP
|
||||
: core_interface::StorageOptions::StorageType::kBufferPool;
|
||||
|
||||
if (0 != index->Open(this->index_file_path(),
|
||||
{storage_type, read_options.create_new,
|
||||
read_options.read_only})) {
|
||||
return Status::InternalError("Failed to open index");
|
||||
}
|
||||
|
||||
return Status::OK();
|
||||
}
|
||||
|
||||
Status VectorColumnIndexer::Flush() {
|
||||
if (index == nullptr) {
|
||||
return Status::InvalidArgument("Index not opened");
|
||||
}
|
||||
|
||||
if (0 != index->Flush()) {
|
||||
return Status::InternalError("Failed to flush index");
|
||||
}
|
||||
return Status::OK();
|
||||
}
|
||||
|
||||
|
||||
Status VectorColumnIndexer::Close() {
|
||||
if (index == nullptr) {
|
||||
return Status::InvalidArgument("Index not opened");
|
||||
}
|
||||
|
||||
if (0 != index->Close()) {
|
||||
return Status::InternalError("Failed to close index");
|
||||
}
|
||||
index.reset();
|
||||
return Status::OK();
|
||||
}
|
||||
|
||||
Status VectorColumnIndexer::Destroy() {
|
||||
if (index == nullptr) {
|
||||
return Status::InvalidArgument("Index not opened");
|
||||
}
|
||||
|
||||
if (Close() != Status::OK()) {
|
||||
return Status::InternalError("Failed to close index");
|
||||
}
|
||||
if (!ailego::File::RemovePath(index_file_path_)) {
|
||||
return Status::InternalError("Failed to remove index file");
|
||||
}
|
||||
return Status::OK();
|
||||
}
|
||||
|
||||
Status VectorColumnIndexer::Merge(
|
||||
const std::vector<VectorColumnIndexer::Ptr> &indexers,
|
||||
const IndexFilter::Ptr &filter,
|
||||
const vector_column_params::MergeOptions &merge_options) {
|
||||
if (index == nullptr) {
|
||||
return Status::InvalidArgument("Index not opened");
|
||||
}
|
||||
|
||||
if (indexers.empty()) {
|
||||
return Status::OK();
|
||||
}
|
||||
|
||||
auto engine_indexers = std::vector<core_interface::Index::Pointer>();
|
||||
|
||||
for (auto &indexer : indexers) {
|
||||
if (indexer->index_file_path() == this->index_file_path()) {
|
||||
continue;
|
||||
}
|
||||
engine_indexers.push_back(indexer->index);
|
||||
}
|
||||
auto engine_filter =
|
||||
ProximaEngineHelper::convert_to_engine_filter(filter.get());
|
||||
if (engine_filter == nullptr) {
|
||||
return Status::InvalidArgument("Failed to convert filter");
|
||||
}
|
||||
if (0 !=
|
||||
index->Merge(engine_indexers, *engine_filter,
|
||||
{merge_options.write_concurrency, merge_options.pool})) {
|
||||
return Status::InternalError("Failed to merge index");
|
||||
}
|
||||
return Status::OK();
|
||||
}
|
||||
|
||||
Status VectorColumnIndexer::Insert(
|
||||
const vector_column_params::VectorData &vector_data, uint32_t doc_id) {
|
||||
if (index == nullptr) {
|
||||
return Status::InvalidArgument("Index not opened");
|
||||
}
|
||||
|
||||
auto engine_vector_data =
|
||||
ProximaEngineHelper::convert_to_engine_vector(vector_data, is_sparse_);
|
||||
if (0 != index->Add(engine_vector_data.value(), doc_id)) {
|
||||
return Status::InternalError("Failed to add vector to index");
|
||||
}
|
||||
return Status::OK();
|
||||
}
|
||||
|
||||
Result<vector_column_params::VectorDataBuffer> VectorColumnIndexer::Fetch(
|
||||
uint32_t doc_id) const {
|
||||
if (index == nullptr) {
|
||||
return tl::make_unexpected(Status::InvalidArgument("Index not opened"));
|
||||
}
|
||||
|
||||
auto vector_data_buffer = core_interface::VectorDataBuffer();
|
||||
|
||||
if (0 != index->Fetch(doc_id, &vector_data_buffer)) {
|
||||
return tl::make_unexpected(
|
||||
Status::InternalError("Failed to fetch vector from index"));
|
||||
}
|
||||
return ProximaEngineHelper::move_from_engine_vector_buffer(
|
||||
std::move(vector_data_buffer), is_sparse_)
|
||||
.value();
|
||||
}
|
||||
|
||||
Result<IndexResults::Ptr> VectorColumnIndexer::Search(
|
||||
const vector_column_params::VectorData &vector_data,
|
||||
const vector_column_params::QueryParams &query_params) {
|
||||
if (index == nullptr) {
|
||||
return tl::make_unexpected(Status::InvalidArgument("Index not opened"));
|
||||
}
|
||||
|
||||
auto engine_vector_data =
|
||||
ProximaEngineHelper::convert_to_engine_vector(vector_data, is_sparse_);
|
||||
core_interface::SearchResult search_result;
|
||||
auto engine_query_param_result =
|
||||
ProximaEngineHelper::convert_to_engine_query_param(field_schema_,
|
||||
query_params);
|
||||
if (!engine_query_param_result.has_value()) {
|
||||
return tl::make_unexpected(engine_query_param_result.error());
|
||||
}
|
||||
auto &engine_query_param = engine_query_param_result.value();
|
||||
if (query_params.bf_pks.size() > 1) {
|
||||
LOG_ERROR("bf_pks size > 1 is not supported");
|
||||
return tl::make_unexpected(
|
||||
Status::InvalidArgument("bf_pks size > 1 is not supported"));
|
||||
} else if (query_params.bf_pks.size() == 1) {
|
||||
auto &bf_pks = query_params.bf_pks[0];
|
||||
engine_query_param->bf_pks =
|
||||
std::make_shared<std::vector<uint64_t>>(std::move(bf_pks));
|
||||
} else {
|
||||
engine_query_param->bf_pks = nullptr;
|
||||
}
|
||||
if (0 != index->Search(engine_vector_data.value(),
|
||||
std::move(engine_query_param), &search_result)) {
|
||||
return tl::make_unexpected(
|
||||
Status::InternalError("Failed to search vector"));
|
||||
}
|
||||
|
||||
auto result = std::make_shared<VectorIndexResults>(
|
||||
is_sparse_, std::move(search_result.doc_list_),
|
||||
std::move(search_result.reverted_vector_list_),
|
||||
std::move(search_result.reverted_sparse_values_list_));
|
||||
return result;
|
||||
}
|
||||
|
||||
} // namespace zvec
|
||||
@@ -0,0 +1,131 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
#pragma once
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <variant>
|
||||
#include <ailego/parallel/lock.h>
|
||||
#include <ailego/pattern/expected.hpp>
|
||||
#include <ailego/utility/string_helper.h>
|
||||
#include <core/interface/index_factory.h>
|
||||
#include "core/interface/index.h"
|
||||
#include "core/interface/index_param.h"
|
||||
#include "db/common/constants.h"
|
||||
#include "db/common/status.h"
|
||||
#include "db/common/typedef.h"
|
||||
#include "db/index/column/common/index_results.h"
|
||||
#include "db/index/common/meta.h"
|
||||
#include "db/index/common/schema.h"
|
||||
#include "vector_column_params.h"
|
||||
#include "vector_index_results.h"
|
||||
|
||||
namespace zvec {
|
||||
|
||||
class ProximaEngineHelper;
|
||||
|
||||
class VectorColumnIndexer {
|
||||
public:
|
||||
using Ptr = std::shared_ptr<VectorColumnIndexer>;
|
||||
PROXIMA_DISALLOW_COPY_AND_ASSIGN(VectorColumnIndexer);
|
||||
|
||||
VectorColumnIndexer(const std::string &index_file_path,
|
||||
const FieldSchema &field_schema,
|
||||
const std::string &engine_name = "proxima")
|
||||
: field_schema_(field_schema),
|
||||
index_file_path_(index_file_path),
|
||||
engine_name_(engine_name) {
|
||||
// assert(field_schema.is_dense_vector() ||
|
||||
// field_schema.is_sparse_vector());
|
||||
is_sparse_ = field_schema.is_sparse_vector();
|
||||
}
|
||||
|
||||
virtual ~VectorColumnIndexer() = default;
|
||||
|
||||
public:
|
||||
Status Open(const vector_column_params::ReadOptions &read_options);
|
||||
|
||||
Status Flush();
|
||||
|
||||
// Close will call Flush()
|
||||
Status Close();
|
||||
|
||||
// Destroy will call Close() and remove index file
|
||||
Status Destroy();
|
||||
|
||||
|
||||
// If HNSWIndexer.merge([FlatIndexer1, FlatIndexer2])
|
||||
// then the merged indexer is a HNSWIndexer
|
||||
Status Merge(const std::vector<VectorColumnIndexer::Ptr> &indexers,
|
||||
const IndexFilter::Ptr &filter = nullptr,
|
||||
const vector_column_params::MergeOptions &merge_options = {});
|
||||
// TODO: should we use this function? or a Reducer?
|
||||
// TODO: sstatic reduce, optimize; iterator/scan
|
||||
|
||||
|
||||
//! Insert vector
|
||||
Status Insert(const vector_column_params::VectorData &vector_data,
|
||||
uint32_t doc_id);
|
||||
// TODO: batch insert
|
||||
|
||||
virtual Result<IndexResults::Ptr> Search(
|
||||
const vector_column_params::VectorData &vector_data,
|
||||
const vector_column_params::QueryParams &query_params);
|
||||
// Result<std::vector<IndexResults::Ptr>> BatchSearch(
|
||||
// const VectorDataset &vector_data,
|
||||
// const vector_column_params::QueryParams &query_params);
|
||||
|
||||
Result<vector_column_params::VectorDataBuffer> Fetch(uint32_t doc_id) const;
|
||||
// Result<VectorDataset> BatchFetch(const std::vector<uint32_t> &doc_ids)
|
||||
// const;
|
||||
|
||||
|
||||
public:
|
||||
std::string index_file_path() const {
|
||||
return index_file_path_;
|
||||
}
|
||||
|
||||
size_t doc_count() const {
|
||||
if (index == nullptr) {
|
||||
return -1;
|
||||
}
|
||||
return index->GetDocCount();
|
||||
}
|
||||
|
||||
// for ut
|
||||
protected:
|
||||
VectorColumnIndexer() = default;
|
||||
|
||||
private:
|
||||
// protected:
|
||||
// virtual bool init_proxima_params() = 0;
|
||||
|
||||
// proxima or other engine index param like VSAGE
|
||||
// build proxima index
|
||||
Status CreateProximaIndex(
|
||||
const vector_column_params::ReadOptions &read_options);
|
||||
|
||||
protected:
|
||||
friend ProximaEngineHelper;
|
||||
core_interface::Index::Pointer index;
|
||||
FieldSchema field_schema_{};
|
||||
std::string index_file_path_{};
|
||||
|
||||
|
||||
std::string engine_name_ = "proxima";
|
||||
bool is_sparse_{false}; // TODO: eliminate the dynamic flag and make it
|
||||
// static/template/seperate class
|
||||
};
|
||||
|
||||
|
||||
} // namespace zvec
|
||||
@@ -0,0 +1,113 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
#pragma once
|
||||
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <variant>
|
||||
#include <vector>
|
||||
#include <ailego/container/params.h>
|
||||
#include <ailego/parallel/thread_pool.h>
|
||||
// #include <aitheta2/index_params.h>
|
||||
// #include "common/constants.h"
|
||||
#include "core/interface/index_param.h"
|
||||
#include "db/index/common/index_filter.h"
|
||||
#include "db/index/common/query_params.h"
|
||||
#include "db/index/common/type.h"
|
||||
|
||||
namespace zvec {
|
||||
class VectorColumnIndexer;
|
||||
|
||||
namespace vector_column_params {
|
||||
struct DenseVector {
|
||||
const void *data;
|
||||
};
|
||||
|
||||
struct SparseVector {
|
||||
uint32_t count;
|
||||
const void *indices; // uint32
|
||||
const void *values; // FP16/FP32
|
||||
};
|
||||
|
||||
struct VectorData {
|
||||
std::variant<DenseVector, SparseVector> vector;
|
||||
};
|
||||
|
||||
|
||||
// VectorData with memory management
|
||||
struct DenseVectorBuffer {
|
||||
std::string data; // use string to manage memory
|
||||
};
|
||||
|
||||
struct SparseVectorBuffer {
|
||||
std::string indices; // uint32_t
|
||||
std::string values;
|
||||
|
||||
using IndexType = uint32_t;
|
||||
uint32_t count() const {
|
||||
return indices.size() / sizeof(IndexType);
|
||||
}
|
||||
};
|
||||
|
||||
struct VectorDataBuffer {
|
||||
std::variant<DenseVectorBuffer, SparseVectorBuffer> vector_buffer;
|
||||
};
|
||||
|
||||
|
||||
struct ReadOptions {
|
||||
bool use_mmap{true};
|
||||
bool create_new{false};
|
||||
bool read_only{false};
|
||||
};
|
||||
|
||||
struct MergeOptions {
|
||||
uint32_t write_concurrency{1};
|
||||
ailego::ThreadPool *pool{nullptr};
|
||||
};
|
||||
|
||||
struct GroupByParams {
|
||||
GroupByParams(uint32_t group_topk, uint32_t group_count,
|
||||
std::function<std::string(uint64_t key)> group_by)
|
||||
: group_topk(group_topk),
|
||||
group_count(group_count),
|
||||
group_by(std::move(group_by)) {}
|
||||
|
||||
uint32_t group_topk{0};
|
||||
uint32_t group_count{0};
|
||||
std::function<std::string(uint64_t key)> group_by{};
|
||||
};
|
||||
|
||||
struct RefinerParam {
|
||||
float scale_factor_{10};
|
||||
std::shared_ptr<VectorColumnIndexer> reference_indexer{nullptr};
|
||||
};
|
||||
|
||||
// This is an internal version, while QueryParams in doc.h is an interface ver
|
||||
struct QueryParams {
|
||||
DataType data_type{DataType::UNDEFINED};
|
||||
uint32_t dimension{0U};
|
||||
uint32_t topk{0U};
|
||||
mutable const IndexFilter *filter{nullptr};
|
||||
bool fetch_vector{false};
|
||||
zvec::QueryParams::Ptr query_params;
|
||||
std::unique_ptr<GroupByParams> group_by;
|
||||
// TODO: 1. should be uint32? 2. if no batch mode, change to optional<vector>
|
||||
std::vector<std::vector<uint64_t>> bf_pks{};
|
||||
|
||||
std::shared_ptr<RefinerParam> refiner_param{nullptr};
|
||||
|
||||
ailego::Params extra_params{};
|
||||
};
|
||||
} // namespace vector_column_params
|
||||
} // namespace zvec
|
||||
@@ -0,0 +1,282 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
#pragma once
|
||||
|
||||
#include <cstddef>
|
||||
#include <memory>
|
||||
#include "core/framework/index_document.h"
|
||||
#include "db/common/typedef.h"
|
||||
#include "db/index/column/common/index_results.h"
|
||||
|
||||
// TODO: eliminate aitheta2 dependency for decoupling
|
||||
|
||||
namespace zvec {
|
||||
|
||||
class VectorIndexResults : public IndexResults {
|
||||
public:
|
||||
class VectorIterator : public IndexResults::Iterator {
|
||||
public:
|
||||
VectorIterator(const VectorIndexResults *rs) : rs_(rs) {}
|
||||
|
||||
VectorIterator(const VectorIndexResults *rs, uint32_t index)
|
||||
: rs_(rs), index_(index) {}
|
||||
|
||||
public:
|
||||
idx_t doc_id() const override {
|
||||
return rs_->document(index_).key();
|
||||
}
|
||||
|
||||
float score() const override {
|
||||
return rs_->document(index_).score();
|
||||
}
|
||||
|
||||
void next() override {
|
||||
index_++;
|
||||
}
|
||||
|
||||
bool valid() const override {
|
||||
return (index_ < rs_->count());
|
||||
}
|
||||
|
||||
const vector_column_params::VectorData vector() const override {
|
||||
if (is_sparse()) {
|
||||
return vector_column_params::VectorData{
|
||||
vector_column_params::SparseVector{sparse_count(),
|
||||
sparse_indices().data(),
|
||||
sparse_values().data()}};
|
||||
}
|
||||
return vector_column_params::VectorData{
|
||||
vector_column_params::DenseVector{dense_vector()}};
|
||||
}
|
||||
|
||||
private:
|
||||
const void *dense_vector() const {
|
||||
if (!rs_->reverted_vector_list_.empty()) {
|
||||
return rs_->reverted_vector_list_[index_].data();
|
||||
}
|
||||
return rs_->document(index_).vector();
|
||||
}
|
||||
uint32_t sparse_count() const {
|
||||
return rs_->document(index_).sparse_doc().sparse_count();
|
||||
}
|
||||
|
||||
const std::string &sparse_indices() const {
|
||||
return rs_->document(index_).sparse_doc().sparse_indices();
|
||||
}
|
||||
|
||||
const std::string &sparse_values() const {
|
||||
if (!rs_->reverted_sparse_values_list_.empty()) {
|
||||
return rs_->reverted_sparse_values_list_[index_];
|
||||
}
|
||||
return rs_->document(index_).sparse_doc().sparse_values();
|
||||
}
|
||||
|
||||
private:
|
||||
const VectorIndexResults *rs_{nullptr};
|
||||
uint32_t index_{0U};
|
||||
};
|
||||
|
||||
friend class VectorIterator;
|
||||
|
||||
public:
|
||||
// VectorIndexResults(core::IndexDocumentList &&doc_list)
|
||||
// : docs_(std::move(doc_list)) {}
|
||||
//
|
||||
// VectorIndexResults(core::IndexDocumentList &&doc_list,
|
||||
// std::vector<std::string> &&reverted_vector_list)
|
||||
// : docs_(std::move(doc_list)),
|
||||
// reverted_vector_list_(std::move(reverted_vector_list)) {}
|
||||
VectorIndexResults(bool is_sparse, core::IndexDocumentList &&doc_list,
|
||||
std::vector<std::string> &&reverted_vector_list,
|
||||
std::vector<std::string> &&reverted_sparse_values_list)
|
||||
: is_sparse_(is_sparse),
|
||||
docs_(std::move(doc_list)),
|
||||
reverted_vector_list_(std::move(reverted_vector_list)),
|
||||
reverted_sparse_values_list_(std::move(reverted_sparse_values_list)) {}
|
||||
|
||||
public:
|
||||
IndexResults::IteratorUPtr create_iterator() override {
|
||||
auto ret = std::unique_ptr<VectorIterator>(new VectorIterator(this));
|
||||
ret->set_is_sparse(is_sparse_);
|
||||
return ret;
|
||||
}
|
||||
|
||||
size_t count() const override {
|
||||
return docs_.size();
|
||||
}
|
||||
|
||||
public: // unique method
|
||||
core::IndexDocumentList &docs() {
|
||||
return docs_;
|
||||
}
|
||||
|
||||
std::vector<std::string> &reverted_vector_list() {
|
||||
return reverted_vector_list_;
|
||||
}
|
||||
|
||||
std::vector<std::string> &reverted_sparse_values_list() {
|
||||
return reverted_sparse_values_list_;
|
||||
}
|
||||
|
||||
|
||||
private:
|
||||
const core::IndexDocument &document(size_t index) const {
|
||||
return docs_[index];
|
||||
}
|
||||
|
||||
private:
|
||||
bool is_sparse_;
|
||||
core::IndexDocumentList docs_{};
|
||||
std::vector<std::string> reverted_vector_list_{};
|
||||
std::vector<std::string> reverted_sparse_values_list_{};
|
||||
};
|
||||
|
||||
class GroupVectorIndexResults : public IndexResults {
|
||||
public:
|
||||
class GroupVectorIterator : public IndexResults::Iterator {
|
||||
public:
|
||||
GroupVectorIterator(const GroupVectorIndexResults *rs) : rs_(rs) {}
|
||||
|
||||
public:
|
||||
idx_t doc_id() const override {
|
||||
return rs_->document(group_index_, doc_index_).key();
|
||||
}
|
||||
|
||||
float score() const override {
|
||||
return rs_->document(group_index_, doc_index_).score();
|
||||
}
|
||||
|
||||
void next() override {
|
||||
doc_index_++;
|
||||
if (doc_index_ >= rs_->groups_[group_index_].docs().size()) {
|
||||
group_index_++;
|
||||
doc_index_ = 0;
|
||||
}
|
||||
}
|
||||
|
||||
bool valid() const override {
|
||||
return group_index_ < rs_->groups_.size();
|
||||
}
|
||||
|
||||
const vector_column_params::VectorData vector() const override {
|
||||
if (is_sparse()) {
|
||||
return vector_column_params::VectorData{
|
||||
vector_column_params::SparseVector{sparse_count(),
|
||||
sparse_indices().data(),
|
||||
sparse_values().data()}};
|
||||
}
|
||||
return vector_column_params::VectorData{
|
||||
vector_column_params::DenseVector{dense_vector()}};
|
||||
}
|
||||
|
||||
private:
|
||||
const void *dense_vector() const {
|
||||
if (!rs_->reverted_vector_list_.empty()) {
|
||||
return rs_->reverted_vector_list_[group_index_][doc_index_].data();
|
||||
}
|
||||
return rs_->document(group_index_, doc_index_).vector();
|
||||
}
|
||||
|
||||
uint32_t sparse_count() const {
|
||||
return rs_->document(group_index_, doc_index_)
|
||||
.sparse_doc()
|
||||
.sparse_count();
|
||||
}
|
||||
|
||||
const std::string &sparse_indices() const {
|
||||
return rs_->document(group_index_, doc_index_)
|
||||
.sparse_doc()
|
||||
.sparse_indices();
|
||||
}
|
||||
|
||||
const std::string &sparse_values() const {
|
||||
if (!rs_->reverted_sparse_values_list_.empty()) {
|
||||
return rs_->reverted_sparse_values_list_[group_index_][doc_index_];
|
||||
}
|
||||
return rs_->document(group_index_, doc_index_)
|
||||
.sparse_doc()
|
||||
.sparse_values();
|
||||
}
|
||||
|
||||
const std::string &group_id() const override {
|
||||
return rs_->groups_[group_index_].group_id();
|
||||
}
|
||||
|
||||
private:
|
||||
const GroupVectorIndexResults *rs_{nullptr};
|
||||
uint32_t group_index_{0U};
|
||||
uint32_t doc_index_{0U};
|
||||
};
|
||||
|
||||
friend class GroupVectorIterator;
|
||||
|
||||
public:
|
||||
GroupVectorIndexResults(core::IndexGroupDocumentList &&group_list)
|
||||
: groups_(std::move(group_list)) {
|
||||
init_count();
|
||||
}
|
||||
|
||||
GroupVectorIndexResults(
|
||||
core::IndexGroupDocumentList &&group_list,
|
||||
std::vector<std::vector<std::string>> &&reverted_vector_list)
|
||||
: groups_(std::move(group_list)),
|
||||
reverted_vector_list_(std::move(reverted_vector_list)) {
|
||||
init_count();
|
||||
}
|
||||
|
||||
GroupVectorIndexResults(
|
||||
core::IndexGroupDocumentList &&group_list,
|
||||
std::vector<std::vector<std::string>> &&reverted_vector_list,
|
||||
std::vector<std::vector<std::string>> &&reverted_sparse_values_list)
|
||||
: groups_(std::move(group_list)),
|
||||
reverted_vector_list_(std::move(reverted_vector_list)),
|
||||
reverted_sparse_values_list_(std::move(reverted_sparse_values_list)) {}
|
||||
|
||||
public:
|
||||
IndexResults::IteratorUPtr create_iterator() override {
|
||||
return std::unique_ptr<GroupVectorIterator>(new GroupVectorIterator(this));
|
||||
}
|
||||
|
||||
|
||||
size_t count() const override {
|
||||
return count_;
|
||||
}
|
||||
|
||||
public: // unique method
|
||||
core::IndexGroupDocumentList &groups() {
|
||||
return groups_;
|
||||
}
|
||||
|
||||
private:
|
||||
const core::IndexDocument &document(size_t group_index,
|
||||
size_t doc_index) const {
|
||||
return groups_[group_index].docs()[doc_index];
|
||||
}
|
||||
|
||||
void init_count() {
|
||||
count_ = 0;
|
||||
for (const auto &group : groups_) {
|
||||
count_ += group.docs().size();
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
core::IndexGroupDocumentList groups_{};
|
||||
std::vector<std::vector<std::string>> reverted_vector_list_{};
|
||||
std::vector<std::vector<std::string>> reverted_sparse_values_list_{};
|
||||
size_t count_{0};
|
||||
};
|
||||
|
||||
|
||||
} // namespace zvec
|
||||
@@ -0,0 +1,152 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#pragma once
|
||||
|
||||
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include "db/common/concurrent_roaring_bitmap.h"
|
||||
#include "index_filter.h"
|
||||
|
||||
|
||||
namespace zvec {
|
||||
|
||||
|
||||
class DeleteStore : public std::enable_shared_from_this<DeleteStore> {
|
||||
public:
|
||||
using Ptr = std::shared_ptr<DeleteStore>;
|
||||
|
||||
explicit DeleteStore(std::string collection_name)
|
||||
: collection_name_(std::move(collection_name)) {};
|
||||
|
||||
~DeleteStore() {
|
||||
LOG_INFO("Closed delete store");
|
||||
}
|
||||
|
||||
static Ptr CreateAndLoad(std::string collection_name,
|
||||
const std::string &file_path) {
|
||||
if (file_path.empty()) {
|
||||
LOG_ERROR("File path is empty");
|
||||
return nullptr;
|
||||
}
|
||||
DeleteStore::Ptr ptr =
|
||||
std::make_shared<DeleteStore>(std::move(collection_name));
|
||||
if (ptr->load(file_path).ok()) {
|
||||
return ptr;
|
||||
} else {
|
||||
return nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private:
|
||||
DeleteStore(const DeleteStore &) = delete;
|
||||
DeleteStore &operator=(const DeleteStore &) = delete;
|
||||
DeleteStore &operator=(DeleteStore &&) = delete;
|
||||
|
||||
|
||||
public:
|
||||
class Filter : public IndexFilter {
|
||||
public:
|
||||
explicit Filter(std::shared_ptr<const DeleteStore> delete_store)
|
||||
: delete_store_(std::move(delete_store)) {}
|
||||
|
||||
bool is_filtered(uint64_t id) const override {
|
||||
return delete_store_->is_deleted(id);
|
||||
}
|
||||
|
||||
private:
|
||||
const std::shared_ptr<const DeleteStore> delete_store_;
|
||||
};
|
||||
|
||||
Status load(const std::string &file_path) {
|
||||
Status status = bitmap_.deserialize(file_path);
|
||||
if (status.ok()) {
|
||||
empty_ = bitmap_.cardinality() == 0 ? true : false;
|
||||
LOG_INFO("Opened delete store, count[%lu]", bitmap_.cardinality());
|
||||
} else {
|
||||
LOG_ERROR("Failed to load delete store from file[%s]", file_path.c_str());
|
||||
}
|
||||
return status;
|
||||
}
|
||||
|
||||
Status flush(const std::string &file_path) {
|
||||
Status status = bitmap_.serialize(file_path, true);
|
||||
if (status.ok()) {
|
||||
LOG_DEBUG("Flushed delete store to file[%s]", file_path.c_str());
|
||||
modified_since_last_flush_ = false;
|
||||
} else {
|
||||
LOG_ERROR("Failed to flush delete store to file[%s]", file_path.c_str());
|
||||
}
|
||||
return status;
|
||||
}
|
||||
|
||||
void mark_deleted(uint64_t doc_id) {
|
||||
bitmap_.add(doc_id);
|
||||
empty_ = false;
|
||||
modified_since_last_flush_ = true;
|
||||
}
|
||||
|
||||
bool is_deleted(uint64_t doc_id) const {
|
||||
return bitmap_.contains(doc_id);
|
||||
}
|
||||
|
||||
std::shared_ptr<IndexFilter> make_filter() const {
|
||||
return empty_ ? nullptr : std::make_shared<Filter>(shared_from_this());
|
||||
};
|
||||
|
||||
size_t storage_size_in_bytes() const {
|
||||
return bitmap_.storage_size_in_bytes();
|
||||
}
|
||||
|
||||
size_t count() const {
|
||||
return bitmap_.cardinality();
|
||||
}
|
||||
|
||||
size_t range_count(uint64_t min_doc_id, uint64_t max_doc_id) const {
|
||||
return bitmap_.range_cardinality(min_doc_id, max_doc_id);
|
||||
}
|
||||
|
||||
const std::string &collection_name() const {
|
||||
return collection_name_;
|
||||
}
|
||||
|
||||
bool modified_since_last_flush() const {
|
||||
return modified_since_last_flush_;
|
||||
}
|
||||
|
||||
Ptr clone() const {
|
||||
auto ptr = std::make_shared<DeleteStore>(collection_name_);
|
||||
ptr->bitmap_ = bitmap_;
|
||||
ptr->empty_ = bitmap_.cardinality() == 0 ? true : false;
|
||||
ptr->modified_since_last_flush_ = false;
|
||||
return ptr;
|
||||
}
|
||||
|
||||
bool empty() const {
|
||||
return empty_;
|
||||
}
|
||||
|
||||
private:
|
||||
using FILE = ailego::File;
|
||||
|
||||
const std::string collection_name_{};
|
||||
ConcurrentRoaringBitmap64 bitmap_{};
|
||||
bool empty_{true};
|
||||
bool modified_since_last_flush_{false};
|
||||
};
|
||||
|
||||
|
||||
} // namespace zvec
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,381 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
#pragma once
|
||||
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
#include <variant>
|
||||
#include <ailego/utility/float_helper.h>
|
||||
#include "db/common/status.h"
|
||||
#include "query_params.h"
|
||||
#include "schema.h"
|
||||
#include "type.h"
|
||||
|
||||
namespace zvec {
|
||||
|
||||
using float16_t = ailego::Float16;
|
||||
|
||||
class Doc {
|
||||
public:
|
||||
using Value = std::variant<
|
||||
std::monostate, // 0 - represents null value
|
||||
bool, int32_t, uint32_t, int64_t, uint64_t, float, double, // 1~7
|
||||
std::string, // 8
|
||||
std::vector<bool>, // 9
|
||||
std::vector<int8_t>, // 10
|
||||
std::vector<int16_t>, // 11
|
||||
std::vector<int32_t>, // 12
|
||||
std::vector<int64_t>, // 13
|
||||
std::vector<uint32_t>, // 14
|
||||
std::vector<uint64_t>, // 15
|
||||
std::vector<float16_t>, // 16
|
||||
std::vector<float>, // 17
|
||||
std::vector<double>, // 18
|
||||
std::vector<std::string>, // 19
|
||||
std::pair<std::vector<uint32_t>, std::vector<float>>, // 20
|
||||
std::pair<std::vector<uint32_t>, std::vector<float16_t>>>; // 21
|
||||
|
||||
using Ptr = std::shared_ptr<Doc>;
|
||||
|
||||
Doc() = default;
|
||||
~Doc() = default;
|
||||
|
||||
Doc(const Doc &) = default;
|
||||
Doc &operator=(const Doc &) = default;
|
||||
Doc(Doc &&) = default;
|
||||
Doc &operator=(Doc &&) = default;
|
||||
|
||||
public:
|
||||
void set_pk(std::string pk) {
|
||||
pk_ = std::move(pk);
|
||||
}
|
||||
|
||||
std::string pk() const {
|
||||
return pk_;
|
||||
}
|
||||
|
||||
void set_score(float score) {
|
||||
score_ = score;
|
||||
}
|
||||
|
||||
float score() const {
|
||||
return score_;
|
||||
}
|
||||
|
||||
void set_doc_id(uint64_t doc_id) {
|
||||
doc_id_ = doc_id;
|
||||
}
|
||||
|
||||
uint64_t doc_id() const {
|
||||
return doc_id_;
|
||||
}
|
||||
|
||||
std::vector<std::string> field_names() const {
|
||||
std::vector<std::string> names;
|
||||
names.reserve(fields_.size());
|
||||
|
||||
for (const auto &[name, _] : fields_) {
|
||||
names.emplace_back(name);
|
||||
}
|
||||
|
||||
return names;
|
||||
}
|
||||
|
||||
void set_operator(const Operator op) {
|
||||
op_ = op;
|
||||
}
|
||||
|
||||
Operator get_operator() {
|
||||
return op_;
|
||||
}
|
||||
|
||||
// Set field value
|
||||
template <typename T>
|
||||
bool set(const std::string &field_name, T value) {
|
||||
// TODO: support char*
|
||||
static_assert(is_valid_type_v<T>, "Unsupported type");
|
||||
fields_[field_name] = std::move(value);
|
||||
return true;
|
||||
}
|
||||
|
||||
// Set field to null
|
||||
void set_null(const std::string &field_name) {
|
||||
fields_[field_name] = std::monostate{};
|
||||
}
|
||||
|
||||
// Check if field exists
|
||||
bool has(const std::string &field_name) const {
|
||||
return fields_.find(field_name) != fields_.end();
|
||||
}
|
||||
|
||||
// Check if field exists and is not null
|
||||
bool has_value(const std::string &field_name) const {
|
||||
auto it = fields_.find(field_name);
|
||||
if (it == fields_.end()) {
|
||||
return false;
|
||||
}
|
||||
return !std::holds_alternative<std::monostate>(it->second);
|
||||
}
|
||||
|
||||
// Check if field is null
|
||||
bool is_null(const std::string &field_name) const {
|
||||
auto it = fields_.find(field_name);
|
||||
if (it == fields_.end()) {
|
||||
return false; // Field does not exist is not equal to null
|
||||
}
|
||||
return std::holds_alternative<std::monostate>(it->second);
|
||||
}
|
||||
|
||||
// Check if fields is empty
|
||||
bool is_empty() const {
|
||||
return fields_.empty();
|
||||
}
|
||||
|
||||
// Field get status enumeration
|
||||
enum class FieldGetStatus {
|
||||
SUCCESS, // Successfully got value
|
||||
NOT_FOUND, // Field does not exist
|
||||
IS_NULL, // Field exists but is null
|
||||
TYPE_MISMATCH // Field exists but type mismatch
|
||||
};
|
||||
|
||||
// Field get result template class
|
||||
template <typename T>
|
||||
class FieldGetResult {
|
||||
public:
|
||||
// Constructor - success case
|
||||
explicit FieldGetResult(const T &value)
|
||||
: status_(FieldGetStatus::SUCCESS), value_(value) {}
|
||||
|
||||
// Constructor - error case
|
||||
explicit FieldGetResult(FieldGetStatus status) : status_(status) {
|
||||
if (status == FieldGetStatus::SUCCESS) {
|
||||
throw std::invalid_argument("Use value constructor for SUCCESS status");
|
||||
}
|
||||
}
|
||||
|
||||
// Get status
|
||||
FieldGetStatus status() const {
|
||||
return status_;
|
||||
}
|
||||
|
||||
// Get value (only available when successful)
|
||||
const T &value() const {
|
||||
if (status_ != FieldGetStatus::SUCCESS) {
|
||||
throw std::runtime_error("No value available");
|
||||
}
|
||||
return value_;
|
||||
}
|
||||
|
||||
// Check if successful
|
||||
bool ok() const {
|
||||
return status_ == FieldGetStatus::SUCCESS;
|
||||
}
|
||||
|
||||
// Convert to optional
|
||||
operator std::optional<T>() const {
|
||||
if (status_ == FieldGetStatus::SUCCESS) {
|
||||
return value_;
|
||||
}
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
private:
|
||||
FieldGetStatus status_;
|
||||
T value_;
|
||||
};
|
||||
|
||||
|
||||
// Get field value, distinguish between not found, null and type mismatch
|
||||
// cases
|
||||
template <typename T>
|
||||
typename Doc::template FieldGetResult<T> get_field(
|
||||
const std::string &field_name) const {
|
||||
static_assert(is_valid_type_v<T>, "Unsupported type");
|
||||
|
||||
auto it = fields_.find(field_name);
|
||||
if (it == fields_.end()) {
|
||||
return FieldGetResult<T>(FieldGetStatus::NOT_FOUND);
|
||||
}
|
||||
|
||||
if (std::holds_alternative<std::monostate>(it->second)) {
|
||||
return FieldGetResult<T>(FieldGetStatus::IS_NULL);
|
||||
}
|
||||
|
||||
try {
|
||||
return FieldGetResult<T>(std::get<T>(it->second));
|
||||
} catch (const std::bad_variant_access &) {
|
||||
return FieldGetResult<T>(FieldGetStatus::TYPE_MISMATCH);
|
||||
}
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
std::optional<T> get(const std::string &field_name) const {
|
||||
auto result = get_field<T>(field_name);
|
||||
if (result.status() == FieldGetStatus::SUCCESS) {
|
||||
return result.value();
|
||||
}
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
void remove(const std::string &field_name) {
|
||||
fields_.erase(field_name);
|
||||
}
|
||||
|
||||
Status validate(const CollectionSchema::Ptr &schema,
|
||||
bool is_update = false) const;
|
||||
|
||||
size_t memory_usage() const;
|
||||
|
||||
void clear() {
|
||||
pk_.clear();
|
||||
score_ = 0.0f;
|
||||
doc_id_ = 0;
|
||||
fields_.clear();
|
||||
}
|
||||
|
||||
const std::string to_string() const {
|
||||
std::stringstream ss;
|
||||
ss << "[op:" << (uint32_t)op_ << ", doc_id: " << doc_id_
|
||||
<< ", score: " << score_ << ", pk: " << pk_
|
||||
<< ", fields: " << fields_.size() << "]";
|
||||
return ss.str();
|
||||
}
|
||||
|
||||
std::string to_detail_string() const;
|
||||
|
||||
bool operator==(const Doc &other) const;
|
||||
|
||||
bool operator!=(const Doc &other) const {
|
||||
return !(*this == other);
|
||||
}
|
||||
|
||||
public:
|
||||
std::vector<uint8_t> serialize() const;
|
||||
|
||||
static Doc::Ptr deserialize(const uint8_t *data, size_t size);
|
||||
static Doc::Ptr deserialize(const std::vector<uint8_t> &data) {
|
||||
return deserialize(data.data(), data.size());
|
||||
}
|
||||
|
||||
public:
|
||||
void merge(const Doc &other) {
|
||||
pk_ = other.pk_;
|
||||
score_ = other.score_;
|
||||
doc_id_ = other.doc_id_;
|
||||
op_ = other.op_;
|
||||
for (const auto &[field_name, value] : other.fields_) {
|
||||
fields_[field_name] = value;
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
static void serialize_value(std::vector<uint8_t> &buffer, const Value &value);
|
||||
|
||||
static Value deserialize_value(const uint8_t *&data, uint8_t type);
|
||||
static Value deserialize_value(const uint8_t *&data);
|
||||
|
||||
static void write_to_buffer(std::vector<uint8_t> &buffer, const void *src,
|
||||
size_t size);
|
||||
|
||||
static void read_from_buffer(const uint8_t *&data, void *dest, size_t size);
|
||||
|
||||
private:
|
||||
std::string pk_;
|
||||
float score_{0.0f};
|
||||
uint64_t doc_id_;
|
||||
Operator op_;
|
||||
|
||||
template <typename T>
|
||||
static constexpr bool is_valid_type_v =
|
||||
std::is_same_v<T, std::monostate> || // 0 - Added null support
|
||||
std::is_same_v<T, bool> || // 1
|
||||
std::is_same_v<T, int32_t> || // 2
|
||||
std::is_same_v<T, uint32_t> || // 3
|
||||
std::is_same_v<T, int64_t> || // 4
|
||||
std::is_same_v<T, uint64_t> || // 5
|
||||
std::is_same_v<T, float> || // 6
|
||||
std::is_same_v<T, double> || // 7
|
||||
std::is_same_v<T, std::string> || // 8
|
||||
std::is_same_v<T, std::vector<bool>> || // 9
|
||||
std::is_same_v<T, std::vector<int8_t>> || // 10
|
||||
std::is_same_v<T, std::vector<int16_t>> || // 11
|
||||
std::is_same_v<T, std::vector<int32_t>> || // 12
|
||||
std::is_same_v<T, std::vector<uint32_t>> || // 13
|
||||
std::is_same_v<T, std::vector<int64_t>> || // 14
|
||||
std::is_same_v<T, std::vector<uint64_t>> || // 15
|
||||
std::is_same_v<T, std::vector<float16_t>> || // 16
|
||||
std::is_same_v<T, std::vector<float>> || // 17
|
||||
std::is_same_v<T, std::vector<double>> || // 18
|
||||
std::is_same_v<T, std::vector<std::string>> || // 19
|
||||
std::is_same_v<
|
||||
T, std::pair<std::vector<uint32_t>, std::vector<float16_t>>> || // 20
|
||||
std::is_same_v<
|
||||
T, std::pair<std::vector<uint32_t>, std::vector<float>>>; // 21
|
||||
|
||||
std::unordered_map<std::string, Value> fields_;
|
||||
};
|
||||
|
||||
std::string get_value_type_name(const Doc::Value &value, bool is_vector);
|
||||
|
||||
using DocPtrList = std::vector<Doc::Ptr>;
|
||||
|
||||
using DocPtrMap = std::unordered_map<std::string, Doc::Ptr>;
|
||||
|
||||
using WriteResults = std::vector<Status>;
|
||||
|
||||
struct VectorQuery {
|
||||
int topk_;
|
||||
std::string field_name_;
|
||||
std::string query_vector_; // fp16, void *
|
||||
std::string query_sparse_indices_;
|
||||
std::string query_sparse_values_;
|
||||
std::string filter_;
|
||||
bool include_vector_{false};
|
||||
bool include_doc_id_{false};
|
||||
// select * by default, select no field if output_fields_ is empty, select
|
||||
// specific fields if output_fields_ is not empty
|
||||
std::optional<std::vector<std::string>> output_fields_;
|
||||
QueryParams::Ptr query_params_;
|
||||
|
||||
Status validate(const FieldSchema *schema) const;
|
||||
};
|
||||
|
||||
struct GroupByVectorQuery {
|
||||
std::string field_name_;
|
||||
std::string query_vector_;
|
||||
std::string query_sparse_indices_;
|
||||
std::string query_sparse_values_;
|
||||
std::string filter_;
|
||||
bool include_vector_;
|
||||
// select * by default, select no field if output_fields_ is empty, select
|
||||
// specific fields if output_fields_ is not empty
|
||||
std::optional<std::vector<std::string>> output_fields_;
|
||||
std::string group_by_field_name_;
|
||||
uint32_t group_count_ = 2;
|
||||
uint32_t group_topk_ = 3;
|
||||
QueryParams::Ptr query_params_;
|
||||
};
|
||||
|
||||
struct GroupResult {
|
||||
std::string group_by_value_;
|
||||
std::vector<Doc> docs_;
|
||||
};
|
||||
|
||||
using GroupResults = std::vector<GroupResult>;
|
||||
|
||||
} // namespace zvec
|
||||
@@ -0,0 +1,184 @@
|
||||
// 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 "id_map.h"
|
||||
#include <ailego/logger/logger.h>
|
||||
#include "db/common/constants.h"
|
||||
|
||||
|
||||
namespace zvec {
|
||||
|
||||
|
||||
Status IDMap::open(const std::string &working_dir, bool create_if_missing,
|
||||
bool read_only) {
|
||||
if (opened_) {
|
||||
LOG_ERROR("IDMap is already opened");
|
||||
return Status::InternalError();
|
||||
}
|
||||
|
||||
Status s;
|
||||
if (FILE::IsExist(working_dir)) {
|
||||
if (!FILE::IsDirectory(working_dir)) {
|
||||
LOG_ERROR("IDMap path[%s] is not a directory", working_dir.c_str());
|
||||
return Status::InvalidArgument();
|
||||
}
|
||||
s = rocksdb_context_.open(working_dir, read_only);
|
||||
} else {
|
||||
if (!create_if_missing) {
|
||||
LOG_ERROR("IDMap path[%s] does not exist", working_dir.c_str());
|
||||
return Status::NotFound();
|
||||
}
|
||||
s = rocksdb_context_.create(working_dir);
|
||||
}
|
||||
if (s.ok()) {
|
||||
LOG_INFO("Opened IDMap[%s]", working_dir.c_str());
|
||||
working_dir_ = working_dir;
|
||||
opened_ = true;
|
||||
} else {
|
||||
LOG_ERROR("Failed to open IDMap[%s]", working_dir.c_str());
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
|
||||
IDMap::Ptr IDMap::CreateAndOpen(const std::string &collection_name,
|
||||
const std::string &working_dir,
|
||||
bool create_if_missing, bool read_only) {
|
||||
IDMap::Ptr id_map = std::make_shared<IDMap>(collection_name);
|
||||
if (id_map->open(working_dir, create_if_missing, read_only).ok()) {
|
||||
return id_map;
|
||||
} else {
|
||||
return nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Status IDMap::close() {
|
||||
if (!opened_) {
|
||||
return Status::OK();
|
||||
}
|
||||
|
||||
Status status = rocksdb_context_.close();
|
||||
if (status.ok()) {
|
||||
LOG_INFO("Closed IDMap[%s]", working_dir_.c_str());
|
||||
} else {
|
||||
LOG_ERROR("Failed to close IDMap[%s]", working_dir_.c_str());
|
||||
}
|
||||
return status;
|
||||
}
|
||||
|
||||
|
||||
Status IDMap::flush() {
|
||||
if (!opened_) {
|
||||
return Status::InternalError();
|
||||
}
|
||||
|
||||
auto s = rocksdb_context_.flush();
|
||||
if (s.ok()) {
|
||||
LOG_INFO("Flushed IDMap[%s]", working_dir_.c_str());
|
||||
} else {
|
||||
LOG_ERROR("Failed to flush IDMap[%s]", working_dir_.c_str());
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
|
||||
Status IDMap::upsert(const std::string &key, uint64_t doc_id) {
|
||||
if (!opened_) {
|
||||
return Status::InternalError();
|
||||
}
|
||||
|
||||
rocksdb::Slice value((const char *)&doc_id, sizeof(uint64_t));
|
||||
auto s = rocksdb_context_.db_->Put(rocksdb_context_.write_opts_, key, value);
|
||||
if (s.ok()) {
|
||||
return Status::OK();
|
||||
} else {
|
||||
LOG_ERROR("Failed to put [%s, %zu] into IDMap[%s], code[%d], reason[%s]",
|
||||
key.c_str(), (size_t)doc_id, working_dir_.c_str(), s.code(),
|
||||
s.ToString().c_str());
|
||||
return Status::InternalError();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
void IDMap::remove(const std::string &key) {
|
||||
rocksdb_context_.db_->Delete(rocksdb_context_.write_opts_, key);
|
||||
}
|
||||
|
||||
|
||||
bool IDMap::has(const std::string &key, uint64_t *doc_id) const {
|
||||
std::string value;
|
||||
auto s = rocksdb_context_.db_->Get(rocksdb_context_.read_opts_, key, &value);
|
||||
if (s.ok()) {
|
||||
if (doc_id) {
|
||||
*doc_id = *(uint64_t *)(value.data());
|
||||
}
|
||||
return true;
|
||||
} else {
|
||||
if (doc_id) {
|
||||
*doc_id = INVALID_DOC_ID;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Status IDMap::multi_get(const std::vector<std::string> &keys,
|
||||
std::vector<uint64_t> *doc_ids) const {
|
||||
if (keys.empty()) {
|
||||
doc_ids->clear();
|
||||
return Status::InvalidArgument();
|
||||
}
|
||||
|
||||
std::vector<rocksdb::Slice> slice_keys(keys.begin(), keys.end());
|
||||
std::vector<rocksdb::PinnableSlice> pinnable_values;
|
||||
pinnable_values.resize(keys.size());
|
||||
std::vector<rocksdb::Status> statuses;
|
||||
statuses.resize(keys.size());
|
||||
|
||||
auto db = rocksdb_context_.db_.get();
|
||||
|
||||
db->MultiGet(rocksdb_context_.read_opts_, db->DefaultColumnFamily(),
|
||||
slice_keys.size(), slice_keys.data(), pinnable_values.data(),
|
||||
statuses.data(), false);
|
||||
|
||||
doc_ids->resize(keys.size());
|
||||
for (size_t i = 0; i < keys.size(); i++) {
|
||||
if (statuses[i].ok()) {
|
||||
(*doc_ids)[i] = *(uint64_t *)(pinnable_values[i].data());
|
||||
} else if (statuses[i].code() == rocksdb::Status::kNotFound) {
|
||||
(*doc_ids)[i] = INVALID_DOC_ID;
|
||||
} else {
|
||||
LOG_ERROR("Failed to get key[%s] from IDMap[%s], code[%d], reason[%s]",
|
||||
keys[i].c_str(), working_dir_.c_str(), statuses[i].code(),
|
||||
statuses[i].ToString().c_str());
|
||||
return Status::InternalError();
|
||||
}
|
||||
}
|
||||
|
||||
return Status::OK();
|
||||
}
|
||||
|
||||
|
||||
size_t IDMap::storage_size_in_bytes() {
|
||||
return rocksdb_context_.sst_file_size();
|
||||
}
|
||||
|
||||
|
||||
size_t IDMap::count() {
|
||||
return rocksdb_context_.count();
|
||||
}
|
||||
|
||||
|
||||
} // namespace zvec
|
||||
@@ -0,0 +1,97 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <ailego/io/file.h>
|
||||
#include "db/common/rocksdb_context.h"
|
||||
#include "db/common/status.h"
|
||||
|
||||
|
||||
namespace zvec {
|
||||
|
||||
|
||||
class IDMap {
|
||||
public:
|
||||
using Ptr = std::shared_ptr<IDMap>;
|
||||
|
||||
explicit IDMap(std::string collection_name)
|
||||
: collection_name_(std::move(collection_name)) {};
|
||||
|
||||
~IDMap() {
|
||||
if (opened_) {
|
||||
close();
|
||||
}
|
||||
}
|
||||
|
||||
static Ptr CreateAndOpen(const std::string &collection_name,
|
||||
const std::string &working_dir,
|
||||
bool create_if_missing, bool read_only);
|
||||
|
||||
|
||||
private:
|
||||
IDMap(const IDMap &) = delete;
|
||||
IDMap &operator=(const IDMap &) = delete;
|
||||
IDMap &operator=(IDMap &&) = delete;
|
||||
|
||||
|
||||
public:
|
||||
Status open(const std::string &working_dir, bool create_if_missing,
|
||||
bool read_only);
|
||||
|
||||
Status close();
|
||||
|
||||
Status create_snapshot(const std::string &snapshot_dir);
|
||||
|
||||
Status flush();
|
||||
|
||||
Status upsert(const std::string &key, uint64_t doc_id);
|
||||
|
||||
void remove(const std::string &key);
|
||||
|
||||
bool has(const std::string &key, uint64_t *doc_id = nullptr) const;
|
||||
|
||||
Status multi_get(const std::vector<std::string> &keys,
|
||||
std::vector<uint64_t> *doc_ids) const;
|
||||
|
||||
size_t storage_size_in_bytes();
|
||||
|
||||
size_t count();
|
||||
|
||||
|
||||
const std::string &collection_name() const {
|
||||
return collection_name_;
|
||||
}
|
||||
|
||||
const std::string &working_dir() const {
|
||||
return working_dir_;
|
||||
}
|
||||
|
||||
|
||||
private:
|
||||
using FILE = ailego::File;
|
||||
|
||||
|
||||
const std::string collection_name_{};
|
||||
std::string working_dir_{};
|
||||
|
||||
RocksdbContext rocksdb_context_{};
|
||||
bool opened_{false};
|
||||
};
|
||||
|
||||
|
||||
} // namespace zvec
|
||||
@@ -0,0 +1,79 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
|
||||
|
||||
namespace zvec {
|
||||
|
||||
|
||||
class IndexFilter {
|
||||
public:
|
||||
using Ptr = std::shared_ptr<IndexFilter>;
|
||||
|
||||
IndexFilter() = default;
|
||||
|
||||
virtual ~IndexFilter() = default;
|
||||
|
||||
IndexFilter(const IndexFilter &) = delete;
|
||||
|
||||
IndexFilter &operator=(const IndexFilter &) = delete;
|
||||
|
||||
/**
|
||||
* @return true if the document is filtered (should be excluded)
|
||||
* @return false if the document is not filtered (should be included)
|
||||
*/
|
||||
virtual bool is_filtered(uint64_t id) const = 0;
|
||||
};
|
||||
|
||||
class EasyIndexFilter : public IndexFilter {
|
||||
public:
|
||||
using FilterFunction = std::function<bool(uint64_t)>;
|
||||
|
||||
/**
|
||||
* Create an IndexFilter::Ptr from a lambda expression or function
|
||||
* @param filter_func A function that takes a uint64_t id and returns true
|
||||
* if the document should be filtered (excluded)
|
||||
*/
|
||||
static IndexFilter::Ptr Create(FilterFunction filter_func) {
|
||||
return std::make_shared<EasyIndexFilter>(std::move(filter_func));
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructor that takes a filter function
|
||||
* @param filter_func A function that takes a uint64_t id and returns true
|
||||
* if the document should be filtered (excluded)
|
||||
*/
|
||||
explicit EasyIndexFilter(FilterFunction filter_func)
|
||||
: filter_func_(std::move(filter_func)) {}
|
||||
|
||||
/**
|
||||
* Check if a document should be filtered
|
||||
* @param id The document ID
|
||||
* @return true if the document should be filtered (excluded)
|
||||
* @return false if the document should not be filtered (included)
|
||||
*/
|
||||
bool is_filtered(uint64_t id) const override {
|
||||
return filter_func_(id);
|
||||
}
|
||||
|
||||
private:
|
||||
FilterFunction filter_func_;
|
||||
};
|
||||
|
||||
|
||||
} // namespace zvec
|
||||
@@ -0,0 +1,332 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
#pragma once
|
||||
|
||||
#include <memory>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
#include "core/interface/constants.h"
|
||||
#include "db/index/common/type_helper.h"
|
||||
#include "type.h"
|
||||
|
||||
namespace zvec {
|
||||
|
||||
/*
|
||||
* Column index params
|
||||
*/
|
||||
class IndexParams {
|
||||
public:
|
||||
using Ptr = std::shared_ptr<IndexParams>;
|
||||
|
||||
IndexParams(IndexType type) : type_(type) {}
|
||||
|
||||
virtual ~IndexParams() = default;
|
||||
|
||||
virtual Ptr clone() const = 0;
|
||||
|
||||
virtual bool operator==(const IndexParams &other) const = 0;
|
||||
|
||||
virtual std::string to_string() const = 0;
|
||||
|
||||
virtual bool operator!=(const IndexParams &other) const {
|
||||
return !(*this == other);
|
||||
}
|
||||
|
||||
bool is_vector_index_type() const {
|
||||
return type_ == IndexType::FLAT || type_ == IndexType::HNSW ||
|
||||
type_ == IndexType::IVF;
|
||||
}
|
||||
|
||||
IndexType type() const {
|
||||
return type_;
|
||||
}
|
||||
|
||||
protected:
|
||||
IndexType type_;
|
||||
};
|
||||
|
||||
/*
|
||||
* Scalar: Invert index params
|
||||
*/
|
||||
class InvertIndexParams : public IndexParams {
|
||||
public:
|
||||
InvertIndexParams(bool enable_range_optimization = true,
|
||||
bool enable_extended_wildcard = false)
|
||||
: IndexParams(IndexType::INVERT),
|
||||
enable_range_optimization_(enable_range_optimization),
|
||||
enable_extended_wildcard_(enable_extended_wildcard) {}
|
||||
|
||||
using OPtr = std::shared_ptr<InvertIndexParams>;
|
||||
|
||||
Ptr clone() const override {
|
||||
return std::make_shared<InvertIndexParams>(enable_range_optimization_,
|
||||
enable_extended_wildcard_);
|
||||
}
|
||||
|
||||
std::string to_string() const override {
|
||||
std::ostringstream oss;
|
||||
oss << "InvertIndexParams{" << "enable_range_optimization:"
|
||||
<< (enable_range_optimization_ ? "true" : "false")
|
||||
<< ", enable_extended_wildcard:"
|
||||
<< (enable_extended_wildcard_ ? "true" : "false") << "}";
|
||||
return oss.str();
|
||||
}
|
||||
|
||||
bool operator==(const IndexParams &other) const override {
|
||||
if (type() != other.type()) {
|
||||
return false;
|
||||
}
|
||||
auto &other_invert = dynamic_cast<const InvertIndexParams &>(other);
|
||||
return enable_range_optimization_ ==
|
||||
other_invert.enable_range_optimization_ &&
|
||||
enable_extended_wildcard_ == other_invert.enable_extended_wildcard_;
|
||||
}
|
||||
|
||||
bool enable_range_optimization() const {
|
||||
return enable_range_optimization_;
|
||||
}
|
||||
|
||||
void set_enable_range_optimization(bool enable_range_optimization) {
|
||||
enable_range_optimization_ = enable_range_optimization;
|
||||
}
|
||||
|
||||
bool enable_extended_wildcard() const {
|
||||
return enable_extended_wildcard_;
|
||||
}
|
||||
|
||||
// Enables suffix and infix search.
|
||||
// Note that prefix search is always enabled regardless of this setting.
|
||||
void set_enable_extended_wildcard(bool enable_extended_wildcard) {
|
||||
enable_extended_wildcard_ = enable_extended_wildcard;
|
||||
}
|
||||
|
||||
private:
|
||||
bool enable_range_optimization_{false};
|
||||
bool enable_extended_wildcard_{false};
|
||||
};
|
||||
|
||||
/*
|
||||
* Column index params
|
||||
*/
|
||||
class VectorIndexParams : public IndexParams {
|
||||
public:
|
||||
VectorIndexParams(IndexType type, MetricType metric_type,
|
||||
QuantizeType quantize_type = QuantizeType::UNDEFINED)
|
||||
: IndexParams(type),
|
||||
metric_type_(metric_type),
|
||||
quantize_type_(quantize_type) {}
|
||||
|
||||
virtual ~VectorIndexParams() = default;
|
||||
|
||||
std::string vector_index_params_to_string(const std::string &class_name,
|
||||
MetricType metric_type,
|
||||
QuantizeType quantize_type) const {
|
||||
std::ostringstream oss;
|
||||
oss << class_name << "{"
|
||||
<< "metric:" << MetricTypeCodeBook::AsString(metric_type)
|
||||
<< ",quantize:" << QuantizeTypeCodeBook::AsString(quantize_type);
|
||||
return oss.str();
|
||||
}
|
||||
|
||||
MetricType metric_type() const {
|
||||
return metric_type_;
|
||||
}
|
||||
|
||||
void set_metric_type(MetricType metric_type) {
|
||||
metric_type_ = metric_type;
|
||||
}
|
||||
|
||||
QuantizeType quantize_type() const {
|
||||
return quantize_type_;
|
||||
}
|
||||
|
||||
void set_quantize_type(QuantizeType quantize_type) {
|
||||
quantize_type_ = quantize_type;
|
||||
}
|
||||
|
||||
protected:
|
||||
MetricType metric_type_;
|
||||
QuantizeType quantize_type_;
|
||||
};
|
||||
|
||||
/*
|
||||
* Vector: Hnsw index params
|
||||
*/
|
||||
class HnswIndexParams : public VectorIndexParams {
|
||||
public:
|
||||
HnswIndexParams(
|
||||
MetricType metric_type, int m = core_interface::kDefaultHnswNeighborCnt,
|
||||
int ef_construction = core_interface::kDefaultHnswEfConstruction,
|
||||
QuantizeType quantize_type = QuantizeType::UNDEFINED)
|
||||
: VectorIndexParams(IndexType::HNSW, metric_type, quantize_type),
|
||||
m_(m),
|
||||
ef_construction_(ef_construction) {}
|
||||
|
||||
using OPtr = std::shared_ptr<HnswIndexParams>;
|
||||
|
||||
public:
|
||||
Ptr clone() const override {
|
||||
return std::make_shared<HnswIndexParams>(metric_type_, m_, ef_construction_,
|
||||
quantize_type_);
|
||||
}
|
||||
|
||||
std::string to_string() const override {
|
||||
auto base_str = vector_index_params_to_string("HnswIndexParams",
|
||||
metric_type_, quantize_type_);
|
||||
std::ostringstream oss;
|
||||
oss << base_str << ",m:" << m_ << ",ef_construction:" << ef_construction_
|
||||
<< "}";
|
||||
return oss.str();
|
||||
}
|
||||
|
||||
bool operator==(const IndexParams &other) const override {
|
||||
return type() == other.type() &&
|
||||
metric_type() ==
|
||||
static_cast<const HnswIndexParams &>(other).metric_type() &&
|
||||
m_ == static_cast<const HnswIndexParams &>(other).m_ &&
|
||||
ef_construction_ ==
|
||||
static_cast<const HnswIndexParams &>(other).ef_construction_ &&
|
||||
quantize_type() ==
|
||||
static_cast<const HnswIndexParams &>(other).quantize_type();
|
||||
}
|
||||
|
||||
void set_m(int m) {
|
||||
m_ = m;
|
||||
}
|
||||
int m() const {
|
||||
return m_;
|
||||
}
|
||||
void set_ef_construction(int ef_construction) {
|
||||
ef_construction_ = ef_construction;
|
||||
}
|
||||
int ef_construction() const {
|
||||
return ef_construction_;
|
||||
}
|
||||
|
||||
private:
|
||||
int m_;
|
||||
int ef_construction_;
|
||||
};
|
||||
|
||||
class FlatIndexParams : public VectorIndexParams {
|
||||
public:
|
||||
FlatIndexParams(MetricType metric_type,
|
||||
QuantizeType quantize_type = QuantizeType::UNDEFINED)
|
||||
: VectorIndexParams(IndexType::FLAT, metric_type, quantize_type) {}
|
||||
|
||||
using OPtr = std::shared_ptr<FlatIndexParams>;
|
||||
|
||||
public:
|
||||
Ptr clone() const override {
|
||||
return std::make_shared<FlatIndexParams>(metric_type_, quantize_type_);
|
||||
}
|
||||
|
||||
std::string to_string() const override {
|
||||
auto base_str = vector_index_params_to_string("FlatIndexParams",
|
||||
metric_type_, quantize_type_);
|
||||
std::ostringstream oss;
|
||||
oss << base_str << "}";
|
||||
return oss.str();
|
||||
}
|
||||
|
||||
bool operator==(const IndexParams &other) const override {
|
||||
return type() == other.type() &&
|
||||
metric_type() ==
|
||||
static_cast<const VectorIndexParams &>(other).metric_type() &&
|
||||
quantize_type() ==
|
||||
static_cast<const VectorIndexParams &>(other).quantize_type();
|
||||
}
|
||||
};
|
||||
|
||||
// define default index params
|
||||
const FlatIndexParams DefaultVectorIndexParams(MetricType::IP);
|
||||
|
||||
inline FlatIndexParams MakeDefaultVectorIndexParams(MetricType metric_type) {
|
||||
return FlatIndexParams(metric_type);
|
||||
}
|
||||
|
||||
inline FlatIndexParams MakeDefaultQuantVectorIndexParams(
|
||||
MetricType metric_type, QuantizeType quantize_type) {
|
||||
return FlatIndexParams(metric_type, quantize_type);
|
||||
}
|
||||
|
||||
class IVFIndexParams : public VectorIndexParams {
|
||||
public:
|
||||
IVFIndexParams(MetricType metric_type, int n_list = 1024, int n_iters = 10,
|
||||
bool use_soar = false,
|
||||
QuantizeType quantize_type = QuantizeType::UNDEFINED)
|
||||
: VectorIndexParams(IndexType::IVF, metric_type, quantize_type),
|
||||
n_list_(n_list),
|
||||
n_iters_(n_iters),
|
||||
use_soar_(use_soar) {}
|
||||
|
||||
using OPtr = std::shared_ptr<IVFIndexParams>;
|
||||
|
||||
public:
|
||||
Ptr clone() const override {
|
||||
return std::make_shared<IVFIndexParams>(metric_type_, n_list_, n_iters_,
|
||||
use_soar_, quantize_type_);
|
||||
}
|
||||
|
||||
std::string to_string() const override {
|
||||
auto base_str = vector_index_params_to_string("IVFIndexParams",
|
||||
metric_type_, quantize_type_);
|
||||
std::ostringstream oss;
|
||||
oss << base_str << ",n_list:" << n_list_ << ",n_iters:" << n_iters_
|
||||
<< ",use_soar:" << use_soar_ << " << ";
|
||||
return oss.str();
|
||||
}
|
||||
|
||||
int n_list() const {
|
||||
return n_list_;
|
||||
}
|
||||
|
||||
void set_n_list(int n_list) {
|
||||
n_list_ = n_list;
|
||||
}
|
||||
|
||||
int n_iters() const {
|
||||
return n_iters_;
|
||||
}
|
||||
|
||||
void set_n_iters(int n_iters) {
|
||||
n_iters_ = n_iters;
|
||||
}
|
||||
|
||||
bool use_soar() const {
|
||||
return use_soar_;
|
||||
}
|
||||
|
||||
void set_use_soar(bool use_soar) {
|
||||
use_soar_ = use_soar;
|
||||
}
|
||||
|
||||
bool operator==(const IndexParams &other) const override {
|
||||
return type() == other.type() &&
|
||||
metric_type() ==
|
||||
static_cast<const IVFIndexParams &>(other).metric_type() &&
|
||||
n_list_ == static_cast<const IVFIndexParams &>(other).n_list_ &&
|
||||
n_iters_ == static_cast<const IVFIndexParams &>(other).n_iters_ &&
|
||||
use_soar_ == static_cast<const IVFIndexParams &>(other).use_soar_ &&
|
||||
quantize_type() ==
|
||||
static_cast<const IVFIndexParams &>(other).quantize_type();
|
||||
}
|
||||
|
||||
private:
|
||||
int n_list_;
|
||||
int n_iters_;
|
||||
bool use_soar_;
|
||||
};
|
||||
|
||||
} // namespace zvec
|
||||
@@ -0,0 +1,434 @@
|
||||
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
#pragma once
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstdint>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <set>
|
||||
#include <sstream>
|
||||
#include <vector>
|
||||
#include "db/common/utils.h"
|
||||
#include "db/index/common/type_helper.h"
|
||||
|
||||
namespace zvec {
|
||||
|
||||
using SegmentID = uint32_t;
|
||||
using BlockID = uint32_t;
|
||||
|
||||
class BlockMeta {
|
||||
public:
|
||||
using Ptr = std::shared_ptr<BlockMeta>;
|
||||
|
||||
public:
|
||||
BlockMeta() = default;
|
||||
|
||||
BlockMeta(uint32_t id, BlockType type, uint64_t min_doc_id,
|
||||
uint64_t max_doc_id, uint32_t doc_count,
|
||||
const std::vector<std::string> &columns)
|
||||
: id_(id),
|
||||
type_(type),
|
||||
min_doc_id_(min_doc_id),
|
||||
max_doc_id_(max_doc_id),
|
||||
doc_count_(doc_count),
|
||||
columns_(columns) {}
|
||||
|
||||
BlockMeta(uint32_t id, BlockType type, uint64_t min_doc_id,
|
||||
uint64_t max_doc_id)
|
||||
: id_(id),
|
||||
type_(type),
|
||||
min_doc_id_(min_doc_id),
|
||||
max_doc_id_(max_doc_id) {}
|
||||
uint32_t id() const {
|
||||
return id_;
|
||||
}
|
||||
|
||||
void set_id(uint32_t id) {
|
||||
id_ = id;
|
||||
}
|
||||
|
||||
BlockType type() const {
|
||||
return type_;
|
||||
}
|
||||
|
||||
void set_type(BlockType type) {
|
||||
type_ = type;
|
||||
}
|
||||
|
||||
uint64_t min_doc_id() const {
|
||||
return min_doc_id_;
|
||||
}
|
||||
|
||||
void set_min_doc_id(uint64_t min_doc_id) {
|
||||
min_doc_id_ = min_doc_id;
|
||||
}
|
||||
|
||||
uint64_t max_doc_id() const {
|
||||
return max_doc_id_;
|
||||
}
|
||||
|
||||
void set_max_doc_id(uint64_t max_doc_id) {
|
||||
max_doc_id_ = max_doc_id;
|
||||
}
|
||||
|
||||
uint32_t doc_count() const {
|
||||
return doc_count_;
|
||||
}
|
||||
|
||||
void set_doc_count(uint32_t doc_count) {
|
||||
doc_count_ = doc_count;
|
||||
}
|
||||
|
||||
const std::vector<std::string> &columns() const {
|
||||
return columns_;
|
||||
}
|
||||
|
||||
void set_columns(const std::vector<std::string> &columns) {
|
||||
columns_ = columns;
|
||||
}
|
||||
|
||||
void add_column(const std::string &column) {
|
||||
columns_.push_back(column);
|
||||
}
|
||||
|
||||
void del_column(const std::string &column) {
|
||||
columns_.erase(std::remove(columns_.begin(), columns_.end(), column),
|
||||
columns_.end());
|
||||
}
|
||||
|
||||
bool contain_column(const std::string &column) const {
|
||||
return std::find(columns_.begin(), columns_.end(), column) !=
|
||||
columns_.end();
|
||||
}
|
||||
|
||||
public:
|
||||
bool operator==(const BlockMeta &other) const {
|
||||
return id_ == other.id_ && type_ == other.type_ &&
|
||||
min_doc_id_ == other.min_doc_id_ &&
|
||||
max_doc_id_ == other.max_doc_id_ && columns_ == other.columns_ &&
|
||||
doc_count_ == other.doc_count_;
|
||||
}
|
||||
|
||||
std::string to_string() const {
|
||||
std::ostringstream oss;
|
||||
oss << "BlockMeta{" << "id:" << id_
|
||||
<< ",type:" << BlockTypeCodeBook::AsString(type_)
|
||||
<< ",min_doc_id:" << min_doc_id_ << ",max_doc_id:" << max_doc_id_
|
||||
<< ",doc_count:" << doc_count_ << ",columns:[";
|
||||
|
||||
for (size_t i = 0; i < columns_.size(); ++i) {
|
||||
if (i > 0) oss << ",";
|
||||
oss << "'" << columns_[i] << "'";
|
||||
}
|
||||
|
||||
oss << "]}";
|
||||
return oss.str();
|
||||
}
|
||||
|
||||
std::string to_string_formatted(int indent_level = 0) const {
|
||||
std::ostringstream oss;
|
||||
oss << indent(indent_level) << "BlockMeta{\n"
|
||||
<< indent(indent_level + 1) << "id: " << id_ << ",\n"
|
||||
<< indent(indent_level + 1)
|
||||
<< "type: " << BlockTypeCodeBook::AsString(type_) << ",\n"
|
||||
<< indent(indent_level + 1) << "min_doc_id: " << min_doc_id_ << ",\n"
|
||||
<< indent(indent_level + 1) << "max_doc_id: " << max_doc_id_ << ",\n"
|
||||
<< indent(indent_level + 1) << "doc_count: " << doc_count_ << ",\n"
|
||||
<< indent(indent_level + 1) << "columns: [";
|
||||
|
||||
if (!columns_.empty()) {
|
||||
oss << "\n";
|
||||
for (size_t i = 0; i < columns_.size(); ++i) {
|
||||
oss << indent(indent_level + 2) << "'" << columns_[i] << "'";
|
||||
if (i < columns_.size() - 1) {
|
||||
oss << ",";
|
||||
}
|
||||
oss << "\n";
|
||||
}
|
||||
oss << indent(indent_level + 1);
|
||||
}
|
||||
|
||||
oss << "]\n" << indent(indent_level) << "}";
|
||||
return oss.str();
|
||||
}
|
||||
|
||||
public:
|
||||
uint32_t id_{0};
|
||||
BlockType type_{BlockType::UNDEFINED};
|
||||
uint64_t min_doc_id_{0};
|
||||
uint64_t max_doc_id_{0};
|
||||
uint32_t doc_count_{0};
|
||||
std::vector<std::string> columns_{};
|
||||
};
|
||||
|
||||
class SegmentMeta {
|
||||
public:
|
||||
using Ptr = std::shared_ptr<SegmentMeta>;
|
||||
|
||||
public:
|
||||
SegmentMeta() {};
|
||||
|
||||
explicit SegmentMeta(SegmentID id) : id_(id) {}
|
||||
|
||||
void set_id(SegmentID id) {
|
||||
id_ = id;
|
||||
}
|
||||
|
||||
SegmentID id() const {
|
||||
return id_;
|
||||
}
|
||||
|
||||
void add_persisted_block(const BlockMeta &block) {
|
||||
persisted_blocks_.push_back(block);
|
||||
}
|
||||
|
||||
void set_persisted_blocks(const std::vector<BlockMeta> &blocks) {
|
||||
persisted_blocks_ = blocks;
|
||||
}
|
||||
|
||||
bool remove_block(BlockID block_id) {
|
||||
auto it = std::remove_if(
|
||||
persisted_blocks_.begin(), persisted_blocks_.end(),
|
||||
[block_id](const BlockMeta &block) { return block.id() == block_id; });
|
||||
bool found = (it != persisted_blocks_.end());
|
||||
persisted_blocks_.erase(it, persisted_blocks_.end());
|
||||
return found;
|
||||
}
|
||||
|
||||
void remove_vector_persisted_block(const std::string &column, bool quantize) {
|
||||
std::vector<BlockMeta> new_persisted_blocks;
|
||||
for (auto &b : persisted_blocks_) {
|
||||
if (quantize) {
|
||||
if (!(b.type() == BlockType::VECTOR_INDEX_QUANTIZE &&
|
||||
b.contain_column(column))) {
|
||||
new_persisted_blocks.push_back(b);
|
||||
}
|
||||
} else {
|
||||
if (!(b.type() == BlockType::VECTOR_INDEX &&
|
||||
b.contain_column(column))) {
|
||||
new_persisted_blocks.push_back(b);
|
||||
}
|
||||
}
|
||||
}
|
||||
persisted_blocks_ = new_persisted_blocks;
|
||||
}
|
||||
|
||||
void remove_vector_persisted_block(const std::string &column) {
|
||||
std::vector<BlockMeta> new_persisted_blocks;
|
||||
for (auto &b : persisted_blocks_) {
|
||||
if (!b.contain_column(column)) {
|
||||
new_persisted_blocks.push_back(b);
|
||||
}
|
||||
}
|
||||
persisted_blocks_ = new_persisted_blocks;
|
||||
}
|
||||
|
||||
void remove_scalar_index_block() {
|
||||
std::vector<BlockMeta> new_persisted_blocks;
|
||||
for (auto &b : persisted_blocks_) {
|
||||
if (b.type() != BlockType::SCALAR_INDEX) {
|
||||
new_persisted_blocks.push_back(b);
|
||||
}
|
||||
}
|
||||
persisted_blocks_ = new_persisted_blocks;
|
||||
}
|
||||
|
||||
void set_writing_forward_block(const BlockMeta &writing_forward_block) {
|
||||
writing_forward_block_ = writing_forward_block;
|
||||
}
|
||||
|
||||
void remove_writing_forward_block() {
|
||||
writing_forward_block_ = std::nullopt;
|
||||
}
|
||||
|
||||
void update_max_doc_id(uint64_t max_doc_id) {
|
||||
if (writing_forward_block_.has_value()) {
|
||||
writing_forward_block_->set_max_doc_id(max_doc_id);
|
||||
}
|
||||
}
|
||||
|
||||
uint64_t min_doc_id() const {
|
||||
if (persisted_blocks_.empty()) {
|
||||
if (writing_forward_block_.has_value()) {
|
||||
return writing_forward_block_->min_doc_id();
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
uint64_t min_doc_id{std::numeric_limits<uint64_t>::max()};
|
||||
for (const auto &block : persisted_blocks_) {
|
||||
if (block.type() == BlockType::SCALAR) {
|
||||
min_doc_id = std::min(min_doc_id, block.min_doc_id());
|
||||
}
|
||||
}
|
||||
if (min_doc_id == std::numeric_limits<uint64_t>::max() &&
|
||||
writing_forward_block_.has_value()) {
|
||||
min_doc_id = writing_forward_block_->min_doc_id();
|
||||
}
|
||||
return min_doc_id;
|
||||
}
|
||||
|
||||
uint64_t max_doc_id() const {
|
||||
if (writing_forward_block_.has_value() &&
|
||||
writing_forward_block_->doc_count_ != 0) {
|
||||
return writing_forward_block_->max_doc_id();
|
||||
}
|
||||
uint64_t max_doc_id{0};
|
||||
for (const auto &block : persisted_blocks_) {
|
||||
if (block.type() == BlockType::SCALAR) {
|
||||
max_doc_id = std::max(max_doc_id, block.max_doc_id());
|
||||
}
|
||||
}
|
||||
return max_doc_id;
|
||||
}
|
||||
|
||||
uint32_t doc_count() const {
|
||||
uint32_t count{0};
|
||||
if (writing_forward_block_.has_value()) {
|
||||
count = writing_forward_block_->doc_count();
|
||||
}
|
||||
for (const auto &block : persisted_blocks_) {
|
||||
if (block.type() == BlockType::SCALAR) {
|
||||
count += block.doc_count();
|
||||
}
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
std::vector<BlockMeta> &persisted_blocks() {
|
||||
return persisted_blocks_;
|
||||
}
|
||||
|
||||
const std::vector<BlockMeta> &persisted_blocks() const {
|
||||
return persisted_blocks_;
|
||||
}
|
||||
|
||||
std::optional<BlockMeta> &writing_forward_block() {
|
||||
return writing_forward_block_;
|
||||
}
|
||||
|
||||
const std::optional<BlockMeta> &writing_forward_block() const {
|
||||
return writing_forward_block_;
|
||||
}
|
||||
|
||||
bool has_writing_forward_block() const {
|
||||
return writing_forward_block_.has_value();
|
||||
}
|
||||
|
||||
bool vector_indexed(const std::string &field) const {
|
||||
return indexed_vector_fields_.count(field) > 0;
|
||||
}
|
||||
|
||||
void add_indexed_vector_field(const std::string &field) {
|
||||
indexed_vector_fields_.insert(field);
|
||||
}
|
||||
|
||||
std::set<std::string> indexed_vector_fields() const {
|
||||
return indexed_vector_fields_;
|
||||
}
|
||||
|
||||
void set_indexed_vector_fields(const std::set<std::string> &fields) {
|
||||
indexed_vector_fields_ = fields;
|
||||
}
|
||||
|
||||
public:
|
||||
bool operator==(const SegmentMeta &other) const {
|
||||
return id_ == other.id_ && persisted_blocks_ == other.persisted_blocks_ &&
|
||||
writing_forward_block_ == other.writing_forward_block_ &&
|
||||
indexed_vector_fields_ == other.indexed_vector_fields_;
|
||||
}
|
||||
|
||||
bool operator!=(const SegmentMeta &other) const {
|
||||
return !(*this == other);
|
||||
}
|
||||
|
||||
// Add these methods to SegmentMeta class in meta.h
|
||||
|
||||
std::string to_string() const {
|
||||
std::ostringstream oss;
|
||||
oss << "SegmentMeta{" << "id:" << id_ << ",persisted_blocks:[";
|
||||
|
||||
for (size_t i = 0; i < persisted_blocks_.size(); ++i) {
|
||||
if (i > 0) oss << ",";
|
||||
oss << persisted_blocks_[i].to_string();
|
||||
}
|
||||
|
||||
oss << "],writing_forward_block:";
|
||||
if (writing_forward_block_.has_value()) {
|
||||
oss << writing_forward_block_->to_string();
|
||||
} else {
|
||||
oss << "null";
|
||||
}
|
||||
|
||||
oss << ",indexed_vector_fields:[";
|
||||
|
||||
size_t i = 0;
|
||||
for (const auto &field : indexed_vector_fields_) {
|
||||
if (i > 0) oss << ",";
|
||||
oss << "'" << field << "'";
|
||||
++i;
|
||||
}
|
||||
|
||||
oss << "]}";
|
||||
return oss.str();
|
||||
}
|
||||
|
||||
std::string to_string_formatted(int indent_level = 0) const {
|
||||
std::ostringstream oss;
|
||||
oss << indent(indent_level) << "SegmentMeta{\n"
|
||||
<< indent(indent_level + 1) << "id: " << id_ << ",\n"
|
||||
<< indent(indent_level + 1) << "persisted_blocks: [\n";
|
||||
|
||||
for (size_t i = 0; i < persisted_blocks_.size(); ++i) {
|
||||
oss << persisted_blocks_[i].to_string_formatted(indent_level + 2);
|
||||
if (i < persisted_blocks_.size() - 1) {
|
||||
oss << ",";
|
||||
}
|
||||
oss << "\n";
|
||||
}
|
||||
|
||||
oss << "\n"
|
||||
<< indent(indent_level + 1) << "],\n"
|
||||
<< indent(indent_level + 1) << "writing_forward_block: ";
|
||||
|
||||
if (writing_forward_block_.has_value()) {
|
||||
oss << "\n"
|
||||
<< writing_forward_block_->to_string_formatted(indent_level + 2)
|
||||
<< "\n";
|
||||
} else {
|
||||
oss << "null\n";
|
||||
}
|
||||
|
||||
oss << indent(indent_level + 1) << "indexed_vector_fields: [";
|
||||
|
||||
size_t i = 0;
|
||||
for (const auto &field : indexed_vector_fields_) {
|
||||
if (i > 0) oss << ",";
|
||||
oss << "'" << field << "'";
|
||||
++i;
|
||||
}
|
||||
|
||||
oss << "]\n" << indent(indent_level) << "}";
|
||||
return oss.str();
|
||||
}
|
||||
|
||||
private:
|
||||
SegmentID id_{0};
|
||||
std::vector<BlockMeta> persisted_blocks_;
|
||||
std::optional<BlockMeta> writing_forward_block_;
|
||||
std::set<std::string> indexed_vector_fields_;
|
||||
};
|
||||
|
||||
} // namespace zvec
|
||||
@@ -0,0 +1,61 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
#include "db/common/constants.h"
|
||||
|
||||
namespace zvec {
|
||||
|
||||
|
||||
struct CollectionOptions {
|
||||
bool read_only_;
|
||||
bool enable_mmap_; // ignnored when load collection
|
||||
uint32_t max_buffer_size_{
|
||||
DEFAULT_MAX_BUFFER_SIZE}; // ignored when read_only=true
|
||||
|
||||
bool operator==(const CollectionOptions &other) const {
|
||||
return read_only_ == other.read_only_ &&
|
||||
enable_mmap_ == other.enable_mmap_ &&
|
||||
max_buffer_size_ == other.max_buffer_size_;
|
||||
}
|
||||
|
||||
bool operator!=(const CollectionOptions &other) const {
|
||||
return !(*this == other);
|
||||
}
|
||||
};
|
||||
|
||||
struct SegmentOptions {
|
||||
bool read_only_;
|
||||
bool enable_mmap_;
|
||||
uint32_t max_buffer_size_{DEFAULT_MAX_BUFFER_SIZE};
|
||||
};
|
||||
|
||||
struct CreateIndexOptions {
|
||||
int concurrency_{0}; // default use config.optimize_thread_pool
|
||||
};
|
||||
|
||||
struct OptimizeOptions {
|
||||
int concurrency_{0};
|
||||
};
|
||||
|
||||
struct AddColumnOptions {
|
||||
int concurrency_{0};
|
||||
};
|
||||
|
||||
struct AlterColumnOptions {
|
||||
int concurrency_{0};
|
||||
};
|
||||
|
||||
} // namespace zvec
|
||||
@@ -0,0 +1,282 @@
|
||||
// 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 "proto_converter.h"
|
||||
|
||||
namespace zvec {
|
||||
|
||||
HnswIndexParams::OPtr ProtoConverter::FromPb(
|
||||
const proto::HnswIndexParams ¶ms_pb) {
|
||||
auto params = std::make_shared<HnswIndexParams>(
|
||||
MetricTypeCodeBook::Get(params_pb.base().metric_type()), params_pb.m(),
|
||||
params_pb.ef_construction(),
|
||||
QuantizeTypeCodeBook::Get(params_pb.base().quantize_type()));
|
||||
|
||||
return params;
|
||||
}
|
||||
|
||||
proto::HnswIndexParams ProtoConverter::ToPb(const HnswIndexParams *params) {
|
||||
proto::HnswIndexParams params_pb;
|
||||
params_pb.mutable_base()->set_metric_type(
|
||||
MetricTypeCodeBook::Get(params->metric_type()));
|
||||
params_pb.mutable_base()->set_quantize_type(
|
||||
QuantizeTypeCodeBook::Get(params->quantize_type()));
|
||||
params_pb.set_ef_construction(params->ef_construction());
|
||||
params_pb.set_m(params->m());
|
||||
return params_pb;
|
||||
}
|
||||
|
||||
// FlatIndexParams
|
||||
FlatIndexParams::OPtr ProtoConverter::FromPb(
|
||||
const proto::FlatIndexParams ¶ms_pb) {
|
||||
return std::make_shared<FlatIndexParams>(
|
||||
MetricTypeCodeBook::Get(params_pb.base().metric_type()),
|
||||
QuantizeTypeCodeBook::Get(params_pb.base().quantize_type()));
|
||||
}
|
||||
|
||||
proto::FlatIndexParams ProtoConverter::ToPb(const FlatIndexParams *params) {
|
||||
proto::FlatIndexParams params_pb;
|
||||
params_pb.mutable_base()->set_metric_type(
|
||||
MetricTypeCodeBook::Get(params->metric_type()));
|
||||
params_pb.mutable_base()->set_quantize_type(
|
||||
QuantizeTypeCodeBook::Get(params->quantize_type()));
|
||||
return params_pb;
|
||||
}
|
||||
|
||||
// IVFIndexParams
|
||||
IVFIndexParams::OPtr ProtoConverter::FromPb(
|
||||
const proto::IVFIndexParams ¶ms_pb) {
|
||||
return std::make_shared<IVFIndexParams>(
|
||||
MetricTypeCodeBook::Get(params_pb.base().metric_type()),
|
||||
params_pb.n_list(), params_pb.n_iters(), params_pb.use_soar(),
|
||||
QuantizeTypeCodeBook::Get(params_pb.base().quantize_type()));
|
||||
}
|
||||
|
||||
proto::IVFIndexParams ProtoConverter::ToPb(const IVFIndexParams *params) {
|
||||
proto::IVFIndexParams params_pb;
|
||||
params_pb.mutable_base()->set_metric_type(
|
||||
MetricTypeCodeBook::Get(params->metric_type()));
|
||||
params_pb.mutable_base()->set_quantize_type(
|
||||
QuantizeTypeCodeBook::Get(params->quantize_type()));
|
||||
params_pb.set_n_list(params->n_list());
|
||||
params_pb.set_n_iters(params->n_iters());
|
||||
params_pb.set_use_soar(params->use_soar());
|
||||
return params_pb;
|
||||
}
|
||||
|
||||
// InvertIndexParams
|
||||
InvertIndexParams::OPtr ProtoConverter::FromPb(
|
||||
const proto::InvertIndexParams ¶ms_pb) {
|
||||
auto params = std::make_shared<InvertIndexParams>(
|
||||
params_pb.enable_range_optimization());
|
||||
|
||||
return params;
|
||||
}
|
||||
|
||||
proto::InvertIndexParams ProtoConverter::ToPb(const InvertIndexParams *params) {
|
||||
proto::InvertIndexParams params_pb;
|
||||
params_pb.set_enable_range_optimization(params->enable_range_optimization());
|
||||
return params_pb;
|
||||
}
|
||||
|
||||
// FieldSchema
|
||||
FieldSchema::Ptr ProtoConverter::FromPb(const proto::FieldSchema &schema_pb) {
|
||||
auto schema = std::make_shared<FieldSchema>();
|
||||
|
||||
schema->set_name(schema_pb.name());
|
||||
schema->set_data_type(DataTypeCodeBook::Get(schema_pb.data_type()));
|
||||
schema->set_dimension(schema_pb.dimension());
|
||||
schema->set_nullable(schema_pb.nullable());
|
||||
if (schema_pb.has_index_params()) {
|
||||
schema->set_index_params(ProtoConverter::FromPb(schema_pb.index_params()));
|
||||
}
|
||||
return schema;
|
||||
}
|
||||
proto::FieldSchema ProtoConverter::ToPb(const FieldSchema &schema) {
|
||||
proto::FieldSchema schema_pb;
|
||||
|
||||
schema_pb.set_name(schema.name());
|
||||
schema_pb.set_data_type(DataTypeCodeBook::Get(schema.data_type()));
|
||||
schema_pb.set_dimension(schema.dimension());
|
||||
schema_pb.set_nullable(schema.nullable());
|
||||
auto index_params = schema.index_params();
|
||||
if (index_params) {
|
||||
auto index_params_pb = schema_pb.mutable_index_params();
|
||||
index_params_pb->MergeFrom(ProtoConverter::ToPb(index_params.get()));
|
||||
}
|
||||
return schema_pb;
|
||||
}
|
||||
|
||||
// CollectionSchema
|
||||
CollectionSchema::Ptr ProtoConverter::FromPb(
|
||||
const proto::CollectionSchema &schema_pb) {
|
||||
CollectionSchema::Ptr schema = std::make_shared<CollectionSchema>();
|
||||
|
||||
schema->set_name(schema_pb.name());
|
||||
|
||||
for (auto &column_schema_pb : schema_pb.fields()) {
|
||||
FieldSchema::Ptr column_schema = ProtoConverter::FromPb(column_schema_pb);
|
||||
schema->add_field(column_schema);
|
||||
}
|
||||
|
||||
schema->set_max_doc_count_per_segment(schema_pb.max_doc_count_per_segment());
|
||||
|
||||
return schema;
|
||||
}
|
||||
|
||||
proto::CollectionSchema ProtoConverter::ToPb(const CollectionSchema &schema) {
|
||||
proto::CollectionSchema schema_pb;
|
||||
schema_pb.set_name(schema.name());
|
||||
for (auto &column_schema : schema.fields()) {
|
||||
proto::FieldSchema *column_schema_pb = schema_pb.add_fields();
|
||||
column_schema_pb->MergeFrom(ProtoConverter::ToPb(*column_schema));
|
||||
}
|
||||
|
||||
schema_pb.set_max_doc_count_per_segment(schema.max_doc_count_per_segment());
|
||||
|
||||
return schema_pb;
|
||||
}
|
||||
|
||||
IndexParams::Ptr ProtoConverter::FromPb(const proto::IndexParams ¶ms_pb) {
|
||||
if (params_pb.has_hnsw()) {
|
||||
return ProtoConverter::FromPb(params_pb.hnsw());
|
||||
} else if (params_pb.has_invert()) {
|
||||
return ProtoConverter::FromPb(params_pb.invert());
|
||||
} else if (params_pb.has_ivf()) {
|
||||
return ProtoConverter::FromPb(params_pb.ivf());
|
||||
} else if (params_pb.has_flat()) {
|
||||
return ProtoConverter::FromPb(params_pb.flat());
|
||||
}
|
||||
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
// BlockMeta
|
||||
BlockMeta::Ptr ProtoConverter::FromPb(const proto::BlockMeta &meta_pb) {
|
||||
auto block_meta = std::make_shared<BlockMeta>();
|
||||
|
||||
block_meta->set_id(meta_pb.block_id());
|
||||
block_meta->set_type(BlockTypeCodeBook::Get(meta_pb.block_type()));
|
||||
block_meta->set_min_doc_id(meta_pb.min_doc_id());
|
||||
block_meta->set_max_doc_id(meta_pb.max_doc_id());
|
||||
block_meta->set_doc_count(meta_pb.doc_count());
|
||||
for (auto &column : meta_pb.columns()) {
|
||||
block_meta->add_column(column);
|
||||
}
|
||||
|
||||
return block_meta;
|
||||
}
|
||||
|
||||
proto::IndexParams ProtoConverter::ToPb(const IndexParams *params) {
|
||||
proto::IndexParams params_pb;
|
||||
|
||||
switch (params->type()) {
|
||||
case IndexType::INVERT: {
|
||||
auto invert_params = dynamic_cast<const InvertIndexParams *>(params);
|
||||
if (invert_params) {
|
||||
params_pb.mutable_invert()->CopyFrom(
|
||||
ProtoConverter::ToPb(invert_params));
|
||||
}
|
||||
break;
|
||||
}
|
||||
case IndexType::HNSW: {
|
||||
auto hnsw_params = dynamic_cast<const HnswIndexParams *>(params);
|
||||
if (hnsw_params) {
|
||||
params_pb.mutable_hnsw()->CopyFrom(ProtoConverter::ToPb(hnsw_params));
|
||||
}
|
||||
break;
|
||||
}
|
||||
case IndexType::IVF: {
|
||||
auto ivf_params = dynamic_cast<const IVFIndexParams *>(params);
|
||||
if (ivf_params) {
|
||||
params_pb.mutable_ivf()->CopyFrom(ProtoConverter::ToPb(ivf_params));
|
||||
}
|
||||
break;
|
||||
}
|
||||
case IndexType::FLAT: {
|
||||
auto flat_params = dynamic_cast<const FlatIndexParams *>(params);
|
||||
if (flat_params) {
|
||||
params_pb.mutable_flat()->CopyFrom(ProtoConverter::ToPb(flat_params));
|
||||
}
|
||||
break;
|
||||
}
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
return params_pb;
|
||||
}
|
||||
|
||||
proto::BlockMeta ProtoConverter::ToPb(const BlockMeta &meta) {
|
||||
proto::BlockMeta meta_pb;
|
||||
meta_pb.set_block_id(meta.id());
|
||||
meta_pb.set_block_type(BlockTypeCodeBook::Get(meta.type()));
|
||||
meta_pb.set_min_doc_id(meta.min_doc_id());
|
||||
meta_pb.set_max_doc_id(meta.max_doc_id());
|
||||
meta_pb.set_doc_count(meta.doc_count());
|
||||
for (auto &column : meta.columns()) {
|
||||
meta_pb.add_columns(column);
|
||||
}
|
||||
|
||||
return meta_pb;
|
||||
}
|
||||
|
||||
// SegmentMeta
|
||||
SegmentMeta::Ptr ProtoConverter::FromPb(const proto::SegmentMeta &meta_pb) {
|
||||
auto meta = std::make_shared<SegmentMeta>(meta_pb.segment_id());
|
||||
|
||||
auto persisted_blocks = meta_pb.persisted_blocks();
|
||||
|
||||
for (auto &persisted_block_pb : persisted_blocks) {
|
||||
BlockMeta::Ptr persisted_block = ProtoConverter::FromPb(persisted_block_pb);
|
||||
meta->add_persisted_block(*persisted_block);
|
||||
}
|
||||
|
||||
if (meta_pb.has_writing_forward_block()) {
|
||||
meta->set_writing_forward_block(
|
||||
*ProtoConverter::FromPb(meta_pb.writing_forward_block()));
|
||||
}
|
||||
|
||||
auto indexed_vector_fields = meta_pb.indexed_vector_fields();
|
||||
for (auto &indexed_vector_field : indexed_vector_fields) {
|
||||
meta->add_indexed_vector_field(indexed_vector_field);
|
||||
}
|
||||
|
||||
return meta;
|
||||
}
|
||||
|
||||
proto::SegmentMeta ProtoConverter::ToPb(const SegmentMeta &meta) {
|
||||
proto::SegmentMeta meta_pb;
|
||||
meta_pb.set_segment_id(meta.id());
|
||||
|
||||
auto persisted_blocks = meta.persisted_blocks();
|
||||
for (auto &persisted_block : persisted_blocks) {
|
||||
auto persisted_block_pb = ProtoConverter::ToPb(persisted_block);
|
||||
meta_pb.add_persisted_blocks()->MergeFrom(persisted_block_pb);
|
||||
}
|
||||
|
||||
if (meta.has_writing_forward_block()) {
|
||||
meta_pb.mutable_writing_forward_block()->MergeFrom(
|
||||
ProtoConverter::ToPb(meta.writing_forward_block().value()));
|
||||
}
|
||||
|
||||
auto indexed_vector_fields = meta.indexed_vector_fields();
|
||||
for (auto &field : indexed_vector_fields) {
|
||||
meta_pb.add_indexed_vector_fields(field);
|
||||
}
|
||||
|
||||
return meta_pb;
|
||||
}
|
||||
|
||||
} // namespace zvec
|
||||
@@ -0,0 +1,62 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
#pragma once
|
||||
|
||||
#include "db/index/common/index_params.h"
|
||||
#include "db/index/common/meta.h"
|
||||
#include "db/index/common/schema.h"
|
||||
|
||||
namespace zvec {
|
||||
|
||||
struct ProtoConverter {
|
||||
// HnswIndexParams
|
||||
static HnswIndexParams::OPtr FromPb(const proto::HnswIndexParams ¶ms_pb);
|
||||
|
||||
static proto::HnswIndexParams ToPb(const HnswIndexParams *params);
|
||||
|
||||
// FlatIndexParams
|
||||
static FlatIndexParams::OPtr FromPb(const proto::FlatIndexParams ¶ms_pb);
|
||||
static proto::FlatIndexParams ToPb(const FlatIndexParams *params);
|
||||
|
||||
// IVFIndexParams
|
||||
static IVFIndexParams::OPtr FromPb(const proto::IVFIndexParams ¶ms_pb);
|
||||
static proto::IVFIndexParams ToPb(const IVFIndexParams *params);
|
||||
|
||||
// InvertIndexParams
|
||||
static InvertIndexParams::OPtr FromPb(
|
||||
const proto::InvertIndexParams ¶ms_pb);
|
||||
static proto::InvertIndexParams ToPb(const InvertIndexParams *params);
|
||||
|
||||
// IndexParams
|
||||
static IndexParams::Ptr FromPb(const proto::IndexParams ¶ms_pb);
|
||||
static proto::IndexParams ToPb(const IndexParams *params);
|
||||
|
||||
// FieldSchema
|
||||
static FieldSchema::Ptr FromPb(const proto::FieldSchema &field_pb);
|
||||
static proto::FieldSchema ToPb(const FieldSchema &field);
|
||||
|
||||
// CollectionSchema
|
||||
static CollectionSchema::Ptr FromPb(const proto::CollectionSchema &schema_pb);
|
||||
static proto::CollectionSchema ToPb(const CollectionSchema &schema);
|
||||
|
||||
// BlockMeta
|
||||
static BlockMeta::Ptr FromPb(const proto::BlockMeta &meta_pb);
|
||||
static proto::BlockMeta ToPb(const BlockMeta &meta);
|
||||
|
||||
// SegmentMeta
|
||||
static SegmentMeta::Ptr FromPb(const proto::SegmentMeta &meta_pb);
|
||||
static proto::SegmentMeta ToPb(const SegmentMeta &meta);
|
||||
};
|
||||
|
||||
} // namespace zvec
|
||||
@@ -0,0 +1,150 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
#pragma once
|
||||
|
||||
#include <memory>
|
||||
#include "core/interface/constants.h"
|
||||
#include "type.h"
|
||||
|
||||
namespace zvec {
|
||||
|
||||
/*
|
||||
* Query Index params
|
||||
*/
|
||||
class QueryParams {
|
||||
public:
|
||||
using Ptr = std::shared_ptr<QueryParams>;
|
||||
|
||||
QueryParams(IndexType type) : type_(type) {}
|
||||
virtual ~QueryParams() = default;
|
||||
|
||||
IndexType type() const {
|
||||
return type_;
|
||||
}
|
||||
|
||||
void set_type(IndexType type) {
|
||||
type_ = type;
|
||||
}
|
||||
|
||||
float radius() const {
|
||||
return radius_;
|
||||
}
|
||||
|
||||
void set_radius(float radius) {
|
||||
radius_ = radius;
|
||||
}
|
||||
|
||||
bool is_linear() const {
|
||||
return is_linear_;
|
||||
}
|
||||
|
||||
void set_is_linear(bool is_linear) {
|
||||
is_linear_ = is_linear;
|
||||
}
|
||||
|
||||
void set_is_using_refiner(bool is_using_refiner) {
|
||||
is_using_refiner_ = is_using_refiner;
|
||||
}
|
||||
bool is_using_refiner() const {
|
||||
return is_using_refiner_;
|
||||
}
|
||||
|
||||
private:
|
||||
IndexType type_;
|
||||
float radius_{0.0f};
|
||||
bool is_linear_{false};
|
||||
|
||||
bool is_using_refiner_{false};
|
||||
};
|
||||
|
||||
class HnswQueryParams : public QueryParams {
|
||||
public:
|
||||
HnswQueryParams(int ef = core_interface::kDefaultHnswEfSearch,
|
||||
float radius = 0.0f, bool is_linear = false,
|
||||
bool is_using_refiner = false)
|
||||
: QueryParams(IndexType::HNSW), ef_(ef) {
|
||||
set_radius(radius);
|
||||
set_is_linear(is_linear);
|
||||
set_is_using_refiner(is_using_refiner);
|
||||
}
|
||||
|
||||
virtual ~HnswQueryParams() = default;
|
||||
|
||||
int ef() const {
|
||||
return ef_;
|
||||
}
|
||||
|
||||
void set_ef(int ef) {
|
||||
ef_ = ef;
|
||||
}
|
||||
|
||||
private:
|
||||
int ef_;
|
||||
};
|
||||
|
||||
class IVFQueryParams : public QueryParams {
|
||||
public:
|
||||
IVFQueryParams(int nprobe = 10, bool is_using_refiner = false,
|
||||
float scale_factor = 10)
|
||||
: QueryParams(IndexType::IVF), nprobe_(nprobe) {
|
||||
set_is_using_refiner(is_using_refiner);
|
||||
set_scale_factor(scale_factor);
|
||||
}
|
||||
|
||||
virtual ~IVFQueryParams() = default;
|
||||
|
||||
int nprobe() const {
|
||||
return nprobe_;
|
||||
}
|
||||
|
||||
void set_nprobe(int nprobe) {
|
||||
nprobe_ = nprobe;
|
||||
}
|
||||
|
||||
float scale_factor() const {
|
||||
return scale_factor_;
|
||||
}
|
||||
|
||||
void set_scale_factor(float scale_factor) {
|
||||
scale_factor_ = scale_factor;
|
||||
}
|
||||
|
||||
private:
|
||||
int nprobe_;
|
||||
float scale_factor_{10};
|
||||
};
|
||||
|
||||
class FlatQueryParams : public QueryParams {
|
||||
public:
|
||||
FlatQueryParams(bool is_using_refiner = false, float scale_factor = 10)
|
||||
: QueryParams(IndexType::FLAT) {
|
||||
set_is_using_refiner(is_using_refiner);
|
||||
set_scale_factor(scale_factor);
|
||||
}
|
||||
|
||||
virtual ~FlatQueryParams() = default;
|
||||
|
||||
float scale_factor() const {
|
||||
return scale_factor_;
|
||||
}
|
||||
|
||||
void set_scale_factor(float scale_factor) {
|
||||
scale_factor_ = scale_factor;
|
||||
}
|
||||
|
||||
private:
|
||||
float scale_factor_{10};
|
||||
};
|
||||
|
||||
} // namespace zvec
|
||||
@@ -0,0 +1,461 @@
|
||||
// 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 "schema.h"
|
||||
#include <regex>
|
||||
#include <unordered_map>
|
||||
#include <unordered_set>
|
||||
#include "common/index_params.h"
|
||||
#include "common/type.h"
|
||||
#include "common/type_helper.h"
|
||||
#include "db/common/status.h"
|
||||
#include "db/common/typedef.h"
|
||||
|
||||
namespace zvec {
|
||||
|
||||
std::unordered_map<DataType, std::set<QuantizeType>> quantize_type_map = {
|
||||
{DataType::VECTOR_FP32,
|
||||
{QuantizeType::FP16, QuantizeType::INT4, QuantizeType::INT8}},
|
||||
// {DataType::VECTOR_FP64, {QuantizeType::FP16}},
|
||||
{DataType::SPARSE_VECTOR_FP32, {QuantizeType::FP16}},
|
||||
};
|
||||
|
||||
std::unordered_set<DataType> support_dense_vector_type = {
|
||||
DataType::VECTOR_FP32,
|
||||
DataType::VECTOR_FP16,
|
||||
DataType::VECTOR_INT8,
|
||||
};
|
||||
|
||||
std::unordered_set<DataType> support_sparse_vector_type = {
|
||||
DataType::SPARSE_VECTOR_FP32,
|
||||
DataType::SPARSE_VECTOR_FP16,
|
||||
};
|
||||
|
||||
std::unordered_set<IndexType> support_dense_vector_index = {
|
||||
IndexType::FLAT, IndexType::HNSW, IndexType::IVF};
|
||||
|
||||
std::unordered_set<IndexType> support_sparse_vector_index = {IndexType::FLAT,
|
||||
IndexType::HNSW};
|
||||
|
||||
Status FieldSchema::validate() const {
|
||||
if (data_type_ == DataType::UNDEFINED) {
|
||||
return Status::InvalidArgument("schema validate failed: field[", name_,
|
||||
"]'s data_type is not defined");
|
||||
}
|
||||
if (name_.empty()) {
|
||||
return Status::InvalidArgument("schema validate failed: field[", name_,
|
||||
"]'s name is empty");
|
||||
}
|
||||
if (!std::regex_match(name_, FIELD_NAME_REGEX)) {
|
||||
return Status::InvalidArgument(
|
||||
"schema validate failed: field[", name_,
|
||||
"]'s name cannot pass the regex verification");
|
||||
}
|
||||
if (is_vector_field()) {
|
||||
auto is_sparse = is_sparse_vector();
|
||||
if (!is_sparse && (dimension_ == 0 || dimension() > kMaxDenseDimSize)) {
|
||||
return Status::InvalidArgument("schema validate failed: field[", name_,
|
||||
"]'s dimension must be in (0,20000]");
|
||||
}
|
||||
|
||||
if (!is_sparse) {
|
||||
if (support_dense_vector_type.find(data_type_) ==
|
||||
support_dense_vector_type.end()) {
|
||||
return Status::InvalidArgument(
|
||||
"schema validate failed: dense_vector's data type only "
|
||||
"support FP32, "
|
||||
"but field[",
|
||||
name_, "]'s data type is ", DataTypeCodeBook::AsString(data_type_));
|
||||
}
|
||||
} else {
|
||||
if (support_sparse_vector_type.find(data_type_) ==
|
||||
support_sparse_vector_type.end()) {
|
||||
return Status::InvalidArgument(
|
||||
"schema validate failed: sparse_vector's data type only "
|
||||
"support FP32, "
|
||||
"but field[",
|
||||
name_, "]'s data type is ", DataTypeCodeBook::AsString(data_type_));
|
||||
}
|
||||
}
|
||||
|
||||
if (index_params_) {
|
||||
auto vector_index_params =
|
||||
std::dynamic_pointer_cast<VectorIndexParams>(index_params_);
|
||||
|
||||
if (is_sparse) {
|
||||
if (support_sparse_vector_index.find(index_params_->type()) ==
|
||||
support_sparse_vector_index.end()) {
|
||||
return Status::InvalidArgument(
|
||||
"schema validate failed: sparse_vector's index_params only "
|
||||
"support FLAT|HNSW index, "
|
||||
"but field[",
|
||||
name_, "]'s index_type is ",
|
||||
IndexTypeCodeBook::AsString(index_params_->type()));
|
||||
}
|
||||
if (vector_index_params->metric_type() != MetricType::IP) {
|
||||
return Status::InvalidArgument(
|
||||
"schema validate failed: sparse_vector's index_params only "
|
||||
"support IP metric, but "
|
||||
"field[",
|
||||
name_, "]'s metric is ",
|
||||
MetricTypeCodeBook::AsString(vector_index_params->metric_type()));
|
||||
}
|
||||
|
||||
} else {
|
||||
if (support_dense_vector_index.find(index_params_->type()) ==
|
||||
support_dense_vector_index.end()) {
|
||||
return Status::InvalidArgument(
|
||||
"schema validate failed: dense_vector's index_params only "
|
||||
"support FLAT|HNSW "
|
||||
"index, "
|
||||
"but field[",
|
||||
name_, "]'s index_type is ",
|
||||
IndexTypeCodeBook::AsString(index_params_->type()));
|
||||
}
|
||||
}
|
||||
|
||||
if (vector_index_params->quantize_type() != QuantizeType::UNDEFINED) {
|
||||
auto iter = quantize_type_map.find(data_type_);
|
||||
if (iter == quantize_type_map.end()) {
|
||||
return Status::InvalidArgument(
|
||||
"schema validate failed: ",
|
||||
is_sparse ? "sparse_vector" : "dense_vector",
|
||||
"'s index_params of ", DataTypeCodeBook::AsString(data_type_),
|
||||
" do not support quantize, but field[", name_,
|
||||
"]'s quantize_type is ",
|
||||
QuantizeTypeCodeBook::AsString(
|
||||
vector_index_params->quantize_type()));
|
||||
} else {
|
||||
if (iter->second.find(vector_index_params->quantize_type()) ==
|
||||
iter->second.end()) {
|
||||
return Status::InvalidArgument(
|
||||
"schema validate failed: ",
|
||||
is_sparse ? "sparse_vector" : "dense_vector",
|
||||
"'s index_params of ", DataTypeCodeBook::AsString(data_type_),
|
||||
" support ", QuantizeTypeCodeBook::AsString(iter->second),
|
||||
" quantize, but field[", name_, "]'s quantize_type is ",
|
||||
QuantizeTypeCodeBook::AsString(
|
||||
vector_index_params->quantize_type()));
|
||||
}
|
||||
}
|
||||
}
|
||||
if (index_params_->type() == IndexType::IVF &&
|
||||
vector_index_params->metric_type() == MetricType::IP) {
|
||||
if (data_type_ != DataType::VECTOR_FP16 &&
|
||||
data_type_ != DataType::VECTOR_FP32) {
|
||||
return Status::InvalidArgument(
|
||||
"schema validate failed: IVF index only support FP32/FP16 data "
|
||||
"types according to the IP metric");
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (index_params_) {
|
||||
if (index_params_->is_vector_index_type()) {
|
||||
return Status::InvalidArgument(
|
||||
"schema validate failed: scalar_field's index_params only support "
|
||||
"INVERT "
|
||||
"index, "
|
||||
"but field[",
|
||||
name_, "]'s index_type is ",
|
||||
IndexTypeCodeBook::AsString(index_params_->type()));
|
||||
}
|
||||
}
|
||||
}
|
||||
return Status::OK();
|
||||
}
|
||||
|
||||
Status CollectionSchema::validate() const {
|
||||
if (name_.empty()) {
|
||||
return Status::InvalidArgument("schema validate failed: name is empty");
|
||||
}
|
||||
if (!std::regex_match(name_, COLLECTION_NAME_REGEX)) {
|
||||
return Status::InvalidArgument(
|
||||
"schema validate failed: collection[", name_,
|
||||
"]'s name cannot pass the regex verification");
|
||||
}
|
||||
if (forward_fields().size() > kMaxScalarFieldSize) {
|
||||
return Status::InvalidArgument(
|
||||
"schema validate failed: collection[", name_,
|
||||
"]'s field size must <= ", kMaxScalarFieldSize);
|
||||
}
|
||||
if (max_doc_count_per_segment_ < MAX_DOC_COUNT_PER_SEGMENT_MIN_THRESHOLD) {
|
||||
return Status::InvalidArgument(
|
||||
"schema validate failed: max_doc_count_per_segment must >= ",
|
||||
MAX_DOC_COUNT_PER_SEGMENT_MIN_THRESHOLD);
|
||||
}
|
||||
auto v_fields = vector_fields();
|
||||
if (v_fields.empty()) {
|
||||
return Status::InvalidArgument(
|
||||
"schema validate failed: vector fields is empty");
|
||||
}
|
||||
if (v_fields.size() > kMaxVectorFieldSize) {
|
||||
return Status::InvalidArgument(
|
||||
"schema validate failed: collection[", name_,
|
||||
"]'s vector field size must <= ", kMaxVectorFieldSize);
|
||||
}
|
||||
for (auto &field : fields_) {
|
||||
auto s = field->validate();
|
||||
CHECK_RETURN_STATUS(s);
|
||||
}
|
||||
return Status::OK();
|
||||
}
|
||||
|
||||
Status CollectionSchema::add_field(FieldSchema::Ptr column_schema) {
|
||||
// Check if field already exists
|
||||
if (has_field(column_schema->name())) {
|
||||
return Status::AlreadyExists("field[", column_schema->name(),
|
||||
"] already exists in schema");
|
||||
}
|
||||
|
||||
// Add field to list and map
|
||||
if (column_schema->is_vector_field()) {
|
||||
if (column_schema->index_params() == nullptr) {
|
||||
column_schema->set_index_params(DefaultVectorIndexParams);
|
||||
}
|
||||
}
|
||||
|
||||
fields_.push_back(column_schema);
|
||||
fields_map_[column_schema->name()] = column_schema;
|
||||
|
||||
return Status::OK();
|
||||
}
|
||||
|
||||
Status CollectionSchema::alter_field(
|
||||
const std::string &column_name,
|
||||
const FieldSchema::Ptr &new_column_options) {
|
||||
// Check if field exists
|
||||
if (!has_field(column_name)) {
|
||||
return Status::NotFound("field[", column_name, "] not found in schema");
|
||||
}
|
||||
|
||||
std::string new_column_name = new_column_options->name();
|
||||
|
||||
// If renaming to an existing field name (and it's not the same field)
|
||||
if (new_column_name != column_name && has_field(new_column_name)) {
|
||||
return Status::AlreadyExists("field[", new_column_name,
|
||||
"] already exists in schema");
|
||||
}
|
||||
|
||||
// Update map: remove old entry if name changed, add new entry
|
||||
if (new_column_name != column_name) {
|
||||
fields_map_.erase(column_name);
|
||||
}
|
||||
fields_map_[new_column_name] = new_column_options;
|
||||
|
||||
// Update list
|
||||
for (auto &field : fields_) {
|
||||
if (field->name() == column_name) {
|
||||
field = new_column_options;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return Status::OK();
|
||||
}
|
||||
|
||||
Status CollectionSchema::drop_field(const std::string &column_name) {
|
||||
// Check if field exists
|
||||
if (!has_field(column_name)) {
|
||||
return Status::NotFound("field[", column_name, "] not found in schema");
|
||||
}
|
||||
|
||||
// Remove from map
|
||||
fields_map_.erase(column_name);
|
||||
|
||||
// Remove from list
|
||||
fields_.erase(std::remove_if(fields_.begin(), fields_.end(),
|
||||
[&column_name](const FieldSchema::Ptr &field) {
|
||||
return field->name() == column_name;
|
||||
}),
|
||||
fields_.end());
|
||||
|
||||
return Status::OK();
|
||||
}
|
||||
|
||||
bool CollectionSchema::has_field(const std::string &column) const {
|
||||
return fields_map_.find(column) != fields_map_.end();
|
||||
}
|
||||
|
||||
const FieldSchema *CollectionSchema::get_field(
|
||||
const std::string &column) const {
|
||||
auto it = fields_map_.find(column);
|
||||
if (it != fields_map_.end()) {
|
||||
return it->second.get();
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
FieldSchema *CollectionSchema::get_field(const std::string &column) {
|
||||
auto it = fields_map_.find(column);
|
||||
if (it != fields_map_.end()) {
|
||||
return it->second.get();
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
const FieldSchema *CollectionSchema::get_forward_field(
|
||||
const std::string &column) const {
|
||||
// Forward fields are typically non-vector fields
|
||||
auto field = get_field(column);
|
||||
if (field && !field->is_vector_field()) {
|
||||
return field;
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
FieldSchema *CollectionSchema::get_forward_field(const std::string &column) {
|
||||
// Forward fields are typically non-vector fields
|
||||
auto field = get_field(column);
|
||||
if (field && !field->is_vector_field()) {
|
||||
return field;
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
const FieldSchema *CollectionSchema::get_vector_field(
|
||||
const std::string &column) const {
|
||||
// Vector fields are fields with vector data types
|
||||
auto field = get_field(column);
|
||||
if (field && field->is_vector_field()) {
|
||||
return field;
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
FieldSchema *CollectionSchema::get_vector_field(const std::string &column) {
|
||||
// Vector fields are fields with vector data types
|
||||
auto field = get_field(column);
|
||||
if (field && field->is_vector_field()) {
|
||||
return field;
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
FieldSchemaPtrList CollectionSchema::fields() const {
|
||||
return fields_;
|
||||
}
|
||||
|
||||
FieldSchemaPtrList CollectionSchema::forward_fields() const {
|
||||
FieldSchemaPtrList forward_fields;
|
||||
for (const auto &field : fields_) {
|
||||
if (!field->is_vector_field()) {
|
||||
forward_fields.push_back(field);
|
||||
}
|
||||
}
|
||||
return forward_fields;
|
||||
}
|
||||
|
||||
FieldSchemaPtrList CollectionSchema::forward_fields_with_index() const {
|
||||
FieldSchemaPtrList forward_fields;
|
||||
for (const auto &field : fields_) {
|
||||
if (!field->is_vector_field() && field->index_params() != nullptr) {
|
||||
forward_fields.push_back(field);
|
||||
}
|
||||
}
|
||||
return forward_fields;
|
||||
}
|
||||
|
||||
std::vector<std::string> CollectionSchema::forward_field_names() const {
|
||||
std::vector<std::string> names;
|
||||
for (const auto &field : fields_) {
|
||||
if (!field->is_vector_field()) {
|
||||
names.push_back(field->name());
|
||||
}
|
||||
}
|
||||
return names;
|
||||
}
|
||||
|
||||
std::vector<std::string> CollectionSchema::forward_field_names_with_index()
|
||||
const {
|
||||
std::vector<std::string> names;
|
||||
for (const auto &field : fields_) {
|
||||
if (!field->is_vector_field() && field->index_params() != nullptr) {
|
||||
names.push_back(field->name());
|
||||
}
|
||||
}
|
||||
return names;
|
||||
}
|
||||
|
||||
std::vector<std::string> CollectionSchema::all_field_names() const {
|
||||
std::vector<std::string> names;
|
||||
for (const auto &field : fields_) {
|
||||
names.push_back(field->name());
|
||||
}
|
||||
return names;
|
||||
}
|
||||
|
||||
FieldSchemaPtrList CollectionSchema::vector_fields() const {
|
||||
FieldSchemaPtrList vector_fields;
|
||||
for (const auto &field : fields_) {
|
||||
if (field->is_vector_field()) {
|
||||
vector_fields.push_back(field);
|
||||
}
|
||||
}
|
||||
return vector_fields;
|
||||
}
|
||||
|
||||
uint64_t CollectionSchema::max_doc_count_per_segment() const {
|
||||
return max_doc_count_per_segment_;
|
||||
}
|
||||
|
||||
void CollectionSchema::set_max_doc_count_per_segment(
|
||||
uint64_t max_doc_count_per_segment) {
|
||||
max_doc_count_per_segment_ = max_doc_count_per_segment;
|
||||
}
|
||||
|
||||
Status CollectionSchema::add_index(const std::string &column,
|
||||
const IndexParams::Ptr &index_params) {
|
||||
// Get field and set index params
|
||||
auto field = get_field(column);
|
||||
if (field) {
|
||||
field->set_index_params(index_params);
|
||||
} else {
|
||||
return Status::NotFound("field[", column, "] not found in schema");
|
||||
}
|
||||
|
||||
return Status::OK();
|
||||
}
|
||||
|
||||
Status CollectionSchema::drop_index(const std::string &column) {
|
||||
// Get field and clear index params
|
||||
auto field = get_field(column);
|
||||
if (field) {
|
||||
if (field->is_vector_field()) {
|
||||
field->set_index_params(DefaultVectorIndexParams);
|
||||
} else {
|
||||
field->set_index_params(nullptr);
|
||||
}
|
||||
} else {
|
||||
return Status::NotFound("field[", column, "] not found in schema");
|
||||
}
|
||||
|
||||
return Status::OK();
|
||||
}
|
||||
|
||||
bool CollectionSchema::has_index(const std::string &column) const {
|
||||
auto field = get_field(column);
|
||||
if (field) {
|
||||
if (field->is_vector_field()) {
|
||||
if (field->index_params() == nullptr) {
|
||||
return false;
|
||||
} else {
|
||||
return *field->index_params() != DefaultVectorIndexParams;
|
||||
}
|
||||
}
|
||||
return field->index_params() != nullptr;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
} // namespace zvec
|
||||
@@ -0,0 +1,463 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
#include <unordered_map>
|
||||
#include "db/common/constants.h"
|
||||
#include "db/common/status.h"
|
||||
#include "db/common/utils.h"
|
||||
#include "index_params.h"
|
||||
#include "type.h"
|
||||
|
||||
namespace zvec {
|
||||
|
||||
/*
|
||||
* Field schema
|
||||
*/
|
||||
class FieldSchema {
|
||||
public:
|
||||
using Ptr = std::shared_ptr<FieldSchema>;
|
||||
|
||||
public:
|
||||
FieldSchema() = default;
|
||||
FieldSchema(const std::string &name, DataType type)
|
||||
: name_(name),
|
||||
data_type_(type),
|
||||
nullable_(false),
|
||||
dimension_(0),
|
||||
index_params_(nullptr) {}
|
||||
FieldSchema(const std::string &name, DataType type, bool nullable,
|
||||
const IndexParams::Ptr &index_params = nullptr)
|
||||
: name_(name),
|
||||
data_type_(type),
|
||||
nullable_(nullable),
|
||||
dimension_(0),
|
||||
index_params_(index_params ? index_params->clone() : nullptr) {}
|
||||
FieldSchema(const std::string &name, DataType type, uint32_t dimension,
|
||||
bool nullable, const IndexParams::Ptr &index_params = nullptr)
|
||||
: name_(name),
|
||||
data_type_(type),
|
||||
nullable_(nullable),
|
||||
dimension_(dimension),
|
||||
index_params_(index_params ? index_params->clone() : nullptr) {}
|
||||
FieldSchema(const FieldSchema &other)
|
||||
: name_(other.name_),
|
||||
data_type_(other.data_type_),
|
||||
nullable_(other.nullable_),
|
||||
dimension_(other.dimension_),
|
||||
index_params_(other.index_params_ ? other.index_params_->clone()
|
||||
: nullptr) {}
|
||||
FieldSchema &operator=(const FieldSchema &other) {
|
||||
if (this != &other) {
|
||||
name_ = other.name_;
|
||||
data_type_ = other.data_type_;
|
||||
nullable_ = other.nullable_;
|
||||
dimension_ = other.dimension_;
|
||||
index_params_ =
|
||||
other.index_params_ ? other.index_params_->clone() : nullptr;
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
FieldSchema(FieldSchema &&) = default;
|
||||
FieldSchema &operator=(FieldSchema &&) = default;
|
||||
;
|
||||
~FieldSchema() = default;
|
||||
|
||||
public:
|
||||
bool operator==(const FieldSchema &other) const {
|
||||
bool index_params_equal = false;
|
||||
if (index_params_ == nullptr && other.index_params_ == nullptr) {
|
||||
index_params_equal = true;
|
||||
} else if (index_params_ != nullptr && other.index_params_ != nullptr) {
|
||||
index_params_equal = (*index_params_ == *(other.index_params_));
|
||||
} else {
|
||||
index_params_equal = false;
|
||||
}
|
||||
|
||||
return name_ == other.name_ && data_type_ == other.data_type_ &&
|
||||
nullable_ == other.nullable_ && dimension_ == other.dimension_ &&
|
||||
index_params_equal;
|
||||
}
|
||||
|
||||
bool operator!=(const FieldSchema &other) const {
|
||||
return !(*this == other);
|
||||
}
|
||||
|
||||
std::string to_string() const {
|
||||
std::ostringstream oss;
|
||||
oss << "FieldSchema{"
|
||||
<< "name:'" << name_ << "'"
|
||||
<< ",data_type:" << DataTypeCodeBook::AsString(data_type_)
|
||||
<< ",nullable:" << (nullable_ ? "true" : "false")
|
||||
<< ",dimension:" << dimension_;
|
||||
|
||||
if (index_params_) {
|
||||
oss << ",index_params:" << index_params_->to_string();
|
||||
} else {
|
||||
oss << ",index_params:null";
|
||||
}
|
||||
|
||||
oss << "}";
|
||||
return oss.str();
|
||||
}
|
||||
|
||||
std::string to_string_formatted(int indent_level = 0) const {
|
||||
std::ostringstream oss;
|
||||
oss << indent(indent_level) << "FieldSchema{\n"
|
||||
<< indent(indent_level + 1) << "name: '" << name_ << "',\n"
|
||||
<< indent(indent_level + 1)
|
||||
<< "data_type: " << DataTypeCodeBook::AsString(data_type_) << ",\n"
|
||||
<< indent(indent_level + 1)
|
||||
<< "nullable: " << (nullable_ ? "true" : "false") << ",\n"
|
||||
<< indent(indent_level + 1) << "dimension: " << dimension_ << ",\n";
|
||||
|
||||
if (index_params_) {
|
||||
oss << indent(indent_level + 1)
|
||||
<< "index_params: " << index_params_->to_string() << "\n";
|
||||
} else {
|
||||
oss << indent(indent_level + 1) << "index_params: null\n";
|
||||
}
|
||||
|
||||
oss << indent(indent_level) << "}";
|
||||
return oss.str();
|
||||
}
|
||||
|
||||
public:
|
||||
void set_name(const std::string &name) {
|
||||
name_ = name;
|
||||
}
|
||||
|
||||
const std::string &name() const {
|
||||
return name_;
|
||||
}
|
||||
|
||||
void set_data_type(DataType type) {
|
||||
data_type_ = type;
|
||||
}
|
||||
|
||||
DataType data_type() const {
|
||||
return data_type_;
|
||||
}
|
||||
|
||||
DataType element_data_type() const {
|
||||
return get_element_data_type(data_type_);
|
||||
}
|
||||
|
||||
size_t element_data_size() const {
|
||||
return get_element_data_size(data_type_);
|
||||
}
|
||||
|
||||
bool is_vector_field() const {
|
||||
return is_vector_field(data_type_);
|
||||
}
|
||||
|
||||
bool is_dense_vector() const {
|
||||
return is_dense_vector_field(data_type_);
|
||||
}
|
||||
|
||||
bool is_sparse_vector() const {
|
||||
return is_sparse_vector_field(data_type_);
|
||||
}
|
||||
|
||||
bool nullable() const {
|
||||
return nullable_;
|
||||
}
|
||||
|
||||
void set_nullable(bool nullable) {
|
||||
nullable_ = nullable;
|
||||
}
|
||||
|
||||
bool has_invert_index() const {
|
||||
return !is_vector_field() && index_params_ != nullptr;
|
||||
}
|
||||
|
||||
bool is_array_type() const {
|
||||
return data_type_ >= DataType::ARRAY_BINARY &&
|
||||
data_type_ <= DataType::ARRAY_DOUBLE;
|
||||
}
|
||||
|
||||
void set_dimension(uint32_t dimension) {
|
||||
dimension_ = dimension;
|
||||
}
|
||||
|
||||
uint32_t dimension() const {
|
||||
return dimension_;
|
||||
}
|
||||
|
||||
IndexType index_type() const {
|
||||
if (index_params_) {
|
||||
return index_params_->type();
|
||||
}
|
||||
return IndexType::UNDEFINED;
|
||||
}
|
||||
|
||||
IndexParams::Ptr index_params() const {
|
||||
return index_params_;
|
||||
}
|
||||
|
||||
void set_index_params(const IndexParams::Ptr &index_params) {
|
||||
index_params_ = index_params;
|
||||
}
|
||||
|
||||
void set_index_params(const IndexParams &index_params) {
|
||||
index_params_ = index_params.clone();
|
||||
}
|
||||
|
||||
Status validate() const;
|
||||
|
||||
public:
|
||||
static bool is_dense_vector_field(DataType type) {
|
||||
return type >= DataType::VECTOR_BINARY32 && type <= DataType::VECTOR_INT16;
|
||||
}
|
||||
|
||||
static bool is_sparse_vector_field(DataType type) {
|
||||
return type >= DataType::SPARSE_VECTOR_FP16 &&
|
||||
type <= DataType::SPARSE_VECTOR_FP32;
|
||||
}
|
||||
|
||||
static bool is_vector_field(DataType type) {
|
||||
return is_dense_vector_field(type) || is_sparse_vector_field(type);
|
||||
}
|
||||
|
||||
static DataType get_element_data_type(DataType data_type) {
|
||||
switch (data_type) {
|
||||
case DataType::ARRAY_BINARY:
|
||||
return DataType::BINARY;
|
||||
case DataType::ARRAY_STRING:
|
||||
return DataType::STRING;
|
||||
case DataType::ARRAY_BOOL:
|
||||
return DataType::BOOL;
|
||||
case DataType::ARRAY_INT32:
|
||||
return DataType::INT32;
|
||||
case DataType::ARRAY_INT64:
|
||||
return DataType::INT64;
|
||||
case DataType::ARRAY_UINT32:
|
||||
return DataType::UINT32;
|
||||
case DataType::ARRAY_UINT64:
|
||||
return DataType::UINT64;
|
||||
case DataType::ARRAY_FLOAT:
|
||||
return DataType::FLOAT;
|
||||
case DataType::ARRAY_DOUBLE:
|
||||
return DataType::DOUBLE;
|
||||
default:
|
||||
return data_type;
|
||||
}
|
||||
}
|
||||
|
||||
static size_t get_element_data_size(DataType data_type) {
|
||||
switch (data_type) {
|
||||
case DataType::ARRAY_BINARY:
|
||||
return 0;
|
||||
case DataType::ARRAY_STRING:
|
||||
return 0;
|
||||
case DataType::ARRAY_BOOL:
|
||||
return sizeof(bool);
|
||||
case DataType::ARRAY_INT32:
|
||||
return sizeof(int32_t);
|
||||
case DataType::ARRAY_INT64:
|
||||
return sizeof(int64_t);
|
||||
case DataType::ARRAY_UINT32:
|
||||
return sizeof(uint32_t);
|
||||
case DataType::ARRAY_UINT64:
|
||||
return sizeof(uint64_t);
|
||||
case DataType::ARRAY_FLOAT:
|
||||
return sizeof(float);
|
||||
case DataType::ARRAY_DOUBLE:
|
||||
return sizeof(double);
|
||||
case DataType::BINARY:
|
||||
return 0;
|
||||
case DataType::STRING:
|
||||
return 0;
|
||||
case DataType::BOOL:
|
||||
return sizeof(bool);
|
||||
case DataType::INT32:
|
||||
return sizeof(int32_t);
|
||||
case DataType::INT64:
|
||||
return sizeof(int64_t);
|
||||
case DataType::UINT32:
|
||||
return sizeof(uint32_t);
|
||||
case DataType::UINT64:
|
||||
return sizeof(uint64_t);
|
||||
case DataType::FLOAT:
|
||||
return sizeof(float);
|
||||
case DataType::DOUBLE:
|
||||
return sizeof(double);
|
||||
default:
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private:
|
||||
std::string name_;
|
||||
DataType data_type_{DataType::UNDEFINED};
|
||||
bool nullable_{false};
|
||||
uint32_t dimension_{0U};
|
||||
IndexParams::Ptr index_params_;
|
||||
};
|
||||
|
||||
using FieldSchemaPtrList = std::vector<FieldSchema::Ptr>;
|
||||
using FieldSchemaPtrMap = std::unordered_map<std::string, FieldSchema::Ptr>;
|
||||
|
||||
/*
|
||||
* Collection schema
|
||||
*/
|
||||
class CollectionSchema {
|
||||
public:
|
||||
using Ptr = std::shared_ptr<CollectionSchema>;
|
||||
|
||||
public:
|
||||
CollectionSchema() = default;
|
||||
|
||||
CollectionSchema(const std::string &name) : name_(name) {}
|
||||
|
||||
CollectionSchema(const std::string &name, const FieldSchemaPtrList &fields)
|
||||
: name_(name) {
|
||||
copy_fields(fields);
|
||||
}
|
||||
|
||||
CollectionSchema(const CollectionSchema &other) {
|
||||
name_ = other.name_;
|
||||
copy_fields(other.fields_);
|
||||
max_doc_count_per_segment_ = other.max_doc_count_per_segment_;
|
||||
}
|
||||
|
||||
public:
|
||||
std::string to_string() const {
|
||||
std::ostringstream oss;
|
||||
oss << "CollectionSchema{"
|
||||
<< "name:'" << name_ << "'"
|
||||
<< ",max_doc_count_per_segment:" << max_doc_count_per_segment_
|
||||
<< ",fields:[";
|
||||
|
||||
for (size_t i = 0; i < fields_.size(); ++i) {
|
||||
if (i > 0) oss << ",";
|
||||
oss << fields_[i]->to_string();
|
||||
}
|
||||
|
||||
oss << "]}";
|
||||
return oss.str();
|
||||
}
|
||||
|
||||
|
||||
std::string to_string_formatted(int indent_level = 0) const {
|
||||
std::ostringstream oss;
|
||||
oss << indent(indent_level) << "CollectionSchema{\n"
|
||||
<< indent(indent_level + 1) << "name: '" << name_ << "',\n"
|
||||
<< indent(indent_level + 1)
|
||||
<< "max_doc_count_per_segment: " << max_doc_count_per_segment_ << ",\n"
|
||||
<< indent(indent_level + 1) << "fields: [\n";
|
||||
|
||||
for (size_t i = 0; i < fields_.size(); ++i) {
|
||||
oss << fields_[i]->to_string_formatted(indent_level + 2);
|
||||
if (i < fields_.size() - 1) {
|
||||
oss << ",";
|
||||
}
|
||||
oss << "\n";
|
||||
}
|
||||
|
||||
oss << indent(indent_level + 1) << "]\n" << indent(indent_level) << "}";
|
||||
return oss.str();
|
||||
}
|
||||
|
||||
std::string name() const {
|
||||
return name_;
|
||||
}
|
||||
|
||||
void set_name(const std::string &name) {
|
||||
name_ = name;
|
||||
}
|
||||
|
||||
Status add_field(FieldSchema::Ptr column_schema);
|
||||
|
||||
Status alter_field(const std::string &column_name,
|
||||
const FieldSchema::Ptr &new_column_options);
|
||||
|
||||
Status drop_field(const std::string &column_name);
|
||||
|
||||
bool has_field(const std::string &column) const;
|
||||
|
||||
const FieldSchema *get_field(const std::string &column) const;
|
||||
FieldSchema *get_field(const std::string &column);
|
||||
const FieldSchema *get_forward_field(const std::string &column) const;
|
||||
FieldSchema *get_forward_field(const std::string &column);
|
||||
const FieldSchema *get_vector_field(const std::string &column) const;
|
||||
FieldSchema *get_vector_field(const std::string &column);
|
||||
|
||||
FieldSchemaPtrList fields() const;
|
||||
|
||||
FieldSchemaPtrList forward_fields() const;
|
||||
|
||||
FieldSchemaPtrList forward_fields_with_index() const;
|
||||
|
||||
std::vector<std::string> forward_field_names() const;
|
||||
|
||||
std::vector<std::string> forward_field_names_with_index() const;
|
||||
|
||||
std::vector<std::string> all_field_names() const;
|
||||
|
||||
FieldSchemaPtrList vector_fields() const;
|
||||
|
||||
uint64_t max_doc_count_per_segment() const;
|
||||
|
||||
void set_max_doc_count_per_segment(uint64_t max_doc_count_per_segment);
|
||||
|
||||
Status validate() const;
|
||||
|
||||
public:
|
||||
Status add_index(const std::string &column,
|
||||
const IndexParams::Ptr &index_options);
|
||||
|
||||
Status drop_index(const std::string &column);
|
||||
|
||||
bool has_index(const std::string &column) const;
|
||||
|
||||
public:
|
||||
bool operator==(const CollectionSchema &other) const {
|
||||
if (name_ != other.name_ || fields_.size() != other.fields_.size()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
for (size_t i = 0; i < fields_.size(); ++i) {
|
||||
if (*fields_[i] != *other.fields_[i]) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool operator!=(const CollectionSchema &other) const {
|
||||
return !(*this == other);
|
||||
}
|
||||
|
||||
private:
|
||||
void copy_fields(const FieldSchemaPtrList &fields) {
|
||||
for (auto &field : fields) {
|
||||
auto c = std::make_shared<FieldSchema>(*field);
|
||||
fields_.push_back(c);
|
||||
fields_map_[field->name()] = c;
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
std::string name_{};
|
||||
FieldSchemaPtrList fields_{};
|
||||
FieldSchemaPtrMap fields_map_{};
|
||||
|
||||
uint64_t max_doc_count_per_segment_{MAX_DOC_COUNT_PER_SEGMENT};
|
||||
};
|
||||
|
||||
} // namespace zvec
|
||||
@@ -0,0 +1,70 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
#include "db/common/utils.h"
|
||||
|
||||
namespace zvec {
|
||||
|
||||
/*
|
||||
* Collection stats
|
||||
*/
|
||||
struct CollectionStats {
|
||||
uint64_t doc_count{0};
|
||||
// column -> completeness
|
||||
std::unordered_map<std::string, float> index_completeness;
|
||||
|
||||
std::string to_string() const {
|
||||
std::ostringstream oss;
|
||||
oss << "CollectionStats{" << "doc_count:" << doc_count
|
||||
<< ",index_completeness:{";
|
||||
|
||||
size_t i = 0;
|
||||
for (const auto &pair : index_completeness) {
|
||||
if (i > 0) oss << ",";
|
||||
oss << pair.first << ":" << pair.second;
|
||||
++i;
|
||||
}
|
||||
|
||||
oss << "}}";
|
||||
return oss.str();
|
||||
}
|
||||
|
||||
std::string to_string_formatted(int indent_level = 0) const {
|
||||
std::ostringstream oss;
|
||||
oss << indent(indent_level) << "CollectionStats{\n"
|
||||
<< indent(indent_level + 1) << "doc_count: " << doc_count << ",\n"
|
||||
<< indent(indent_level + 1) << "index_completeness: {\n";
|
||||
|
||||
size_t i = 0;
|
||||
for (const auto &pair : index_completeness) {
|
||||
if (i > 0) oss << ",\n";
|
||||
oss << indent(indent_level + 2) << pair.first << ": " << pair.second;
|
||||
++i;
|
||||
}
|
||||
|
||||
if (!index_completeness.empty()) {
|
||||
oss << "\n";
|
||||
}
|
||||
oss << indent(indent_level + 1) << "}\n" << indent(indent_level) << "}";
|
||||
|
||||
return oss.str();
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace zvec
|
||||
@@ -0,0 +1,140 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
namespace zvec {
|
||||
|
||||
/*
|
||||
* Column index types
|
||||
*/
|
||||
enum class IndexType : uint32_t {
|
||||
UNDEFINED = 0,
|
||||
HNSW = 1,
|
||||
IVF = 3,
|
||||
FLAT = 4,
|
||||
INVERT = 10,
|
||||
};
|
||||
|
||||
/*
|
||||
* Column data types
|
||||
*/
|
||||
enum class DataType : uint32_t {
|
||||
UNDEFINED = 0,
|
||||
|
||||
BINARY = 1,
|
||||
STRING = 2,
|
||||
BOOL = 3,
|
||||
INT32 = 4,
|
||||
INT64 = 5,
|
||||
UINT32 = 6,
|
||||
UINT64 = 7,
|
||||
FLOAT = 8,
|
||||
DOUBLE = 9,
|
||||
|
||||
VECTOR_BINARY32 = 20,
|
||||
VECTOR_BINARY64 = 21,
|
||||
VECTOR_FP16 = 22,
|
||||
VECTOR_FP32 = 23,
|
||||
VECTOR_FP64 = 24,
|
||||
VECTOR_INT4 = 25,
|
||||
VECTOR_INT8 = 26,
|
||||
VECTOR_INT16 = 27,
|
||||
|
||||
SPARSE_VECTOR_FP16 = 30,
|
||||
SPARSE_VECTOR_FP32 = 31,
|
||||
|
||||
ARRAY_BINARY = 40,
|
||||
ARRAY_STRING = 41,
|
||||
ARRAY_BOOL = 42,
|
||||
ARRAY_INT32 = 43,
|
||||
ARRAY_INT64 = 44,
|
||||
ARRAY_UINT32 = 45,
|
||||
ARRAY_UINT64 = 46,
|
||||
ARRAY_FLOAT = 47,
|
||||
ARRAY_DOUBLE = 48,
|
||||
};
|
||||
|
||||
enum class QuantizeType : uint32_t {
|
||||
UNDEFINED = 0,
|
||||
FP16 = 1,
|
||||
INT8 = 2,
|
||||
INT4 = 3,
|
||||
};
|
||||
|
||||
enum class MetricType : uint32_t {
|
||||
UNDEFINED = 0,
|
||||
L2 = 1,
|
||||
IP = 2,
|
||||
COSINE = 3,
|
||||
MIPSL2 = 4,
|
||||
};
|
||||
|
||||
enum class Operator : uint32_t {
|
||||
INSERT = 0,
|
||||
UPSERT = 1,
|
||||
UPDATE = 2,
|
||||
DELETE = 3,
|
||||
};
|
||||
|
||||
enum class CompareOp : uint32_t {
|
||||
NONE = 0,
|
||||
EQ,
|
||||
NE,
|
||||
LT,
|
||||
LE,
|
||||
GT,
|
||||
GE,
|
||||
LIKE,
|
||||
CONTAIN_ALL,
|
||||
CONTAIN_ANY,
|
||||
NOT_CONTAIN_ALL,
|
||||
NOT_CONTAIN_ANY,
|
||||
IS_NULL,
|
||||
IS_NOT_NULL,
|
||||
HAS_PREFIX,
|
||||
HAS_SUFFIX,
|
||||
};
|
||||
|
||||
enum RelationOp : uint32_t {
|
||||
NONE = 0,
|
||||
|
||||
AND = 1,
|
||||
OR = 2
|
||||
};
|
||||
|
||||
enum BlockType : uint32_t {
|
||||
UNDEFINED = 0,
|
||||
SCALAR = 1,
|
||||
SCALAR_INDEX = 2,
|
||||
VECTOR_INDEX = 3,
|
||||
VECTOR_INDEX_QUANTIZE = 4,
|
||||
};
|
||||
|
||||
|
||||
enum class FileFormat : uint32_t {
|
||||
UNKNOWN = 0,
|
||||
IPC = 1,
|
||||
PARQUET = 2,
|
||||
};
|
||||
|
||||
enum class ColumnOp : uint32_t {
|
||||
UNDEFINED = 0,
|
||||
ADD,
|
||||
ALTER,
|
||||
DROP,
|
||||
};
|
||||
|
||||
} // namespace zvec
|
||||
@@ -0,0 +1,49 @@
|
||||
// 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 "type_helper.h"
|
||||
#include "core/framework/index_meta.h"
|
||||
|
||||
namespace zvec {
|
||||
|
||||
core::IndexMeta::DataType DataTypeCodeBook::to_data_type(DataType type) {
|
||||
switch (type) {
|
||||
case DataType::VECTOR_FP32:
|
||||
return core::IndexMeta::DataType::DT_FP32;
|
||||
case DataType::VECTOR_FP64:
|
||||
return core::IndexMeta::DataType::DT_FP64;
|
||||
case DataType::VECTOR_FP16:
|
||||
return core::IndexMeta::DataType::DT_FP16;
|
||||
case DataType::VECTOR_INT8:
|
||||
return core::IndexMeta::DataType::DT_INT8;
|
||||
case DataType::VECTOR_INT16:
|
||||
return core::IndexMeta::DataType::DT_INT16;
|
||||
case DataType::VECTOR_INT4:
|
||||
return core::IndexMeta::DataType::DT_INT4;
|
||||
case DataType::VECTOR_BINARY32:
|
||||
return core::IndexMeta::DataType::DT_BINARY32;
|
||||
case DataType::VECTOR_BINARY64:
|
||||
return core::IndexMeta::DataType::DT_BINARY64;
|
||||
|
||||
case DataType::SPARSE_VECTOR_FP16:
|
||||
return core::IndexMeta::DataType::DT_FP16;
|
||||
case DataType::SPARSE_VECTOR_FP32:
|
||||
return core::IndexMeta::DataType::DT_FP32;
|
||||
|
||||
default:
|
||||
return core::IndexMeta::DataType::DT_UNDEFINED;
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace zvec
|
||||
@@ -0,0 +1,510 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
#pragma once
|
||||
|
||||
#include <core/framework/index_meta.h>
|
||||
#include "db/index/common/type.h"
|
||||
#include "proto/zvec.pb.h"
|
||||
|
||||
namespace zvec {
|
||||
|
||||
//! Index Type Codebook
|
||||
struct IndexTypeCodeBook {
|
||||
//! convert protobuf IndexType to C++ IndexType
|
||||
static IndexType Get(proto::IndexType type) {
|
||||
switch (type) {
|
||||
case proto::IT_HNSW:
|
||||
return IndexType::HNSW;
|
||||
case proto::IT_FLAT:
|
||||
return IndexType::FLAT;
|
||||
case proto::IT_IVF:
|
||||
return IndexType::IVF;
|
||||
case proto::IT_INVERT:
|
||||
return IndexType::INVERT;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
return IndexType::UNDEFINED;
|
||||
}
|
||||
|
||||
//! Convert C++ IndexType to protobuf IndexType
|
||||
static proto::IndexType Get(IndexType type) {
|
||||
switch (type) {
|
||||
case IndexType::HNSW:
|
||||
return proto::IT_HNSW;
|
||||
case IndexType::FLAT:
|
||||
return proto::IT_FLAT;
|
||||
case IndexType::IVF:
|
||||
return proto::IT_IVF;
|
||||
case IndexType::INVERT:
|
||||
return proto::IT_INVERT;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
return proto::IT_UNDEFINED;
|
||||
}
|
||||
|
||||
//! Convert C++ IndexType to C++ String
|
||||
static std::string AsString(IndexType type) {
|
||||
switch (type) {
|
||||
case IndexType::HNSW:
|
||||
return "HNSW";
|
||||
// case IndexType::SPARSE_HNSW:
|
||||
// return "SPARSE_HNSW";
|
||||
case IndexType::INVERT:
|
||||
return "INVERT";
|
||||
default:
|
||||
break;
|
||||
}
|
||||
return "UNDEFINED";
|
||||
}
|
||||
};
|
||||
|
||||
struct DataTypeCodeBook {
|
||||
static bool IsArrayType(proto::DataType type) {
|
||||
return proto::DataType::DT_ARRAY_BINARY <= type &&
|
||||
type <= proto::DataType::DT_ARRAY_DOUBLE;
|
||||
}
|
||||
|
||||
static DataType Get(proto::DataType type) {
|
||||
DataType data_types = DataType::UNDEFINED;
|
||||
switch (type) {
|
||||
case proto::DataType::DT_BINARY:
|
||||
data_types = DataType::BINARY;
|
||||
break;
|
||||
case proto::DataType::DT_STRING:
|
||||
data_types = DataType::STRING;
|
||||
break;
|
||||
case proto::DataType::DT_BOOL:
|
||||
data_types = DataType::BOOL;
|
||||
break;
|
||||
case proto::DataType::DT_INT32:
|
||||
data_types = DataType::INT32;
|
||||
break;
|
||||
case proto::DataType::DT_INT64:
|
||||
data_types = DataType::INT64;
|
||||
break;
|
||||
case proto::DataType::DT_UINT32:
|
||||
data_types = DataType::UINT32;
|
||||
break;
|
||||
case proto::DataType::DT_UINT64:
|
||||
data_types = DataType::UINT64;
|
||||
break;
|
||||
case proto::DataType::DT_FLOAT:
|
||||
data_types = DataType::FLOAT;
|
||||
break;
|
||||
case proto::DataType::DT_DOUBLE:
|
||||
data_types = DataType::DOUBLE;
|
||||
break;
|
||||
case proto::DataType::DT_VECTOR_BINARY32:
|
||||
data_types = DataType::VECTOR_BINARY32;
|
||||
break;
|
||||
case proto::DataType::DT_VECTOR_BINARY64:
|
||||
data_types = DataType::VECTOR_BINARY64;
|
||||
break;
|
||||
case proto::DataType::DT_VECTOR_FP16:
|
||||
data_types = DataType::VECTOR_FP16;
|
||||
break;
|
||||
case proto::DataType::DT_VECTOR_FP32:
|
||||
data_types = DataType::VECTOR_FP32;
|
||||
break;
|
||||
case proto::DataType::DT_VECTOR_FP64:
|
||||
data_types = DataType::VECTOR_FP64;
|
||||
break;
|
||||
case proto::DataType::DT_VECTOR_INT4:
|
||||
data_types = DataType::VECTOR_INT4;
|
||||
break;
|
||||
case proto::DataType::DT_VECTOR_INT8:
|
||||
data_types = DataType::VECTOR_INT8;
|
||||
break;
|
||||
case proto::DataType::DT_VECTOR_INT16:
|
||||
data_types = DataType::VECTOR_INT16;
|
||||
break;
|
||||
case proto::DataType::DT_SPARSE_VECTOR_FP16:
|
||||
data_types = DataType::SPARSE_VECTOR_FP16;
|
||||
break;
|
||||
case proto::DataType::DT_SPARSE_VECTOR_FP32:
|
||||
data_types = DataType::SPARSE_VECTOR_FP32;
|
||||
break;
|
||||
case proto::DataType::DT_ARRAY_BINARY:
|
||||
data_types = DataType::ARRAY_BINARY;
|
||||
break;
|
||||
case proto::DataType::DT_ARRAY_STRING:
|
||||
data_types = DataType::ARRAY_STRING;
|
||||
break;
|
||||
case proto::DataType::DT_ARRAY_BOOL:
|
||||
data_types = DataType::ARRAY_BOOL;
|
||||
break;
|
||||
case proto::DataType::DT_ARRAY_INT32:
|
||||
data_types = DataType::ARRAY_INT32;
|
||||
break;
|
||||
case proto::DataType::DT_ARRAY_INT64:
|
||||
data_types = DataType::ARRAY_INT64;
|
||||
break;
|
||||
case proto::DataType::DT_ARRAY_UINT32:
|
||||
data_types = DataType::ARRAY_UINT32;
|
||||
break;
|
||||
case proto::DataType::DT_ARRAY_UINT64:
|
||||
data_types = DataType::ARRAY_UINT64;
|
||||
break;
|
||||
case proto::DataType::DT_ARRAY_FLOAT:
|
||||
data_types = DataType::ARRAY_FLOAT;
|
||||
break;
|
||||
case proto::DataType::DT_ARRAY_DOUBLE:
|
||||
data_types = DataType::ARRAY_DOUBLE;
|
||||
break;
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
return data_types;
|
||||
}
|
||||
|
||||
static proto::DataType Get(const DataType type) {
|
||||
proto::DataType data_type = proto::DataType::DT_UNDEFINED;
|
||||
switch (type) {
|
||||
case DataType::BINARY:
|
||||
data_type = proto::DataType::DT_BINARY;
|
||||
break;
|
||||
case DataType::STRING:
|
||||
data_type = proto::DataType::DT_STRING;
|
||||
break;
|
||||
case DataType::BOOL:
|
||||
data_type = proto::DataType::DT_BOOL;
|
||||
break;
|
||||
case DataType::INT32:
|
||||
data_type = proto::DataType::DT_INT32;
|
||||
break;
|
||||
case DataType::INT64:
|
||||
data_type = proto::DataType::DT_INT64;
|
||||
break;
|
||||
case DataType::UINT32:
|
||||
data_type = proto::DataType::DT_UINT32;
|
||||
break;
|
||||
case DataType::UINT64:
|
||||
data_type = proto::DataType::DT_UINT64;
|
||||
break;
|
||||
case DataType::FLOAT:
|
||||
data_type = proto::DataType::DT_FLOAT;
|
||||
break;
|
||||
case DataType::DOUBLE:
|
||||
data_type = proto::DataType::DT_DOUBLE;
|
||||
break;
|
||||
case DataType::VECTOR_BINARY32:
|
||||
data_type = proto::DataType::DT_VECTOR_BINARY32;
|
||||
break;
|
||||
case DataType::VECTOR_BINARY64:
|
||||
data_type = proto::DataType::DT_VECTOR_BINARY64;
|
||||
break;
|
||||
case DataType::VECTOR_FP16:
|
||||
data_type = proto::DataType::DT_VECTOR_FP16;
|
||||
break;
|
||||
case DataType::VECTOR_FP32:
|
||||
data_type = proto::DataType::DT_VECTOR_FP32;
|
||||
break;
|
||||
case DataType::VECTOR_FP64:
|
||||
data_type = proto::DataType::DT_VECTOR_FP64;
|
||||
break;
|
||||
case DataType::VECTOR_INT4:
|
||||
data_type = proto::DataType::DT_VECTOR_INT4;
|
||||
break;
|
||||
case DataType::VECTOR_INT8:
|
||||
data_type = proto::DataType::DT_VECTOR_INT8;
|
||||
break;
|
||||
case DataType::VECTOR_INT16:
|
||||
data_type = proto::DataType::DT_VECTOR_INT16;
|
||||
break;
|
||||
case DataType::SPARSE_VECTOR_FP16:
|
||||
data_type = proto::DataType::DT_SPARSE_VECTOR_FP16;
|
||||
break;
|
||||
case DataType::SPARSE_VECTOR_FP32:
|
||||
data_type = proto::DataType::DT_SPARSE_VECTOR_FP32;
|
||||
break;
|
||||
case DataType::ARRAY_BINARY:
|
||||
data_type = proto::DataType::DT_ARRAY_BINARY;
|
||||
break;
|
||||
case DataType::ARRAY_BOOL:
|
||||
data_type = proto::DataType::DT_ARRAY_BOOL;
|
||||
break;
|
||||
case DataType::ARRAY_DOUBLE:
|
||||
data_type = proto::DataType::DT_ARRAY_DOUBLE;
|
||||
break;
|
||||
case DataType::ARRAY_FLOAT:
|
||||
data_type = proto::DataType::DT_ARRAY_FLOAT;
|
||||
break;
|
||||
case DataType::ARRAY_INT32:
|
||||
data_type = proto::DataType::DT_ARRAY_INT32;
|
||||
break;
|
||||
case DataType::ARRAY_INT64:
|
||||
data_type = proto::DataType::DT_ARRAY_INT64;
|
||||
break;
|
||||
case DataType::ARRAY_STRING:
|
||||
data_type = proto::DataType::DT_ARRAY_STRING;
|
||||
break;
|
||||
case DataType::ARRAY_UINT32:
|
||||
data_type = proto::DataType::DT_ARRAY_UINT32;
|
||||
break;
|
||||
case DataType::ARRAY_UINT64:
|
||||
data_type = proto::DataType::DT_ARRAY_UINT64;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
return data_type;
|
||||
}
|
||||
|
||||
static std::string AsString(DataType type) {
|
||||
std::string data_type;
|
||||
|
||||
switch (type) {
|
||||
case DataType::BINARY:
|
||||
data_type = "BINARY";
|
||||
break;
|
||||
case DataType::STRING:
|
||||
data_type = "STRING";
|
||||
break;
|
||||
case DataType::BOOL:
|
||||
data_type = "BOOL";
|
||||
break;
|
||||
case DataType::INT32:
|
||||
data_type = "INT32";
|
||||
break;
|
||||
case DataType::INT64:
|
||||
data_type = "INT64";
|
||||
break;
|
||||
case DataType::UINT32:
|
||||
data_type = "UINT32";
|
||||
break;
|
||||
case DataType::UINT64:
|
||||
data_type = "UINT64";
|
||||
break;
|
||||
case DataType::FLOAT:
|
||||
data_type = "FLOAT";
|
||||
break;
|
||||
case DataType::DOUBLE:
|
||||
data_type = "DOUBLE";
|
||||
break;
|
||||
case DataType::VECTOR_BINARY32:
|
||||
data_type = "VECTOR_BINARY32";
|
||||
break;
|
||||
case DataType::VECTOR_BINARY64:
|
||||
data_type = "VECTOR_BINARY64";
|
||||
break;
|
||||
case DataType::VECTOR_FP16:
|
||||
data_type = "VECTOR_FP16";
|
||||
break;
|
||||
case DataType::VECTOR_FP32:
|
||||
data_type = "VECTOR_FP32";
|
||||
break;
|
||||
case DataType::VECTOR_FP64:
|
||||
data_type = "VECTOR_FP64";
|
||||
break;
|
||||
case DataType::VECTOR_INT4:
|
||||
data_type = "VECTOR_INT4";
|
||||
break;
|
||||
case DataType::VECTOR_INT8:
|
||||
data_type = "VECTOR_INT8";
|
||||
break;
|
||||
case DataType::VECTOR_INT16:
|
||||
data_type = "VECTOR_INT16";
|
||||
break;
|
||||
case DataType::ARRAY_BINARY:
|
||||
data_type = "ARRAY_BINARY";
|
||||
break;
|
||||
case DataType::ARRAY_BOOL:
|
||||
data_type = "ARRAY_BOOL";
|
||||
break;
|
||||
case DataType::ARRAY_DOUBLE:
|
||||
data_type = "ARRAY_DOUBLE";
|
||||
break;
|
||||
case DataType::ARRAY_FLOAT:
|
||||
data_type = "ARRAY_FLOAT";
|
||||
break;
|
||||
case DataType::ARRAY_INT32:
|
||||
data_type = "ARRAY_INT32";
|
||||
break;
|
||||
case DataType::ARRAY_INT64:
|
||||
data_type = "ARRAY_INT64";
|
||||
break;
|
||||
case DataType::ARRAY_STRING:
|
||||
data_type = "ARRAY_STRING";
|
||||
break;
|
||||
case DataType::ARRAY_UINT32:
|
||||
data_type = "ARRAY_UINT32";
|
||||
break;
|
||||
case DataType::ARRAY_UINT64:
|
||||
data_type = "ARRAY_UINT64";
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
return data_type;
|
||||
}
|
||||
|
||||
static core::IndexMeta::DataType to_data_type(DataType type);
|
||||
};
|
||||
|
||||
struct MetricTypeCodeBook {
|
||||
static MetricType Get(proto::MetricType type) {
|
||||
switch (type) {
|
||||
case proto::MetricType::MT_IP:
|
||||
return MetricType::IP;
|
||||
case proto::MetricType::MT_L2:
|
||||
return MetricType::L2;
|
||||
case proto::MetricType::MT_COSINE:
|
||||
return MetricType::COSINE;
|
||||
default:
|
||||
return MetricType::UNDEFINED;
|
||||
}
|
||||
}
|
||||
|
||||
static proto::MetricType Get(MetricType type) {
|
||||
switch (type) {
|
||||
case MetricType::IP:
|
||||
return proto::MetricType::MT_IP;
|
||||
case MetricType::L2:
|
||||
return proto::MetricType::MT_L2;
|
||||
case MetricType::COSINE:
|
||||
return proto::MetricType::MT_COSINE;
|
||||
default:
|
||||
return proto::MetricType::MT_UNDEFINED;
|
||||
}
|
||||
}
|
||||
|
||||
static std::string AsString(MetricType type) {
|
||||
switch (type) {
|
||||
case MetricType::IP:
|
||||
return "IP";
|
||||
case MetricType::L2:
|
||||
return "L2";
|
||||
case MetricType::COSINE:
|
||||
return "COSINE";
|
||||
default:
|
||||
return "UNDEFINED";
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
struct QuantizeTypeCodeBook {
|
||||
static QuantizeType Get(proto::QuantizeType type) {
|
||||
switch (type) {
|
||||
case proto::QuantizeType::QT_FP16:
|
||||
return QuantizeType::FP16;
|
||||
case proto::QuantizeType::QT_INT4:
|
||||
return QuantizeType::INT4;
|
||||
case proto::QuantizeType::QT_INT8:
|
||||
return QuantizeType::INT8;
|
||||
default:
|
||||
return QuantizeType::UNDEFINED;
|
||||
}
|
||||
}
|
||||
|
||||
static proto::QuantizeType Get(QuantizeType type) {
|
||||
switch (type) {
|
||||
case QuantizeType::FP16:
|
||||
return proto::QuantizeType::QT_FP16;
|
||||
case QuantizeType::INT4:
|
||||
return proto::QuantizeType::QT_INT4;
|
||||
case QuantizeType::INT8:
|
||||
return proto::QuantizeType::QT_INT8;
|
||||
default:
|
||||
return proto::QuantizeType::QT_UNDEFINED;
|
||||
}
|
||||
}
|
||||
|
||||
static std::string AsString(QuantizeType type) {
|
||||
switch (type) {
|
||||
case QuantizeType::FP16:
|
||||
return "FP16";
|
||||
case QuantizeType::INT4:
|
||||
return "INT4";
|
||||
case QuantizeType::INT8:
|
||||
return "INT8";
|
||||
default:
|
||||
return "UNDEFINED";
|
||||
}
|
||||
}
|
||||
|
||||
static std::string AsString(std::set<QuantizeType> type) {
|
||||
std::string str;
|
||||
for (auto t : type) {
|
||||
str += QuantizeTypeCodeBook::AsString(t) + ",";
|
||||
}
|
||||
return str.substr(0, str.size() - 1);
|
||||
}
|
||||
};
|
||||
|
||||
struct BlockTypeCodeBook {
|
||||
static BlockType Get(proto::BlockType type) {
|
||||
BlockType block_types = BlockType::UNDEFINED;
|
||||
switch (type) {
|
||||
case proto::BlockType::BT_SCALAR:
|
||||
block_types = BlockType::SCALAR;
|
||||
break;
|
||||
case proto::BlockType::BT_SCALAR_INDEX:
|
||||
block_types = BlockType::SCALAR_INDEX;
|
||||
break;
|
||||
case proto::BlockType::BT_VECTOR_INDEX:
|
||||
block_types = BlockType::VECTOR_INDEX;
|
||||
break;
|
||||
case proto::BlockType::BT_VECTOR_INDEX_QUANTIZE:
|
||||
block_types = BlockType::VECTOR_INDEX_QUANTIZE;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
return block_types;
|
||||
}
|
||||
|
||||
static proto::BlockType Get(BlockType type) {
|
||||
proto::BlockType block_types = proto::BlockType::BT_UNDEFINED;
|
||||
switch (type) {
|
||||
case BlockType::SCALAR:
|
||||
block_types = proto::BlockType::BT_SCALAR;
|
||||
break;
|
||||
case BlockType::SCALAR_INDEX:
|
||||
block_types = proto::BlockType::BT_SCALAR_INDEX;
|
||||
break;
|
||||
case BlockType::VECTOR_INDEX:
|
||||
block_types = proto::BlockType::BT_VECTOR_INDEX;
|
||||
break;
|
||||
case BlockType::VECTOR_INDEX_QUANTIZE:
|
||||
block_types = proto::BlockType::BT_VECTOR_INDEX_QUANTIZE;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
return block_types;
|
||||
}
|
||||
|
||||
static std::string AsString(BlockType type) {
|
||||
switch (type) {
|
||||
case BlockType::SCALAR:
|
||||
return "SCALAR";
|
||||
case BlockType::SCALAR_INDEX:
|
||||
return "SCALAR_INDEX";
|
||||
case BlockType::VECTOR_INDEX:
|
||||
return "VECTOR_INDEX";
|
||||
case BlockType::VECTOR_INDEX_QUANTIZE:
|
||||
return "VECTOR_INDEX_QUANTIZE";
|
||||
default:
|
||||
return "UNDEFINED";
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace zvec
|
||||
@@ -0,0 +1,301 @@
|
||||
// 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 "version_manager.h"
|
||||
#include <cerrno>
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <mutex>
|
||||
#include <regex>
|
||||
#include <string>
|
||||
#include <ailego/logger/logger.h>
|
||||
#include <ailego/utility/string_helper.h>
|
||||
#include <proto/zvec.pb.h>
|
||||
#include "ailego/pattern/expected.hpp"
|
||||
#include "db/common/file_helper.h"
|
||||
#include "db/common/status.h"
|
||||
#include "db/common/typedef.h"
|
||||
#include "db/index/common/proto_converter.h"
|
||||
#include "db/index/common/type_helper.h"
|
||||
|
||||
namespace zvec {
|
||||
|
||||
Status Version::Load(const std::string &path, Version *version) {
|
||||
std::ifstream ifs(path, std::ios::binary);
|
||||
if (!ifs.is_open()) {
|
||||
LOG_ERROR("Failed to open file: %s", path.c_str());
|
||||
return Status::InternalError("Failed to open file");
|
||||
}
|
||||
|
||||
proto::Manifest manifest;
|
||||
|
||||
if (!manifest.ParseFromIstream(&ifs)) {
|
||||
LOG_ERROR("Failed to parse manifest from file: %s", path.c_str());
|
||||
return Status::InternalError("Failed to parse manifest");
|
||||
}
|
||||
|
||||
CollectionSchema::Ptr schema = ProtoConverter::FromPb(manifest.schema());
|
||||
version->set_schema(*schema);
|
||||
|
||||
version->set_enable_mmap(manifest.enable_mmap());
|
||||
|
||||
for (int i = 0; i < manifest.persisted_segment_metas_size(); ++i) {
|
||||
SegmentMeta::Ptr meta =
|
||||
ProtoConverter::FromPb(manifest.persisted_segment_metas(i));
|
||||
version->add_persisted_segment_meta(meta);
|
||||
}
|
||||
|
||||
if (manifest.has_writing_segment_meta()) {
|
||||
SegmentMeta::Ptr meta =
|
||||
ProtoConverter::FromPb(manifest.writing_segment_meta());
|
||||
version->reset_writing_segment_meta(meta);
|
||||
}
|
||||
|
||||
version->set_id_map_path_suffix(manifest.id_map_path_suffix());
|
||||
version->set_delete_snapshot_path_suffix(
|
||||
manifest.delete_snapshot_path_suffix());
|
||||
|
||||
version->set_next_segment_id(manifest.next_segment_id());
|
||||
|
||||
return Status::OK();
|
||||
}
|
||||
|
||||
Status Version::Save(const std::string &path, const Version &version) {
|
||||
std::ofstream ofs(path, std::ios::binary);
|
||||
if (!ofs.is_open()) {
|
||||
LOG_ERROR("Failed to open file: %s, err: %s", path.c_str(),
|
||||
strerror(errno));
|
||||
return Status::InternalError("Failed to open file: %s", path.c_str());
|
||||
}
|
||||
|
||||
proto::Manifest manifest;
|
||||
|
||||
// set schema
|
||||
auto schema = ProtoConverter::ToPb(version.schema());
|
||||
manifest.mutable_schema()->Swap(&schema);
|
||||
|
||||
manifest.set_enable_mmap(version.enable_mmap());
|
||||
|
||||
// set segments meta
|
||||
for (auto &meta : version.persisted_segment_metas()) {
|
||||
auto meta_pb = ProtoConverter::ToPb(*meta);
|
||||
manifest.add_persisted_segment_metas()->Swap(&meta_pb);
|
||||
}
|
||||
|
||||
if (version.writing_segment_meta()) {
|
||||
auto meta_pb = ProtoConverter::ToPb(*version.writing_segment_meta());
|
||||
manifest.mutable_writing_segment_meta()->Swap(&meta_pb);
|
||||
}
|
||||
|
||||
manifest.set_id_map_path_suffix(version.id_map_path_suffix());
|
||||
manifest.set_delete_snapshot_path_suffix(
|
||||
version.delete_snapshot_path_suffix());
|
||||
manifest.set_next_segment_id(version.next_segment_id());
|
||||
|
||||
if (!manifest.SerializeToOstream(&ofs)) {
|
||||
LOG_ERROR("Failed to serialize manifest to file: %s", path.c_str());
|
||||
return Status::InternalError("Failed to serialize manifest to file");
|
||||
}
|
||||
|
||||
return Status::OK();
|
||||
}
|
||||
|
||||
std::string Version::to_string() const {
|
||||
std::ostringstream oss;
|
||||
oss << "Version{" << "schema:" << (schema_ ? schema_->to_string() : "null")
|
||||
<< ",persisted_segment_metas:[";
|
||||
|
||||
size_t i = 0;
|
||||
for (const auto &pair : persisted_segment_metas_map_) {
|
||||
if (i > 0) oss << ",";
|
||||
oss << pair.second->to_string();
|
||||
++i;
|
||||
}
|
||||
|
||||
oss << "],writing_segment_meta:";
|
||||
if (writing_segment_meta_) {
|
||||
oss << writing_segment_meta_->to_string();
|
||||
} else {
|
||||
oss << "null";
|
||||
}
|
||||
|
||||
oss << ",id_map_path_suffix:" << id_map_path_suffix_
|
||||
<< ",delete_snapshot_path_suffix:" << delete_snapshot_path_suffix_
|
||||
<< ",next_segment_id:" << next_segment_id_
|
||||
<< ",enable_mmap:" << enable_mmap_ << "}";
|
||||
return oss.str();
|
||||
}
|
||||
|
||||
std::string Version::to_string_formatted(int indent_level) const {
|
||||
std::ostringstream oss;
|
||||
oss << indent(indent_level) << "Version{\n"
|
||||
<< indent(indent_level + 1) << "schema: ";
|
||||
|
||||
if (schema_) {
|
||||
oss << "\n" << schema_->to_string_formatted(indent_level + 2) << "\n";
|
||||
} else {
|
||||
oss << "null\n";
|
||||
}
|
||||
|
||||
oss << indent(indent_level + 1) << "persisted_segment_metas: [\n";
|
||||
|
||||
size_t i = 0;
|
||||
for (const auto &pair : persisted_segment_metas_map_) {
|
||||
oss << pair.second->to_string_formatted(indent_level + 2);
|
||||
if (i < persisted_segment_metas_map_.size() - 1) {
|
||||
oss << ",";
|
||||
}
|
||||
oss << "\n";
|
||||
++i;
|
||||
}
|
||||
|
||||
oss << "\n"
|
||||
<< indent(indent_level + 1) << "],\n"
|
||||
<< indent(indent_level + 1) << "writing_segment_meta: ";
|
||||
|
||||
if (writing_segment_meta_) {
|
||||
oss << "\n"
|
||||
<< writing_segment_meta_->to_string_formatted(indent_level + 2) << "\n";
|
||||
} else {
|
||||
oss << "null\n";
|
||||
}
|
||||
|
||||
oss << indent(indent_level + 1)
|
||||
<< "id_map_path_suffix: " << id_map_path_suffix_ << ",\n"
|
||||
<< indent(indent_level + 1)
|
||||
<< "delete_snapshot_path_suffix: " << delete_snapshot_path_suffix_
|
||||
<< ",\n"
|
||||
<< indent(indent_level + 1) << "next_segment_id: " << next_segment_id_
|
||||
<< "\n"
|
||||
<< indent(indent_level + 1) << "enable_mmap: " << enable_mmap_ << "\n"
|
||||
<< indent(indent_level) << "}";
|
||||
return oss.str();
|
||||
}
|
||||
|
||||
Result<VersionManager::Ptr> VersionManager::Recovery(const std::string &path) {
|
||||
namespace fs = std::filesystem;
|
||||
if (!fs::exists(path)) {
|
||||
LOG_ERROR("VersionManager::Recovery: path %s does not exist", path.c_str());
|
||||
return tl::make_unexpected(
|
||||
Status::NotFound("path ", path, " does not exist"));
|
||||
}
|
||||
if (!fs::is_directory(path)) {
|
||||
LOG_ERROR("VersionManager::Recovery: path %s is not a directory",
|
||||
path.c_str());
|
||||
return tl::make_unexpected(
|
||||
Status::InvalidArgument("path", path, " is not a directory"));
|
||||
}
|
||||
|
||||
std::string prefix = GetFileName(FileID::MANIFEST_FILE);
|
||||
std::string manifest_pattern = "^" + prefix + R"(\.(\d+)$)";
|
||||
std::regex regex(manifest_pattern);
|
||||
std::smatch match;
|
||||
|
||||
uint64_t max_id = UINT64_MAX;
|
||||
std::string version_path;
|
||||
|
||||
for (const auto &entry : fs::directory_iterator(path)) {
|
||||
if (entry.is_regular_file()) {
|
||||
std::string filename = entry.path().filename().string();
|
||||
if (std::regex_match(filename, match, regex)) {
|
||||
uint64_t id = std::stoull(match[1].str());
|
||||
if (id > max_id || max_id == UINT64_MAX) {
|
||||
max_id = id;
|
||||
version_path = entry.path().string();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (max_id == UINT64_MAX) {
|
||||
LOG_ERROR("Failed to find the version file in collction_path(%s)",
|
||||
path.c_str());
|
||||
return tl::make_unexpected(
|
||||
Status::NotFound("Failed to find the version file"));
|
||||
}
|
||||
|
||||
Version version;
|
||||
auto s = Version::Load(version_path, &version);
|
||||
CHECK_RETURN_STATUS_EXPECTED(s);
|
||||
|
||||
VersionManager::Ptr manager =
|
||||
VersionManager::Ptr(new VersionManager(path, version, max_id + 1));
|
||||
|
||||
return manager;
|
||||
}
|
||||
|
||||
Result<VersionManager::Ptr> VersionManager::Create(
|
||||
const std::string &path, const Version &initial_version) {
|
||||
VersionManager::Ptr manager =
|
||||
VersionManager::Ptr(new VersionManager(path, initial_version));
|
||||
return manager;
|
||||
}
|
||||
|
||||
VersionManager::VersionManager(const std::string &path,
|
||||
const Version &initial_version,
|
||||
uint64_t version_id)
|
||||
: path_(path), current_version_(initial_version), version_id_(version_id) {}
|
||||
|
||||
Version VersionManager::get_current_version() {
|
||||
std::lock_guard lock(mtx_);
|
||||
return current_version_;
|
||||
}
|
||||
|
||||
Status VersionManager::apply(const Version &version) {
|
||||
std::lock_guard lock(mtx_);
|
||||
current_version_ = version;
|
||||
return Status::OK();
|
||||
}
|
||||
|
||||
Status VersionManager::reset_writing_segment_meta(SegmentMeta::Ptr meta) {
|
||||
std::lock_guard lock(mtx_);
|
||||
current_version_.reset_writing_segment_meta(meta);
|
||||
return Status::OK();
|
||||
}
|
||||
|
||||
Status VersionManager::add_persisted_segment_meta(SegmentMeta::Ptr meta) {
|
||||
std::lock_guard lock(mtx_);
|
||||
return current_version_.add_persisted_segment_meta(meta);
|
||||
}
|
||||
|
||||
Status VersionManager::remove_persisted_segment_meta(SegmentID id) {
|
||||
std::lock_guard lock(mtx_);
|
||||
return current_version_.remove_persisted_segment_meta(id);
|
||||
}
|
||||
|
||||
Status VersionManager::flush() {
|
||||
std::lock_guard lock(mtx_);
|
||||
|
||||
std::string current_path;
|
||||
if (version_id_ != 0) {
|
||||
current_path =
|
||||
FileHelper::MakeFilePath(path_, FileID::MANIFEST_FILE, version_id_ - 1);
|
||||
}
|
||||
|
||||
auto s = Version::Save(
|
||||
FileHelper::MakeFilePath(path_, FileID::MANIFEST_FILE, version_id_++),
|
||||
current_version_);
|
||||
CHECK_RETURN_STATUS(s);
|
||||
|
||||
if (!current_path.empty()) {
|
||||
FileHelper::RemoveFile(current_path);
|
||||
}
|
||||
|
||||
return Status::OK();
|
||||
}
|
||||
|
||||
|
||||
} // namespace zvec
|
||||
@@ -0,0 +1,240 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
#pragma once
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstdint>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
#include "db/common/status.h"
|
||||
#include "db/index/common/meta.h"
|
||||
#include "db/index/common/schema.h"
|
||||
|
||||
namespace zvec {
|
||||
|
||||
class Version {
|
||||
public:
|
||||
using Ptr = std::shared_ptr<Version>;
|
||||
|
||||
Version() = default;
|
||||
|
||||
static Status Load(const std::string &path, Version *version);
|
||||
|
||||
static Status Save(const std::string &path, const Version &version);
|
||||
|
||||
public:
|
||||
void set_schema(const CollectionSchema &schema) {
|
||||
schema_ = std::make_shared<CollectionSchema>(schema);
|
||||
}
|
||||
|
||||
const CollectionSchema &schema() const {
|
||||
return *schema_;
|
||||
}
|
||||
|
||||
void set_enable_mmap(bool enable_mmap) {
|
||||
enable_mmap_ = enable_mmap;
|
||||
}
|
||||
|
||||
bool enable_mmap() const {
|
||||
return enable_mmap_;
|
||||
}
|
||||
|
||||
Status add_persisted_segment_meta(const SegmentMeta::Ptr &meta) {
|
||||
if (meta == nullptr) {
|
||||
return Status::InvalidArgument("Segment meta is null");
|
||||
}
|
||||
auto iter = persisted_segment_metas_map_.find(meta->id());
|
||||
if (iter != persisted_segment_metas_map_.end()) {
|
||||
return Status::InvalidArgument("Segment meta already exists");
|
||||
}
|
||||
persisted_segment_metas_map_[meta->id()] = meta;
|
||||
return Status::OK();
|
||||
}
|
||||
|
||||
Status remove_persisted_segment_meta(SegmentID segment_id) {
|
||||
auto iter = persisted_segment_metas_map_.find(segment_id);
|
||||
if (iter == persisted_segment_metas_map_.end()) {
|
||||
return Status::NotFound("Segment meta not found");
|
||||
}
|
||||
persisted_segment_metas_map_.erase(segment_id);
|
||||
return Status::OK();
|
||||
}
|
||||
|
||||
Status update_persisted_segment_meta(SegmentMeta::Ptr meta) {
|
||||
if (meta == nullptr) {
|
||||
return Status::InvalidArgument("Segment meta is null");
|
||||
}
|
||||
auto iter = persisted_segment_metas_map_.find(meta->id());
|
||||
if (iter == persisted_segment_metas_map_.end()) {
|
||||
return Status::NotFound("Segment meta not found");
|
||||
}
|
||||
persisted_segment_metas_map_[meta->id()] =
|
||||
std::make_shared<SegmentMeta>(*meta);
|
||||
return Status::OK();
|
||||
}
|
||||
|
||||
void set_persisted_segment_metas(const std::vector<SegmentMeta::Ptr> &metas) {
|
||||
for (auto &meta : metas) {
|
||||
persisted_segment_metas_map_[meta->id()] = meta;
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<SegmentMeta::Ptr> persisted_segment_metas() const {
|
||||
std::vector<SegmentMeta::Ptr> segment_metas;
|
||||
segment_metas.reserve(persisted_segment_metas_map_.size());
|
||||
for (auto &segment_meta : persisted_segment_metas_map_) {
|
||||
segment_metas.push_back(segment_meta.second);
|
||||
}
|
||||
|
||||
std::sort(segment_metas.begin(), segment_metas.end(),
|
||||
[](const SegmentMeta::Ptr &lhs, const SegmentMeta::Ptr &rhs) {
|
||||
return lhs->min_doc_id() < rhs->min_doc_id();
|
||||
});
|
||||
|
||||
return segment_metas;
|
||||
}
|
||||
|
||||
void reset_writing_segment_meta(SegmentMeta::Ptr segment_meta) {
|
||||
writing_segment_meta_ = segment_meta;
|
||||
}
|
||||
|
||||
SegmentMeta::Ptr writing_segment_meta() const {
|
||||
return writing_segment_meta_;
|
||||
}
|
||||
|
||||
void set_id_map_path_suffix(uint32_t suffix) {
|
||||
id_map_path_suffix_ = suffix;
|
||||
}
|
||||
|
||||
uint32_t id_map_path_suffix() const {
|
||||
return id_map_path_suffix_;
|
||||
}
|
||||
|
||||
void set_delete_snapshot_path_suffix(uint32_t suffix) {
|
||||
delete_snapshot_path_suffix_ = suffix;
|
||||
}
|
||||
|
||||
uint32_t delete_snapshot_path_suffix() const {
|
||||
return delete_snapshot_path_suffix_;
|
||||
}
|
||||
|
||||
void set_next_segment_id(SegmentID id) {
|
||||
next_segment_id_ = id;
|
||||
}
|
||||
|
||||
SegmentID next_segment_id() const {
|
||||
return next_segment_id_;
|
||||
}
|
||||
|
||||
public:
|
||||
bool operator==(const Version &other) const {
|
||||
if (*schema_ != *other.schema_ ||
|
||||
persisted_segment_metas_map_.size() !=
|
||||
other.persisted_segment_metas_map_.size()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
for (const auto &item : persisted_segment_metas_map_) {
|
||||
auto it = other.persisted_segment_metas_map_.find(item.first);
|
||||
if (it == other.persisted_segment_metas_map_.end() ||
|
||||
*item.second != *it->second) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
std::string to_string() const;
|
||||
|
||||
std::string to_string_formatted(int indent_level = 0) const;
|
||||
|
||||
private:
|
||||
CollectionSchema::Ptr schema_;
|
||||
bool enable_mmap_;
|
||||
|
||||
std::unordered_map<SegmentID, SegmentMeta::Ptr> persisted_segment_metas_map_;
|
||||
|
||||
SegmentMeta::Ptr writing_segment_meta_;
|
||||
|
||||
uint32_t id_map_path_suffix_{0};
|
||||
uint32_t delete_snapshot_path_suffix_{0};
|
||||
|
||||
SegmentID next_segment_id_{0};
|
||||
};
|
||||
|
||||
// Wrapper of Current Version
|
||||
class VersionManager {
|
||||
public:
|
||||
using Ptr = std::shared_ptr<VersionManager>;
|
||||
|
||||
static Result<VersionManager::Ptr> Recovery(const std::string &path);
|
||||
|
||||
static Result<VersionManager::Ptr> Create(const std::string &path,
|
||||
const Version &initial_version);
|
||||
|
||||
private:
|
||||
VersionManager(const std::string &path, const Version &initial_version,
|
||||
uint64_t version_id = 0);
|
||||
|
||||
public:
|
||||
Version get_current_version();
|
||||
|
||||
// overwrite the current version
|
||||
Status apply(const Version &version);
|
||||
|
||||
Status reset_writing_segment_meta(SegmentMeta::Ptr meta);
|
||||
|
||||
Status add_persisted_segment_meta(SegmentMeta::Ptr meta);
|
||||
|
||||
Status remove_persisted_segment_meta(SegmentID id);
|
||||
|
||||
Status flush();
|
||||
|
||||
void set_id_map_path_suffix(uint32_t suffix) {
|
||||
std::lock_guard lock(mtx_);
|
||||
current_version_.set_id_map_path_suffix(suffix);
|
||||
}
|
||||
|
||||
void set_delete_snapshot_path_suffix(uint32_t suffix) {
|
||||
std::lock_guard lock(mtx_);
|
||||
current_version_.set_delete_snapshot_path_suffix(suffix);
|
||||
}
|
||||
|
||||
uint32_t delete_snapshot_path_suffix() const {
|
||||
std::lock_guard lock(mtx_);
|
||||
return current_version_.delete_snapshot_path_suffix();
|
||||
}
|
||||
|
||||
void set_next_segment_id(SegmentID id) {
|
||||
std::lock_guard lock(mtx_);
|
||||
current_version_.set_next_segment_id(id);
|
||||
}
|
||||
|
||||
void set_enable_mmap(bool enable_mmap) {
|
||||
std::lock_guard lock(mtx_);
|
||||
current_version_.set_enable_mmap(enable_mmap);
|
||||
}
|
||||
|
||||
private:
|
||||
const std::string path_;
|
||||
Version current_version_;
|
||||
mutable std::mutex mtx_;
|
||||
|
||||
uint64_t version_id_ = 0;
|
||||
};
|
||||
|
||||
} // namespace zvec
|
||||
@@ -0,0 +1,133 @@
|
||||
// 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 "column_merging_reader.h"
|
||||
#include <iostream>
|
||||
#include <arrow/array.h>
|
||||
#include <arrow/result.h>
|
||||
#include <arrow/status.h>
|
||||
#include <arrow/table.h>
|
||||
#include "db/index/storage/store_helper.h"
|
||||
|
||||
namespace zvec {
|
||||
|
||||
std::shared_ptr<ColumnMergingReader> ColumnMergingReader::Make(
|
||||
const std::shared_ptr<arrow::Schema> &target_schema,
|
||||
std::vector<std::shared_ptr<arrow::ipc::RecordBatchReader>>
|
||||
&&input_readers) {
|
||||
return std::make_shared<ColumnMergingReader>(target_schema,
|
||||
std::move(input_readers));
|
||||
}
|
||||
|
||||
ColumnMergingReader::ColumnMergingReader(
|
||||
const std::shared_ptr<arrow::Schema> &target_schema,
|
||||
std::vector<std::shared_ptr<arrow::ipc::RecordBatchReader>> &&input_readers)
|
||||
: target_schema_(target_schema), input_readers_(std::move(input_readers)) {
|
||||
current_batches_.resize(input_readers_.size());
|
||||
std::fill(current_batches_.begin(), current_batches_.end(), nullptr);
|
||||
}
|
||||
|
||||
std::shared_ptr<arrow::Schema> ColumnMergingReader::schema() const {
|
||||
return target_schema_;
|
||||
}
|
||||
|
||||
arrow::Status ColumnMergingReader::ReadNext(
|
||||
std::shared_ptr<arrow::RecordBatch> *out) {
|
||||
*out = nullptr;
|
||||
|
||||
if (!has_more_) {
|
||||
return arrow::Status::OK();
|
||||
}
|
||||
|
||||
// Read next batch from each input reader
|
||||
for (size_t i = 0; i < input_readers_.size(); ++i) {
|
||||
arrow::Status status = input_readers_[i]->ReadNext(¤t_batches_[i]);
|
||||
if (!status.ok()) {
|
||||
return status;
|
||||
}
|
||||
}
|
||||
|
||||
// Check if all readers have reached EOF
|
||||
bool all_null = true;
|
||||
for (const auto &batch : current_batches_) {
|
||||
if (batch != nullptr) {
|
||||
all_null = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// All readers reached EOF
|
||||
if (all_null) {
|
||||
has_more_ = false;
|
||||
return arrow::Status::OK();
|
||||
}
|
||||
|
||||
// Verify that all non-null batches have consistent row counts
|
||||
int64_t expected_rows = -1;
|
||||
for (const auto &batch : current_batches_) {
|
||||
if (batch) {
|
||||
if (expected_rows == -1) {
|
||||
expected_rows = batch->num_rows();
|
||||
} else if (expected_rows != batch->num_rows()) {
|
||||
return arrow::Status::Invalid(
|
||||
"Input readers have inconsistent row counts");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (expected_rows <= 0) {
|
||||
has_more_ = false;
|
||||
return arrow::Status::OK();
|
||||
}
|
||||
|
||||
// Build each column
|
||||
std::vector<std::shared_ptr<arrow::Array>> columns;
|
||||
columns.reserve(target_schema_->num_fields());
|
||||
|
||||
for (int i = 0; i < target_schema_->num_fields(); ++i) {
|
||||
auto field = target_schema_->field(i);
|
||||
std::shared_ptr<arrow::Array> col_array = nullptr;
|
||||
|
||||
// Try to find this column from any batch
|
||||
for (const auto &batch : current_batches_) {
|
||||
if (!batch) continue;
|
||||
int col_idx = batch->schema()->GetFieldIndex(field->name());
|
||||
if (col_idx != -1) {
|
||||
col_array = batch->column(col_idx);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!col_array) {
|
||||
return arrow::Status::Invalid(
|
||||
"Failed to find column in any input reader: ", field->name());
|
||||
}
|
||||
|
||||
columns.push_back(std::move(col_array));
|
||||
}
|
||||
|
||||
// Construct final batch
|
||||
*out = arrow::RecordBatch::Make(target_schema_, expected_rows,
|
||||
std::move(columns));
|
||||
if (!*out) {
|
||||
return arrow::Status::Invalid("Failed to create merged record batch");
|
||||
}
|
||||
|
||||
// Clear current batches, prepare for next read
|
||||
std::fill(current_batches_.begin(), current_batches_.end(), nullptr);
|
||||
|
||||
return arrow::Status::OK();
|
||||
}
|
||||
|
||||
} // namespace zvec
|
||||
@@ -0,0 +1,50 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <memory>
|
||||
#include <vector>
|
||||
#include <arrow/api.h>
|
||||
#include <arrow/ipc/reader.h>
|
||||
|
||||
namespace zvec {
|
||||
|
||||
class ColumnMergingReader : public arrow::RecordBatchReader {
|
||||
public:
|
||||
static std::shared_ptr<ColumnMergingReader> Make(
|
||||
const std::shared_ptr<arrow::Schema> &target_schema,
|
||||
std::vector<std::shared_ptr<arrow::ipc::RecordBatchReader>>
|
||||
&&input_readers);
|
||||
|
||||
explicit ColumnMergingReader(
|
||||
const std::shared_ptr<arrow::Schema> &target_schema,
|
||||
std::vector<std::shared_ptr<arrow::ipc::RecordBatchReader>>
|
||||
&&input_readers);
|
||||
|
||||
~ColumnMergingReader() override = default; // LCOV_EXCL_LINE
|
||||
|
||||
std::shared_ptr<arrow::Schema> schema() const override;
|
||||
|
||||
arrow::Status ReadNext(std::shared_ptr<arrow::RecordBatch> *out) override;
|
||||
|
||||
private:
|
||||
std::shared_ptr<arrow::Schema> target_schema_;
|
||||
std::vector<std::shared_ptr<arrow::ipc::RecordBatchReader>> input_readers_;
|
||||
|
||||
std::vector<std::shared_ptr<arrow::RecordBatch>> current_batches_;
|
||||
bool has_more_ = true;
|
||||
};
|
||||
|
||||
} // namespace zvec
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,183 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
#include <ailego/pattern/expected.hpp>
|
||||
#include <arrow/record_batch.h>
|
||||
#include "db/common/status.h"
|
||||
#include "db/index/column/inverted_column/inverted_column_indexer.h"
|
||||
#include "db/index/column/inverted_column/inverted_indexer.h"
|
||||
#include "db/index/column/vector_column/combined_vector_column_indexer.h"
|
||||
#include "db/index/column/vector_column/vector_column_indexer.h"
|
||||
#include "db/index/common/delete_store.h"
|
||||
#include "db/index/common/doc.h"
|
||||
#include "db/index/common/id_map.h"
|
||||
#include "db/index/common/index_params.h"
|
||||
#include "db/index/common/meta.h"
|
||||
#include "db/index/common/options.h"
|
||||
#include "db/index/common/schema.h"
|
||||
#include "db/index/common/version_manager.h"
|
||||
#include "db/index/storage/base_forward_store.h"
|
||||
|
||||
namespace zvec {
|
||||
|
||||
class CombinedRecordBatchReader;
|
||||
|
||||
class Segment {
|
||||
public:
|
||||
using Ptr = std::shared_ptr<Segment>;
|
||||
|
||||
static Result<Ptr> CreateAndOpen(const std::string &path,
|
||||
const CollectionSchema &schema,
|
||||
SegmentID segment_id, uint64_t min_doc_id,
|
||||
const IDMap::Ptr &id_map,
|
||||
const DeleteStore::Ptr &delete_store,
|
||||
const VersionManager::Ptr &version_manager,
|
||||
const SegmentOptions &options);
|
||||
|
||||
static Result<Ptr> Open(const std::string &path,
|
||||
const CollectionSchema &schema,
|
||||
const SegmentMeta &segment_meta,
|
||||
const IDMap::Ptr &id_map,
|
||||
const DeleteStore::Ptr &delete_store,
|
||||
const VersionManager::Ptr &version_manager,
|
||||
const SegmentOptions &options);
|
||||
|
||||
virtual SegmentID id() const = 0;
|
||||
|
||||
virtual SegmentMeta::Ptr meta() const = 0;
|
||||
|
||||
virtual uint64_t doc_count(const IndexFilter::Ptr filter = nullptr) = 0;
|
||||
|
||||
// for collection
|
||||
virtual Status add_column(const std::string &column_name,
|
||||
FieldSchema::Ptr column_schema,
|
||||
const std::string &expression,
|
||||
const AddColumnOptions &options) = 0;
|
||||
|
||||
virtual Status alter_column(const std::string &column_name,
|
||||
const FieldSchema::Ptr &new_column_schema,
|
||||
const AlterColumnOptions &options) = 0;
|
||||
|
||||
virtual Status drop_column(const std::string &column_name) = 0;
|
||||
|
||||
virtual Status create_all_vector_index(
|
||||
int concurrency, SegmentMeta::Ptr *new_segmnet_meta,
|
||||
std::unordered_map<std::string, VectorColumnIndexer::Ptr>
|
||||
*vector_indexers,
|
||||
std::unordered_map<std::string, VectorColumnIndexer::Ptr>
|
||||
*quant_vector_indexers) = 0;
|
||||
|
||||
// defined in segment.h cause it needs to access block_id generator
|
||||
virtual Status create_vector_index(
|
||||
const std::string &column, const IndexParams::Ptr &index_params,
|
||||
int concurrency, SegmentMeta::Ptr *new_segmnet_meta,
|
||||
std::unordered_map<std::string, VectorColumnIndexer::Ptr>
|
||||
*vector_indexers,
|
||||
std::unordered_map<std::string, VectorColumnIndexer::Ptr>
|
||||
*quant_vector_indexers) = 0;
|
||||
|
||||
virtual Status drop_vector_index(
|
||||
const std::string &column, SegmentMeta::Ptr *new_segmnet_meta,
|
||||
std::unordered_map<std::string, VectorColumnIndexer::Ptr>
|
||||
*vector_indexers) = 0;
|
||||
|
||||
virtual Status reload_vector_index(
|
||||
const CollectionSchema &schema, const SegmentMeta::Ptr &segment_meta,
|
||||
const std::unordered_map<std::string, VectorColumnIndexer::Ptr>
|
||||
&vector_indexers,
|
||||
const std::unordered_map<std::string, VectorColumnIndexer::Ptr>
|
||||
&quant_vector_indexers = {}) = 0;
|
||||
|
||||
virtual bool vector_index_ready(
|
||||
const std::string &column,
|
||||
const IndexParams::Ptr &index_params) const = 0;
|
||||
|
||||
virtual bool all_vector_index_ready() const = 0;
|
||||
|
||||
// defined in segment.h cause it needs to access block_id generator
|
||||
virtual Status create_scalar_index(
|
||||
const std::vector<std::string> &columns,
|
||||
const IndexParams::Ptr &index_params, SegmentMeta::Ptr *new_segment_meta,
|
||||
InvertedIndexer::Ptr *new_scalar_indexer) = 0;
|
||||
|
||||
// defined in segment.h cause it needs to access block_id generator
|
||||
virtual Status drop_scalar_index(
|
||||
const std::vector<std::string> &columns,
|
||||
SegmentMeta::Ptr *new_segment_meta,
|
||||
InvertedIndexer::Ptr *new_scalar_indexer) = 0;
|
||||
|
||||
virtual Status reload_scalar_index(
|
||||
const CollectionSchema &schema, const SegmentMeta::Ptr &segment_meta,
|
||||
const InvertedIndexer::Ptr &scalar_indexer) = 0;
|
||||
|
||||
virtual Status Insert(Doc &doc) = 0;
|
||||
|
||||
virtual Status Upsert(Doc &doc) = 0;
|
||||
|
||||
virtual Status Update(Doc &doc) = 0;
|
||||
|
||||
virtual Status Delete(const std::string &pk) = 0;
|
||||
|
||||
virtual Status Delete(uint64_t doc_id) = 0;
|
||||
|
||||
virtual Doc::Ptr Fetch(uint64_t doc_id) = 0;
|
||||
|
||||
// for sqlengine
|
||||
virtual TablePtr fetch(const std::vector<std::string> &columns,
|
||||
const std::vector<int> &indices) const = 0;
|
||||
|
||||
virtual ExecBatchPtr fetch(const std::vector<std::string> &columns,
|
||||
int index) const = 0;
|
||||
|
||||
// caller should hold segment shared_ptr for segment handle the indexer's
|
||||
// lifetime
|
||||
virtual RecordBatchReaderPtr scan(
|
||||
const std::vector<std::string> &columns) const = 0;
|
||||
|
||||
// caller hold segment shared_ptr for segment handle the indexer's lifetime
|
||||
virtual CombinedVectorColumnIndexer::Ptr get_combined_vector_indexer(
|
||||
const std::string &field_name) const = 0;
|
||||
|
||||
// caller hold segment shared_ptr for segment handle the indexer's lifetime
|
||||
virtual CombinedVectorColumnIndexer::Ptr get_quant_combined_vector_indexer(
|
||||
const std::string &field_name) const = 0;
|
||||
|
||||
// caller hold segment shared_ptr for segment handle the indexer's lifetime
|
||||
virtual std::vector<VectorColumnIndexer::Ptr> get_vector_indexer(
|
||||
const std::string &field_name) const = 0;
|
||||
|
||||
virtual std::vector<VectorColumnIndexer::Ptr> get_quant_vector_indexer(
|
||||
const std::string &field_name) const = 0;
|
||||
|
||||
// caller hold segment shared_ptr for segment handle the indexer's lifetime
|
||||
virtual InvertedColumnIndexer::Ptr get_scalar_indexer(
|
||||
const std::string &field_name) const = 0;
|
||||
|
||||
virtual const IndexFilter::Ptr get_filter() = 0;
|
||||
|
||||
// for others
|
||||
virtual Status flush() = 0;
|
||||
virtual Status dump() = 0;
|
||||
|
||||
// only mark need_destroyed
|
||||
virtual Status destroy() = 0;
|
||||
};
|
||||
|
||||
} // namespace zvec
|
||||
@@ -0,0 +1,830 @@
|
||||
// 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 "segment_helper.h"
|
||||
#include <cstdint>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <arrow/compute/api_vector.h>
|
||||
#include <arrow/type_fwd.h>
|
||||
#include "ailego/logger/logger.h"
|
||||
#include "column/inverted_column/inverted_indexer.h"
|
||||
#include "column/vector_column/vector_column_indexer.h"
|
||||
#include "common/meta.h"
|
||||
#include "db/common/constants.h"
|
||||
#include "db/common/file_helper.h"
|
||||
#include "db/common/global_resource.h"
|
||||
#include "db/common/status.h"
|
||||
#include "db/common/typedef.h"
|
||||
#include "db/index/common/index_filter.h"
|
||||
#include "db/index/common/type.h"
|
||||
#include "db/index/storage/forward_writer.h"
|
||||
#include "roaring.hh"
|
||||
|
||||
namespace zvec {
|
||||
|
||||
Status SegmentHelper::Execute(SegmentTask::Ptr &task) {
|
||||
auto &task_info = task->task_info();
|
||||
Status s;
|
||||
if (std::holds_alternative<CompactTask>(task_info)) {
|
||||
auto &compact_task = std::get<CompactTask>(task_info);
|
||||
s = ExecuteCompactTask(compact_task);
|
||||
} else if (std::holds_alternative<CreateVectorIndexTask>(task_info)) {
|
||||
auto &create_index_task = std::get<CreateVectorIndexTask>(task_info);
|
||||
s = ExecuteCreateVectorIndexTask(create_index_task);
|
||||
} else if (std::holds_alternative<CreateScalarIndexTask>(task_info)) {
|
||||
auto &create_index_task = std::get<CreateScalarIndexTask>(task_info);
|
||||
s = ExecuteCreateScalarIndexTask(create_index_task);
|
||||
} else if (std::holds_alternative<DropVectorIndexTask>(task_info)) {
|
||||
auto &drop_index_task = std::get<DropVectorIndexTask>(task_info);
|
||||
s = ExecuteDropVectorIndexTask(drop_index_task);
|
||||
} else if (std::holds_alternative<DropScalarIndexTask>(task_info)) {
|
||||
auto &drop_index_task = std::get<DropScalarIndexTask>(task_info);
|
||||
s = ExecuteDropScalarIndexTask(drop_index_task);
|
||||
} else {
|
||||
return Status::InvalidArgument("Unknown task type");
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
class RowIdFilter : public IndexFilter {
|
||||
public:
|
||||
explicit RowIdFilter(roaring::Roaring &&delete_row_id_bitmap)
|
||||
: delete_row_id_bitmap_(delete_row_id_bitmap) {}
|
||||
|
||||
bool is_filtered(uint64_t id) const override {
|
||||
return delete_row_id_bitmap_.contains(id);
|
||||
}
|
||||
|
||||
private:
|
||||
roaring::Roaring delete_row_id_bitmap_;
|
||||
};
|
||||
|
||||
Status SegmentHelper::ExecuteCompactTask(CompactTask &task) {
|
||||
// input
|
||||
auto collection_path = task.collection_path_;
|
||||
auto schema = task.schema_;
|
||||
auto input_segments = task.input_segments_;
|
||||
auto filter = task.filter_;
|
||||
auto output_segment_id = task.output_segment_id_;
|
||||
|
||||
auto columns = schema->forward_field_names();
|
||||
|
||||
// make segment path
|
||||
auto output_segment_path =
|
||||
FileHelper::MakeTempSegmentPath(collection_path, output_segment_id);
|
||||
if (!FileHelper::CreateDirectory(output_segment_path)) {
|
||||
LOG_ERROR("Create directory failed: %s", output_segment_path.c_str());
|
||||
return Status::InternalError("Create directory failed: %s",
|
||||
output_segment_path.c_str());
|
||||
}
|
||||
|
||||
std::function<BlockID()> block_id_generator =
|
||||
[block_id = BlockID{0}]() mutable { return block_id++; };
|
||||
|
||||
// iterate every doc, build forward and invert indexer
|
||||
roaring::Roaring delete_row_id_bitmap;
|
||||
uint64_t min_doc_id{std::numeric_limits<uint64_t>::max()};
|
||||
uint64_t max_doc_id{0};
|
||||
uint32_t doc_count{0};
|
||||
std::vector<BlockMeta> block_metas;
|
||||
Status s = ReduceScalar(schema, input_segments, output_segment_path, columns,
|
||||
filter, task.forward_use_parquet_, block_id_generator,
|
||||
&delete_row_id_bitmap, &block_metas, &min_doc_id,
|
||||
&max_doc_id, &doc_count);
|
||||
CHECK_RETURN_STATUS(s);
|
||||
|
||||
if (doc_count == 0) {
|
||||
FileHelper::RemoveDirectory(output_segment_path);
|
||||
return Status::OK();
|
||||
}
|
||||
|
||||
std::shared_ptr<RowIdFilter> row_id_filter =
|
||||
std::make_shared<RowIdFilter>(std::move(delete_row_id_bitmap));
|
||||
|
||||
s = ReduceVectorIndex(schema, input_segments, output_segment_path,
|
||||
row_id_filter, block_id_generator, min_doc_id,
|
||||
max_doc_id, doc_count, task.concurrency_, &block_metas);
|
||||
CHECK_RETURN_STATUS(s);
|
||||
|
||||
LOG_INFO("Compacted vector index");
|
||||
|
||||
auto new_segment_meta = std::make_shared<SegmentMeta>();
|
||||
new_segment_meta->set_id(task.output_segment_id_);
|
||||
new_segment_meta->set_persisted_blocks(block_metas);
|
||||
std::set<std::string> indexed_vector_fields;
|
||||
for (auto &field : schema->vector_fields()) {
|
||||
indexed_vector_fields.emplace(field->name());
|
||||
}
|
||||
new_segment_meta->set_indexed_vector_fields(indexed_vector_fields);
|
||||
task.output_segment_meta_ = new_segment_meta;
|
||||
|
||||
return Status::OK();
|
||||
}
|
||||
|
||||
Status SegmentHelper::ReduceScalar(
|
||||
const CollectionSchema::Ptr schema,
|
||||
const std::vector<Segment::Ptr> &input_segments,
|
||||
const std::string &output_segment_path,
|
||||
const std::vector<std::string> &columns, const IndexFilter::Ptr &filter,
|
||||
bool forward_use_parquet, std::function<BlockID()> &block_id_generator,
|
||||
roaring::Roaring *delete_row_id_bitmap,
|
||||
std::vector<BlockMeta> *output_block_metas, uint64_t *min_doc_id,
|
||||
uint64_t *max_doc_id, uint32_t *doc_count) {
|
||||
// forward
|
||||
auto forward_block_id = block_id_generator();
|
||||
auto forward_path = FileHelper::MakeForwardBlockPath(
|
||||
output_segment_path, forward_block_id, forward_use_parquet);
|
||||
|
||||
std::shared_ptr<ForwardWriter> forward_writer;
|
||||
if (forward_use_parquet) {
|
||||
forward_writer = ForwardWriter::CreateParquetWriter(forward_path);
|
||||
} else {
|
||||
forward_writer = ForwardWriter::CreateArrowIPCWriter(forward_path);
|
||||
}
|
||||
|
||||
// invert index
|
||||
auto all_fields = schema->fields();
|
||||
std::vector<FieldSchema> invert_fields;
|
||||
std::vector<std::string> invert_field_names;
|
||||
for (auto &field : all_fields) {
|
||||
if (!field->is_vector_field()) {
|
||||
if (field->index_params() &&
|
||||
field->index_params()->type() == IndexType::INVERT) {
|
||||
invert_fields.push_back(*field);
|
||||
invert_field_names.push_back(field->name());
|
||||
}
|
||||
}
|
||||
}
|
||||
InvertedIndexer::Ptr invert_indexer;
|
||||
BlockID invert_block_id{0};
|
||||
if (invert_fields.size() > 0) {
|
||||
invert_block_id = block_id_generator();
|
||||
auto invert_path =
|
||||
FileHelper::MakeInvertIndexPath(output_segment_path, invert_block_id);
|
||||
invert_indexer = InvertedIndexer::CreateAndOpen(schema->name(), invert_path,
|
||||
true, invert_fields, false);
|
||||
if (invert_indexer == nullptr) {
|
||||
return Status::InternalError("Open invert indexer failed");
|
||||
}
|
||||
}
|
||||
|
||||
uint32_t row_id_offset{0U};
|
||||
*doc_count = 0;
|
||||
|
||||
std::vector<std::string> all_reduce_columns{GLOBAL_DOC_ID, USER_ID};
|
||||
for (auto &column : columns) {
|
||||
all_reduce_columns.push_back(column);
|
||||
}
|
||||
|
||||
for (auto &segment : input_segments) {
|
||||
auto reader = segment->scan(all_reduce_columns);
|
||||
if (reader == nullptr) {
|
||||
return Status::InternalError("scan segment failed");
|
||||
}
|
||||
|
||||
while (true) {
|
||||
auto batch = reader->Next();
|
||||
if (!batch.ok()) {
|
||||
return Status::InternalError("reader next failed: ",
|
||||
batch.status().message());
|
||||
}
|
||||
|
||||
auto batch_value = batch.ValueOrDie();
|
||||
|
||||
if (!batch_value) {
|
||||
break;
|
||||
}
|
||||
|
||||
if (batch_value->num_rows() == 0) continue;
|
||||
|
||||
std::shared_ptr<arrow::RecordBatch> filtered_batch;
|
||||
auto as =
|
||||
FilterRecordBatch(batch_value, filter, row_id_offset, &filtered_batch,
|
||||
delete_row_id_bitmap, min_doc_id, max_doc_id);
|
||||
if (!as.ok()) {
|
||||
return Status::InternalError("filter record batch failed: ",
|
||||
as.message());
|
||||
}
|
||||
|
||||
row_id_offset += batch_value->num_rows();
|
||||
|
||||
if (!filtered_batch || filtered_batch->num_rows() == 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// forward
|
||||
as = forward_writer->insert_batch(filtered_batch);
|
||||
if (!as.ok()) {
|
||||
return Status::InternalError("writer insert failed: ", as.message());
|
||||
}
|
||||
|
||||
// invert index
|
||||
if (invert_indexer) {
|
||||
auto s = ReduceScalarIndex(invert_indexer, filtered_batch, *doc_count);
|
||||
CHECK_RETURN_STATUS(s);
|
||||
}
|
||||
|
||||
*doc_count += filtered_batch->num_rows();
|
||||
}
|
||||
}
|
||||
|
||||
if (*doc_count == 0) {
|
||||
// no docs
|
||||
return Status::OK();
|
||||
}
|
||||
|
||||
// flush forward
|
||||
auto as = forward_writer->finalize();
|
||||
if (!as.ok()) {
|
||||
return Status::InternalError("writer finalize failed: ", as.message());
|
||||
}
|
||||
|
||||
BlockMeta forward_meta;
|
||||
forward_meta.set_id(forward_block_id);
|
||||
forward_meta.set_type(BlockType::SCALAR);
|
||||
forward_meta.set_min_doc_id(*min_doc_id);
|
||||
forward_meta.set_max_doc_id(*max_doc_id);
|
||||
forward_meta.set_doc_count(*doc_count);
|
||||
forward_meta.set_columns(all_reduce_columns);
|
||||
|
||||
output_block_metas->push_back(forward_meta);
|
||||
|
||||
if (invert_indexer) {
|
||||
auto s = invert_indexer->flush();
|
||||
CHECK_RETURN_STATUS(s);
|
||||
|
||||
s = invert_indexer->seal();
|
||||
CHECK_RETURN_STATUS(s);
|
||||
|
||||
BlockMeta meta;
|
||||
meta.set_id(invert_block_id);
|
||||
meta.set_type(BlockType::SCALAR_INDEX);
|
||||
|
||||
output_block_metas->push_back(meta);
|
||||
}
|
||||
|
||||
LOG_INFO("Compacted scalar and scalar index");
|
||||
|
||||
return Status::OK();
|
||||
}
|
||||
|
||||
Status SegmentHelper::ReduceScalarIndex(
|
||||
InvertedIndexer::Ptr invert_indexer,
|
||||
const std::shared_ptr<arrow::RecordBatch> &batch, uint32_t doc_id_offset) {
|
||||
auto a_schema = batch->schema();
|
||||
int num_columns = batch->num_columns();
|
||||
|
||||
for (int i = 0; i < num_columns; ++i) {
|
||||
auto field = a_schema->field(i);
|
||||
auto column_name = field->name();
|
||||
|
||||
auto indexer = (*invert_indexer)[column_name];
|
||||
if (!indexer) {
|
||||
continue;
|
||||
}
|
||||
|
||||
auto array = batch->column(i);
|
||||
auto type_id = field->type()->id();
|
||||
|
||||
Status s;
|
||||
|
||||
switch (type_id) {
|
||||
case arrow::Type::BOOL: {
|
||||
auto typed_array = std::static_pointer_cast<arrow::BooleanArray>(array);
|
||||
for (int64_t j = 0; j < typed_array->length(); ++j) {
|
||||
if (!typed_array->IsNull(j)) {
|
||||
bool value = typed_array->Value(j);
|
||||
s = indexer->insert(j + doc_id_offset, value);
|
||||
CHECK_RETURN_STATUS(s);
|
||||
} else {
|
||||
s = indexer->insert_null(j + doc_id_offset);
|
||||
CHECK_RETURN_STATUS(s);
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
case arrow::Type::INT32: {
|
||||
auto typed_array = std::static_pointer_cast<arrow::Int32Array>(array);
|
||||
for (int64_t j = 0; j < typed_array->length(); ++j) {
|
||||
if (!typed_array->IsNull(j)) {
|
||||
int32_t value = typed_array->Value(j);
|
||||
std::string value_str(reinterpret_cast<const char *>(&value),
|
||||
sizeof(value));
|
||||
s = indexer->insert(j + doc_id_offset, value_str);
|
||||
CHECK_RETURN_STATUS(s);
|
||||
} else {
|
||||
s = indexer->insert_null(j + doc_id_offset);
|
||||
CHECK_RETURN_STATUS(s);
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
case arrow::Type::INT64: {
|
||||
auto typed_array = std::static_pointer_cast<arrow::Int64Array>(array);
|
||||
for (int64_t j = 0; j < typed_array->length(); ++j) {
|
||||
if (!typed_array->IsNull(j)) {
|
||||
int64_t value = typed_array->Value(j);
|
||||
std::string value_str(reinterpret_cast<const char *>(&value),
|
||||
sizeof(value));
|
||||
s = indexer->insert(j + doc_id_offset, value_str);
|
||||
CHECK_RETURN_STATUS(s);
|
||||
} else {
|
||||
s = indexer->insert_null(j + doc_id_offset);
|
||||
CHECK_RETURN_STATUS(s);
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
case arrow::Type::UINT32: {
|
||||
auto typed_array = std::static_pointer_cast<arrow::UInt32Array>(array);
|
||||
for (int64_t j = 0; j < typed_array->length(); ++j) {
|
||||
if (!typed_array->IsNull(j)) {
|
||||
uint32_t value = typed_array->Value(j);
|
||||
std::string value_str(reinterpret_cast<const char *>(&value),
|
||||
sizeof(value));
|
||||
s = indexer->insert(j + doc_id_offset, value_str);
|
||||
CHECK_RETURN_STATUS(s);
|
||||
} else {
|
||||
s = indexer->insert_null(j + doc_id_offset);
|
||||
CHECK_RETURN_STATUS(s);
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
case arrow::Type::UINT64: {
|
||||
auto typed_array = std::static_pointer_cast<arrow::UInt64Array>(array);
|
||||
for (int64_t j = 0; j < typed_array->length(); ++j) {
|
||||
if (!typed_array->IsNull(j)) {
|
||||
uint64_t value = typed_array->Value(j);
|
||||
std::string value_str(reinterpret_cast<const char *>(&value),
|
||||
sizeof(value));
|
||||
s = indexer->insert(j + doc_id_offset, value_str);
|
||||
CHECK_RETURN_STATUS(s);
|
||||
} else {
|
||||
s = indexer->insert_null(j + doc_id_offset);
|
||||
CHECK_RETURN_STATUS(s);
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
case arrow::Type::FLOAT: {
|
||||
auto typed_array = std::static_pointer_cast<arrow::FloatArray>(array);
|
||||
for (int64_t j = 0; j < typed_array->length(); ++j) {
|
||||
if (!typed_array->IsNull(j)) {
|
||||
float value = typed_array->Value(j);
|
||||
std::string value_str(reinterpret_cast<const char *>(&value),
|
||||
sizeof(value));
|
||||
s = indexer->insert(j + doc_id_offset, value_str);
|
||||
CHECK_RETURN_STATUS(s);
|
||||
} else {
|
||||
s = indexer->insert_null(j + doc_id_offset);
|
||||
CHECK_RETURN_STATUS(s);
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
case arrow::Type::DOUBLE: {
|
||||
auto typed_array = std::static_pointer_cast<arrow::DoubleArray>(array);
|
||||
for (int64_t j = 0; j < typed_array->length(); ++j) {
|
||||
if (!typed_array->IsNull(j)) {
|
||||
double value = typed_array->Value(j);
|
||||
std::string value_str(reinterpret_cast<const char *>(&value),
|
||||
sizeof(value));
|
||||
s = indexer->insert(j + doc_id_offset, value_str);
|
||||
CHECK_RETURN_STATUS(s);
|
||||
} else {
|
||||
s = indexer->insert_null(j + doc_id_offset);
|
||||
CHECK_RETURN_STATUS(s);
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
case arrow::Type::STRING: {
|
||||
auto typed_array = std::static_pointer_cast<arrow::StringArray>(array);
|
||||
for (int64_t j = 0; j < typed_array->length(); ++j) {
|
||||
if (!typed_array->IsNull(j)) {
|
||||
std::string value_str = typed_array->GetString(j);
|
||||
s = indexer->insert(j + doc_id_offset, value_str);
|
||||
CHECK_RETURN_STATUS(s);
|
||||
} else {
|
||||
s = indexer->insert_null(j + doc_id_offset);
|
||||
CHECK_RETURN_STATUS(s);
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
case arrow::Type::LIST: {
|
||||
auto list_array = std::static_pointer_cast<arrow::ListArray>(array);
|
||||
auto value_array = list_array->values();
|
||||
auto value_type_id = value_array->type()->id();
|
||||
|
||||
auto offset_array = list_array->offsets();
|
||||
auto typed_offsets =
|
||||
std::static_pointer_cast<arrow::Int32Array>(offset_array);
|
||||
|
||||
for (int64_t j = 0; j < list_array->length(); ++j) {
|
||||
if (list_array->IsNull(j)) {
|
||||
s = (*invert_indexer)[column_name]->insert_null(j + doc_id_offset);
|
||||
CHECK_RETURN_STATUS(s);
|
||||
continue;
|
||||
}
|
||||
|
||||
int32_t start_offset = typed_offsets->Value(j);
|
||||
int32_t end_offset = typed_offsets->Value(j + 1);
|
||||
|
||||
switch (value_type_id) {
|
||||
case arrow::Type::BOOL: {
|
||||
std::vector<bool> values;
|
||||
auto typed =
|
||||
std::static_pointer_cast<arrow::BooleanArray>(value_array);
|
||||
for (int32_t k = start_offset; k < end_offset; ++k) {
|
||||
if (typed->IsValid(k)) {
|
||||
values.push_back(typed->Value(k));
|
||||
}
|
||||
}
|
||||
s = (*invert_indexer)[column_name]->insert(j + doc_id_offset,
|
||||
values);
|
||||
CHECK_RETURN_STATUS(s);
|
||||
break;
|
||||
}
|
||||
case arrow::Type::INT32: {
|
||||
std::vector<std::string> values;
|
||||
auto typed =
|
||||
std::static_pointer_cast<arrow::Int32Array>(value_array);
|
||||
for (int32_t k = start_offset; k < end_offset; ++k) {
|
||||
if (typed->IsValid(k)) {
|
||||
int32_t value = typed->Value(k);
|
||||
std::string value_str(reinterpret_cast<const char *>(&value),
|
||||
sizeof(value));
|
||||
values.push_back(value_str);
|
||||
}
|
||||
}
|
||||
s = (*invert_indexer)[column_name]->insert(j + doc_id_offset,
|
||||
values);
|
||||
CHECK_RETURN_STATUS(s);
|
||||
break;
|
||||
}
|
||||
case arrow::Type::INT64: {
|
||||
std::vector<std::string> values;
|
||||
auto typed =
|
||||
std::static_pointer_cast<arrow::Int64Array>(value_array);
|
||||
for (int32_t k = start_offset; k < end_offset; ++k) {
|
||||
if (typed->IsValid(k)) {
|
||||
int64_t value = typed->Value(k);
|
||||
std::string value_str(reinterpret_cast<const char *>(&value),
|
||||
sizeof(value));
|
||||
values.push_back(value_str);
|
||||
}
|
||||
}
|
||||
s = (*invert_indexer)[column_name]->insert(j + doc_id_offset,
|
||||
values);
|
||||
CHECK_RETURN_STATUS(s);
|
||||
break;
|
||||
}
|
||||
case arrow::Type::UINT32: {
|
||||
std::vector<std::string> values;
|
||||
auto typed =
|
||||
std::static_pointer_cast<arrow::UInt32Array>(value_array);
|
||||
for (int32_t k = start_offset; k < end_offset; ++k) {
|
||||
if (typed->IsValid(k)) {
|
||||
uint32_t value = typed->Value(k);
|
||||
std::string value_str(reinterpret_cast<const char *>(&value),
|
||||
sizeof(value));
|
||||
values.push_back(value_str);
|
||||
}
|
||||
}
|
||||
s = (*invert_indexer)[column_name]->insert(j + doc_id_offset,
|
||||
values);
|
||||
CHECK_RETURN_STATUS(s);
|
||||
break;
|
||||
}
|
||||
case arrow::Type::UINT64: {
|
||||
std::vector<std::string> values;
|
||||
auto typed =
|
||||
std::static_pointer_cast<arrow::UInt64Array>(value_array);
|
||||
for (int32_t k = start_offset; k < end_offset; ++k) {
|
||||
if (typed->IsValid(k)) {
|
||||
uint64_t value = typed->Value(k);
|
||||
std::string value_str(reinterpret_cast<const char *>(&value),
|
||||
sizeof(value));
|
||||
values.push_back(value_str);
|
||||
}
|
||||
}
|
||||
s = (*invert_indexer)[column_name]->insert(j + doc_id_offset,
|
||||
values);
|
||||
CHECK_RETURN_STATUS(s);
|
||||
break;
|
||||
}
|
||||
case arrow::Type::FLOAT: {
|
||||
std::vector<std::string> values;
|
||||
auto typed =
|
||||
std::static_pointer_cast<arrow::FloatArray>(value_array);
|
||||
for (int32_t k = start_offset; k < end_offset; ++k) {
|
||||
if (typed->IsValid(k)) {
|
||||
float value = typed->Value(k);
|
||||
std::string value_str(reinterpret_cast<const char *>(&value),
|
||||
sizeof(value));
|
||||
values.push_back(value_str);
|
||||
}
|
||||
}
|
||||
s = (*invert_indexer)[column_name]->insert(j + doc_id_offset,
|
||||
values);
|
||||
CHECK_RETURN_STATUS(s);
|
||||
break;
|
||||
}
|
||||
case arrow::Type::DOUBLE: {
|
||||
std::vector<std::string> values;
|
||||
auto typed =
|
||||
std::static_pointer_cast<arrow::DoubleArray>(value_array);
|
||||
for (int32_t k = start_offset; k < end_offset; ++k) {
|
||||
if (typed->IsValid(k)) {
|
||||
double value = typed->Value(k);
|
||||
std::string value_str(reinterpret_cast<const char *>(&value),
|
||||
sizeof(value));
|
||||
values.push_back(value_str);
|
||||
}
|
||||
}
|
||||
s = (*invert_indexer)[column_name]->insert(j + doc_id_offset,
|
||||
values);
|
||||
CHECK_RETURN_STATUS(s);
|
||||
break;
|
||||
}
|
||||
case arrow::Type::STRING: {
|
||||
std::vector<std::string> values;
|
||||
auto typed =
|
||||
std::static_pointer_cast<arrow::StringArray>(value_array);
|
||||
for (int32_t k = start_offset; k < end_offset; ++k) {
|
||||
if (typed->IsValid(k)) {
|
||||
values.push_back(typed->GetString(k));
|
||||
}
|
||||
}
|
||||
s = (*invert_indexer)[column_name]->insert(j + doc_id_offset,
|
||||
values);
|
||||
CHECK_RETURN_STATUS(s);
|
||||
break;
|
||||
}
|
||||
default:
|
||||
LOG_WARN(
|
||||
"Warning: Unsupported nested type '%s' in List column '%s'",
|
||||
value_array->type()->ToString().c_str(), column_name.c_str());
|
||||
continue;
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
default:
|
||||
LOG_WARN("Warning: Unsupported column type '%s' for column '%s'",
|
||||
field->type()->ToString().c_str(), column_name.c_str());
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
return Status::OK();
|
||||
}
|
||||
|
||||
Status SegmentHelper::ReduceVectorIndex(
|
||||
const CollectionSchema::Ptr schema,
|
||||
const std::vector<Segment::Ptr> &input_segments,
|
||||
const std::string &output_segment_path, const IndexFilter::Ptr &filter,
|
||||
std::function<BlockID()> &block_id_generator, uint64_t min_doc_id,
|
||||
uint64_t max_doc_id, uint32_t doc_count, int concurrency,
|
||||
std::vector<BlockMeta> *output_block_metas) {
|
||||
Status s;
|
||||
|
||||
// vector
|
||||
auto vector_fields = schema->vector_fields();
|
||||
for (auto &field : vector_fields) {
|
||||
auto vector_index_params =
|
||||
std::dynamic_pointer_cast<VectorIndexParams>(field->index_params());
|
||||
|
||||
auto vector_block_id = block_id_generator();
|
||||
if (vector_index_params->quantize_type() == QuantizeType::UNDEFINED) {
|
||||
auto vector_index_path = FileHelper::MakeVectorIndexPath(
|
||||
output_segment_path, field->name(), vector_block_id);
|
||||
|
||||
// only create original vector indexer
|
||||
auto vector_indexer =
|
||||
std::make_shared<VectorColumnIndexer>(vector_index_path, *field);
|
||||
s = vector_indexer->Open({true, true});
|
||||
CHECK_RETURN_STATUS(s);
|
||||
|
||||
std::vector<VectorColumnIndexer::Ptr> merge_indexers;
|
||||
for (auto &input_segment : input_segments) {
|
||||
// merge_indexers should be ordered put
|
||||
auto to_merge_indexers =
|
||||
input_segment->get_vector_indexer(field->name());
|
||||
merge_indexers.insert(merge_indexers.end(), to_merge_indexers.begin(),
|
||||
to_merge_indexers.end());
|
||||
}
|
||||
|
||||
vector_column_params::MergeOptions merge_options;
|
||||
if (concurrency == 0) {
|
||||
merge_options.pool = GlobalResource::Instance().optimize_thread_pool();
|
||||
} else {
|
||||
merge_options.write_concurrency = concurrency;
|
||||
}
|
||||
|
||||
s = vector_indexer->Merge(merge_indexers, filter, merge_options);
|
||||
CHECK_RETURN_STATUS(s);
|
||||
|
||||
s = vector_indexer->Flush();
|
||||
CHECK_RETURN_STATUS(s);
|
||||
|
||||
BlockMeta new_block_meta;
|
||||
new_block_meta.set_id(vector_block_id);
|
||||
new_block_meta.set_type(BlockType::VECTOR_INDEX);
|
||||
new_block_meta.set_columns({field->name()});
|
||||
new_block_meta.set_min_doc_id(min_doc_id);
|
||||
new_block_meta.set_max_doc_id(max_doc_id);
|
||||
new_block_meta.set_doc_count(doc_count);
|
||||
|
||||
output_block_metas->push_back(new_block_meta);
|
||||
} else {
|
||||
auto vector_index_path = FileHelper::MakeQuantizeVectorIndexPath(
|
||||
output_segment_path, field->name(), vector_block_id);
|
||||
|
||||
auto field_without_quantize = std::make_shared<FieldSchema>(*field);
|
||||
field_without_quantize->set_index_params(
|
||||
MakeDefaultVectorIndexParams(vector_index_params->metric_type()));
|
||||
|
||||
// create flat index
|
||||
auto vector_indexer = std::make_shared<VectorColumnIndexer>(
|
||||
vector_index_path, *field_without_quantize);
|
||||
s = vector_indexer->Open({true, true});
|
||||
CHECK_RETURN_STATUS(s);
|
||||
|
||||
std::vector<VectorColumnIndexer::Ptr> merge_indexers;
|
||||
for (auto &input_segment : input_segments) {
|
||||
// merge_indexers should be ordered put
|
||||
auto to_merge_indexers =
|
||||
input_segment->get_vector_indexer(field->name());
|
||||
merge_indexers.insert(merge_indexers.end(), to_merge_indexers.begin(),
|
||||
to_merge_indexers.end());
|
||||
}
|
||||
|
||||
vector_column_params::MergeOptions merge_options;
|
||||
if (concurrency == 0) {
|
||||
merge_options.pool = GlobalResource::Instance().optimize_thread_pool();
|
||||
} else {
|
||||
merge_options.write_concurrency = concurrency;
|
||||
}
|
||||
|
||||
s = vector_indexer->Merge(merge_indexers, filter, merge_options);
|
||||
CHECK_RETURN_STATUS(s);
|
||||
|
||||
s = vector_indexer->Flush();
|
||||
CHECK_RETURN_STATUS(s);
|
||||
|
||||
BlockMeta new_block_meta;
|
||||
new_block_meta.set_id(vector_block_id);
|
||||
new_block_meta.set_type(BlockType::VECTOR_INDEX);
|
||||
new_block_meta.set_columns({field->name()});
|
||||
output_block_metas->push_back(new_block_meta);
|
||||
|
||||
// create quantize index
|
||||
auto vector_quan_block_id = block_id_generator();
|
||||
|
||||
auto vector_quan_index_path = FileHelper::MakeQuantizeVectorIndexPath(
|
||||
output_segment_path, field->name(), vector_quan_block_id);
|
||||
|
||||
auto vector_indexer_quantize =
|
||||
std::make_shared<VectorColumnIndexer>(vector_quan_index_path, *field);
|
||||
s = vector_indexer_quantize->Open({true, true});
|
||||
CHECK_RETURN_STATUS(s);
|
||||
|
||||
merge_indexers.clear();
|
||||
for (auto &input_segment : input_segments) {
|
||||
// merge_indexers should be ordered put
|
||||
auto to_merge_indexers =
|
||||
input_segment->get_quant_vector_indexer(field->name());
|
||||
merge_indexers.insert(merge_indexers.end(), to_merge_indexers.begin(),
|
||||
to_merge_indexers.end());
|
||||
}
|
||||
|
||||
s = vector_indexer_quantize->Merge(merge_indexers, filter, merge_options);
|
||||
CHECK_RETURN_STATUS(s);
|
||||
|
||||
s = vector_indexer_quantize->Flush();
|
||||
CHECK_RETURN_STATUS(s);
|
||||
|
||||
new_block_meta.set_id(vector_quan_block_id);
|
||||
new_block_meta.set_type(BlockType::VECTOR_INDEX_QUANTIZE);
|
||||
new_block_meta.set_columns({field->name()});
|
||||
output_block_metas->push_back(new_block_meta);
|
||||
}
|
||||
}
|
||||
|
||||
return Status::OK();
|
||||
}
|
||||
|
||||
arrow::Status SegmentHelper::FilterRecordBatch(
|
||||
const std::shared_ptr<arrow::RecordBatch> &batch,
|
||||
const IndexFilter::Ptr filter, uint32_t row_id_offset,
|
||||
std::shared_ptr<arrow::RecordBatch> *filterd,
|
||||
roaring::Roaring *delete_row_id_bitmap, uint64_t *min_doc_id,
|
||||
uint64_t *max_doc_id) {
|
||||
if (!filter) {
|
||||
*filterd = batch;
|
||||
for (int64_t i = 0; i < batch->num_rows(); ++i) {
|
||||
// column 0 is doc_id
|
||||
auto result = batch->column(0)->GetScalar(i);
|
||||
if (!result.ok()) {
|
||||
return result.status();
|
||||
}
|
||||
uint64_t doc_id =
|
||||
std::dynamic_pointer_cast<arrow::UInt64Scalar>(*result)->value;
|
||||
*min_doc_id = std::min(*min_doc_id, doc_id);
|
||||
*max_doc_id = std::max(*max_doc_id, doc_id);
|
||||
}
|
||||
return arrow::Status::OK();
|
||||
}
|
||||
|
||||
std::vector<uint64_t> selected_indices;
|
||||
for (int64_t i = 0; i < batch->num_rows(); ++i) {
|
||||
auto result = batch->column(0)->GetScalar(i);
|
||||
if (!result.ok()) {
|
||||
return result.status();
|
||||
}
|
||||
uint64_t doc_id =
|
||||
std::dynamic_pointer_cast<arrow::UInt64Scalar>(*result)->value;
|
||||
if (!filter->is_filtered(doc_id)) {
|
||||
selected_indices.push_back(i);
|
||||
*min_doc_id = std::min(*min_doc_id, doc_id);
|
||||
*max_doc_id = std::max(*max_doc_id, doc_id);
|
||||
} else {
|
||||
delete_row_id_bitmap->add(i + row_id_offset);
|
||||
}
|
||||
}
|
||||
|
||||
if (selected_indices.empty()) {
|
||||
return arrow::Status::OK();
|
||||
}
|
||||
|
||||
arrow::UInt64Builder builder;
|
||||
ARROW_RETURN_NOT_OK(builder.AppendValues(selected_indices));
|
||||
std::shared_ptr<arrow::Array> selection_array;
|
||||
ARROW_RETURN_NOT_OK(builder.Finish(&selection_array));
|
||||
|
||||
std::vector<std::shared_ptr<arrow::Array>> filtered_columns;
|
||||
for (int i = 0; i < batch->num_columns(); ++i) {
|
||||
arrow::Datum out;
|
||||
ARROW_ASSIGN_OR_RAISE(
|
||||
out, arrow::compute::Take(batch->column(i), selection_array));
|
||||
filtered_columns.push_back(out.make_array());
|
||||
}
|
||||
|
||||
auto filtered_batch = arrow::RecordBatch::Make(
|
||||
batch->schema(), static_cast<int64_t>(selected_indices.size()),
|
||||
filtered_columns);
|
||||
|
||||
*filterd = filtered_batch;
|
||||
|
||||
return arrow::Status::OK();
|
||||
}
|
||||
|
||||
Status SegmentHelper::ExecuteCreateVectorIndexTask(
|
||||
CreateVectorIndexTask &task) {
|
||||
if (task.column_to_build_vector_index_ == "") {
|
||||
return task.input_segment_->create_all_vector_index(
|
||||
task.concurrency_, &task.output_segment_meta_,
|
||||
&task.output_vector_indexers_, &task.output_quant_vector_indexers_);
|
||||
} else {
|
||||
return task.input_segment_->create_vector_index(
|
||||
task.column_to_build_vector_index_, task.index_params_,
|
||||
task.concurrency_, &task.output_segment_meta_,
|
||||
&task.output_vector_indexers_, &task.output_quant_vector_indexers_);
|
||||
}
|
||||
}
|
||||
|
||||
Status SegmentHelper::ExecuteCreateScalarIndexTask(
|
||||
CreateScalarIndexTask &task) {
|
||||
return task.input_segment_->create_scalar_index(
|
||||
task.columns_to_build_scalar_index_, task.index_params_,
|
||||
&task.output_segment_meta_, &task.output_scalar_indexer_);
|
||||
}
|
||||
|
||||
Status SegmentHelper::ExecuteDropVectorIndexTask(DropVectorIndexTask &task) {
|
||||
return task.input_segment_->drop_vector_index(
|
||||
task.column_to_drop_vector_index_, &task.output_segment_meta_,
|
||||
&task.output_vector_indexers_);
|
||||
}
|
||||
|
||||
Status SegmentHelper::ExecuteDropScalarIndexTask(DropScalarIndexTask &task) {
|
||||
return task.input_segment_->drop_scalar_index(
|
||||
task.columns_to_drop_scalar_index_, &task.output_segment_meta_,
|
||||
&task.output_scalar_indexer_);
|
||||
}
|
||||
|
||||
} // namespace zvec
|
||||
@@ -0,0 +1,226 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
#pragma once
|
||||
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
#include <variant>
|
||||
#include <arrow/record_batch.h>
|
||||
#include <arrow/status.h>
|
||||
#include "db/index/column/inverted_column/inverted_indexer.h"
|
||||
#include "db/index/common/index_filter.h"
|
||||
#include "db/index/common/index_params.h"
|
||||
#include "db/index/common/meta.h"
|
||||
#include "segment.h"
|
||||
|
||||
namespace zvec {
|
||||
|
||||
struct CompactTask {
|
||||
CompactTask(const std::string &collection_path,
|
||||
const CollectionSchema::Ptr &schema,
|
||||
const std::vector<Segment::Ptr> &input_segments,
|
||||
SegmentID output_segment_id, const IndexFilter::Ptr filter,
|
||||
bool forward_use_parquet, int concurrency)
|
||||
: collection_path_(collection_path),
|
||||
schema_(schema),
|
||||
input_segments_(input_segments),
|
||||
output_segment_id_(output_segment_id),
|
||||
filter_(std::move(filter)),
|
||||
forward_use_parquet_(forward_use_parquet),
|
||||
concurrency_(concurrency) {}
|
||||
|
||||
const std::string collection_path_;
|
||||
const CollectionSchema::Ptr schema_;
|
||||
const std::vector<Segment::Ptr>
|
||||
input_segments_; // size must > 1 when filter is nullptr; size could = 1
|
||||
// when filter is not nullptr
|
||||
SegmentID output_segment_id_;
|
||||
const IndexFilter::Ptr filter_;
|
||||
bool forward_use_parquet_;
|
||||
int concurrency_;
|
||||
|
||||
// output
|
||||
SegmentMeta::Ptr output_segment_meta_;
|
||||
};
|
||||
|
||||
struct CreateVectorIndexTask {
|
||||
CreateVectorIndexTask(const Segment::Ptr &input_segment,
|
||||
const std::string &column_to_build_vector_index,
|
||||
const IndexParams::Ptr &index_params, int concurrency)
|
||||
: input_segment_(input_segment),
|
||||
column_to_build_vector_index_(column_to_build_vector_index),
|
||||
index_params_(index_params),
|
||||
concurrency_(concurrency) {}
|
||||
|
||||
Segment::Ptr input_segment_;
|
||||
std::string column_to_build_vector_index_; // if empty means create index for
|
||||
// all vector columns
|
||||
IndexParams::Ptr index_params_;
|
||||
int concurrency_;
|
||||
|
||||
// output
|
||||
SegmentMeta::Ptr output_segment_meta_;
|
||||
std::unordered_map<std::string, VectorColumnIndexer::Ptr>
|
||||
output_vector_indexers_;
|
||||
std::unordered_map<std::string, VectorColumnIndexer::Ptr>
|
||||
output_quant_vector_indexers_;
|
||||
};
|
||||
|
||||
struct DropVectorIndexTask {
|
||||
DropVectorIndexTask(const Segment::Ptr &input_segment,
|
||||
const std::string &column_to_drop_vector_index)
|
||||
: input_segment_(input_segment),
|
||||
column_to_drop_vector_index_(column_to_drop_vector_index) {}
|
||||
|
||||
Segment::Ptr input_segment_;
|
||||
std::string column_to_drop_vector_index_;
|
||||
|
||||
// output
|
||||
SegmentMeta::Ptr output_segment_meta_;
|
||||
std::unordered_map<std::string, VectorColumnIndexer::Ptr>
|
||||
output_vector_indexers_;
|
||||
};
|
||||
|
||||
struct CreateScalarIndexTask {
|
||||
CreateScalarIndexTask(
|
||||
const Segment::Ptr &input_segment,
|
||||
const std::vector<std::string> &columns_to_build_scalar_index,
|
||||
const IndexParams::Ptr &index_params, int concurrency)
|
||||
: input_segment_(input_segment),
|
||||
columns_to_build_scalar_index_(columns_to_build_scalar_index),
|
||||
index_params_(index_params),
|
||||
concurrency_(concurrency) {}
|
||||
|
||||
Segment::Ptr input_segment_;
|
||||
std::vector<std::string> columns_to_build_scalar_index_;
|
||||
IndexParams::Ptr index_params_;
|
||||
int concurrency_;
|
||||
|
||||
// output
|
||||
SegmentMeta::Ptr output_segment_meta_;
|
||||
InvertedIndexer::Ptr output_scalar_indexer_;
|
||||
};
|
||||
|
||||
struct DropScalarIndexTask {
|
||||
DropScalarIndexTask(Segment::Ptr input_segment,
|
||||
std::vector<std::string> columns_to_drop_scalar_index)
|
||||
: input_segment_(input_segment),
|
||||
columns_to_drop_scalar_index_(columns_to_drop_scalar_index) {}
|
||||
|
||||
Segment::Ptr input_segment_;
|
||||
std::vector<std::string> columns_to_drop_scalar_index_;
|
||||
|
||||
// output
|
||||
SegmentMeta::Ptr output_segment_meta_;
|
||||
InvertedIndexer::Ptr output_scalar_indexer_; // nullptr means no scalar index
|
||||
};
|
||||
|
||||
class SegmentTask {
|
||||
public:
|
||||
using Ptr = std::shared_ptr<SegmentTask>;
|
||||
|
||||
using TaskInfo =
|
||||
std::variant<CompactTask, CreateVectorIndexTask, DropVectorIndexTask,
|
||||
CreateScalarIndexTask, DropScalarIndexTask>;
|
||||
|
||||
static Ptr CreateComapctTask(const CompactTask &task) {
|
||||
return std::make_shared<SegmentTask>(task);
|
||||
}
|
||||
|
||||
static Ptr CreateCreateVectorIndexTask(const CreateVectorIndexTask &task) {
|
||||
return std::make_shared<SegmentTask>(task);
|
||||
}
|
||||
|
||||
static Ptr CreateDropVectorIndexTask(const DropVectorIndexTask &task) {
|
||||
return std::make_shared<SegmentTask>(task);
|
||||
}
|
||||
|
||||
static Ptr CreateCreateScalarIndexTask(const CreateScalarIndexTask &task) {
|
||||
return std::make_shared<SegmentTask>(task);
|
||||
}
|
||||
|
||||
static Ptr CreateDropScalarIndexTask(const DropScalarIndexTask &task) {
|
||||
return std::make_shared<SegmentTask>(task);
|
||||
}
|
||||
|
||||
public:
|
||||
SegmentTask(const CompactTask &task) : task_info_(task) {}
|
||||
|
||||
SegmentTask(const CreateVectorIndexTask &task) : task_info_(task) {}
|
||||
|
||||
SegmentTask(const CreateScalarIndexTask &task) : task_info_(task) {}
|
||||
|
||||
SegmentTask(const DropVectorIndexTask &task) : task_info_(task) {}
|
||||
|
||||
SegmentTask(const DropScalarIndexTask &task) : task_info_(task) {}
|
||||
|
||||
TaskInfo &task_info() {
|
||||
return task_info_;
|
||||
}
|
||||
|
||||
private:
|
||||
TaskInfo task_info_;
|
||||
};
|
||||
|
||||
class SegmentHelper {
|
||||
public:
|
||||
static Status Execute(SegmentTask::Ptr &task);
|
||||
|
||||
private:
|
||||
static Status ExecuteCompactTask(CompactTask &task);
|
||||
|
||||
static Status ExecuteCreateVectorIndexTask(CreateVectorIndexTask &task);
|
||||
|
||||
static Status ExecuteCreateScalarIndexTask(CreateScalarIndexTask &task);
|
||||
|
||||
static Status ExecuteDropVectorIndexTask(DropVectorIndexTask &task);
|
||||
|
||||
static Status ExecuteDropScalarIndexTask(DropScalarIndexTask &task);
|
||||
|
||||
public:
|
||||
static Status ReduceScalar(const CollectionSchema::Ptr schema,
|
||||
const std::vector<Segment::Ptr> &input_segments,
|
||||
const std::string &output_segment_path,
|
||||
const std::vector<std::string> &columns,
|
||||
const IndexFilter::Ptr &filter,
|
||||
bool forward_use_parquet,
|
||||
std::function<BlockID()> &block_id_generator,
|
||||
roaring::Roaring *delete_row_id_bitmap,
|
||||
std::vector<BlockMeta> *output_block_metas,
|
||||
uint64_t *min_doc_id, uint64_t *max_doc_id,
|
||||
uint32_t *doc_count);
|
||||
|
||||
static Status ReduceScalarIndex(
|
||||
InvertedIndexer::Ptr indexer,
|
||||
const std::shared_ptr<arrow::RecordBatch> &batch, uint32_t doc_id_offset);
|
||||
|
||||
static Status ReduceVectorIndex(
|
||||
const CollectionSchema::Ptr schema,
|
||||
const std::vector<Segment::Ptr> &input_segments,
|
||||
const std::string &output_segment_path, const IndexFilter::Ptr &filter,
|
||||
std::function<BlockID()> &block_id_generator, uint64_t min_doc_id,
|
||||
uint64_t max_doc_id, uint32_t doc_count, int concurrency,
|
||||
std::vector<BlockMeta> *output_block_metas);
|
||||
|
||||
static arrow::Status FilterRecordBatch(
|
||||
const std::shared_ptr<arrow::RecordBatch> &batch,
|
||||
const IndexFilter::Ptr filter, uint32_t row_id_offset,
|
||||
std::shared_ptr<arrow::RecordBatch> *filtered,
|
||||
roaring::Roaring *delete_row_id_bitmap, uint64_t *min_doc_id,
|
||||
uint64_t *max_doc_id);
|
||||
};
|
||||
|
||||
} // namespace zvec
|
||||
@@ -0,0 +1,160 @@
|
||||
// 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.
|
||||
|
||||
// segment_manager.cpp
|
||||
#include "db/index/segment/segment_manager.h"
|
||||
#include <algorithm>
|
||||
#include <future>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
#include "db/common/status.h"
|
||||
#include "db/common/typedef.h"
|
||||
|
||||
namespace zvec {
|
||||
|
||||
Status SegmentManager::add_segment(Segment::Ptr segment) {
|
||||
if (!segment) {
|
||||
return Status::InvalidArgument("Segment is null");
|
||||
}
|
||||
|
||||
segments_map_[segment->id()] = segment;
|
||||
return Status::OK();
|
||||
}
|
||||
|
||||
Status SegmentManager::remove_segment(SegmentID segment_id) {
|
||||
auto iter = segments_map_.find(segment_id);
|
||||
if (iter == segments_map_.end()) {
|
||||
return Status::NotFound("Segment not found");
|
||||
}
|
||||
|
||||
segments_map_.erase(segment_id);
|
||||
return Status::OK();
|
||||
}
|
||||
|
||||
Status SegmentManager::destroy_segment(SegmentID segment_id) {
|
||||
auto iter = segments_map_.find(segment_id);
|
||||
if (iter == segments_map_.end()) {
|
||||
return Status::NotFound("Segment not found");
|
||||
}
|
||||
|
||||
auto s = iter->second->destroy();
|
||||
CHECK_RETURN_STATUS(s);
|
||||
|
||||
segments_map_.erase(segment_id);
|
||||
return Status::OK();
|
||||
}
|
||||
|
||||
std::vector<Segment::Ptr> SegmentManager::get_segments() const {
|
||||
std::vector<Segment::Ptr> segments;
|
||||
for (auto &pair : segments_map_) {
|
||||
segments.push_back(pair.second);
|
||||
}
|
||||
std::sort(segments.begin(), segments.end(),
|
||||
[](Segment::Ptr a, Segment::Ptr b) {
|
||||
return a->meta()->min_doc_id() < b->meta()->min_doc_id();
|
||||
});
|
||||
return segments;
|
||||
}
|
||||
|
||||
std::vector<SegmentMeta::Ptr> SegmentManager::get_segments_meta() const {
|
||||
std::vector<SegmentMeta::Ptr> segments_meta;
|
||||
for (auto &pair : segments_map_) {
|
||||
segments_meta.push_back(pair.second->meta());
|
||||
}
|
||||
|
||||
std::sort(segments_meta.begin(), segments_meta.end(),
|
||||
[](SegmentMeta::Ptr a, SegmentMeta::Ptr b) {
|
||||
return a->min_doc_id() < b->min_doc_id();
|
||||
});
|
||||
|
||||
return segments_meta;
|
||||
}
|
||||
|
||||
Status SegmentManager::add_column(const std::string &column_name,
|
||||
const FieldSchema::Ptr &column_schema,
|
||||
const std::string &expression,
|
||||
int concurrency) {
|
||||
if (concurrency <= 0) {
|
||||
concurrency = static_cast<int>(std::thread::hardware_concurrency());
|
||||
}
|
||||
|
||||
std::vector<std::future<Status>> futures;
|
||||
std::vector<std::pair<SegmentID, Segment::Ptr>> segments(
|
||||
segments_map_.begin(), segments_map_.end());
|
||||
|
||||
for (size_t i = 0; i < segments.size(); i += concurrency) {
|
||||
size_t end = std::min(i + concurrency, segments.size());
|
||||
for (size_t j = i; j < end; ++j) {
|
||||
auto &segment = segments[j].second;
|
||||
futures.emplace_back(std::async(std::launch::async, [&]() -> Status {
|
||||
return segment->add_column(column_name, column_schema, expression,
|
||||
AddColumnOptions{concurrency});
|
||||
}));
|
||||
}
|
||||
|
||||
for (auto it = futures.begin(); it != futures.end(); ++it) {
|
||||
Status status = it->get();
|
||||
if (!status.ok()) {
|
||||
return status;
|
||||
}
|
||||
}
|
||||
futures.clear();
|
||||
}
|
||||
|
||||
return Status::OK();
|
||||
}
|
||||
|
||||
Status SegmentManager::alter_column(const std::string &column_name,
|
||||
const FieldSchema::Ptr &new_column_schema,
|
||||
int concurrency) {
|
||||
if (concurrency <= 0) {
|
||||
concurrency = static_cast<int>(std::thread::hardware_concurrency());
|
||||
}
|
||||
|
||||
std::vector<std::future<Status>> futures;
|
||||
std::vector<std::pair<SegmentID, Segment::Ptr>> segments(
|
||||
segments_map_.begin(), segments_map_.end());
|
||||
|
||||
for (size_t i = 0; i < segments.size(); i += concurrency) {
|
||||
size_t end = std::min(i + concurrency, segments.size());
|
||||
for (size_t j = i; j < end; ++j) {
|
||||
auto &segment = segments[j].second;
|
||||
futures.emplace_back(std::async(std::launch::async, [&]() -> Status {
|
||||
return segment->alter_column(column_name, new_column_schema,
|
||||
AlterColumnOptions{concurrency});
|
||||
}));
|
||||
}
|
||||
|
||||
for (auto it = futures.begin(); it != futures.end(); ++it) {
|
||||
Status status = it->get();
|
||||
if (!status.ok()) {
|
||||
return status;
|
||||
}
|
||||
}
|
||||
futures.clear();
|
||||
}
|
||||
|
||||
return Status::OK();
|
||||
}
|
||||
|
||||
Status SegmentManager::drop_column(const std::string &column_name) {
|
||||
for (auto &[segment_id, segment] : segments_map_) {
|
||||
auto s = segment->drop_column(column_name);
|
||||
CHECK_RETURN_STATUS(s);
|
||||
}
|
||||
|
||||
return Status::OK();
|
||||
}
|
||||
|
||||
} // namespace zvec
|
||||
@@ -0,0 +1,56 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
#pragma once
|
||||
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
#include "segment.h"
|
||||
|
||||
namespace zvec {
|
||||
class SegmentManager {
|
||||
public:
|
||||
using Ptr = std::shared_ptr<SegmentManager>;
|
||||
|
||||
SegmentManager() = default;
|
||||
~SegmentManager() = default;
|
||||
|
||||
public:
|
||||
uint32_t segment_count() const {
|
||||
return segments_map_.size();
|
||||
}
|
||||
|
||||
Status add_segment(Segment::Ptr segment);
|
||||
|
||||
Status remove_segment(SegmentID segment_id);
|
||||
|
||||
Status destroy_segment(SegmentID segment_id);
|
||||
|
||||
std::vector<Segment::Ptr> get_segments() const;
|
||||
|
||||
std::vector<SegmentMeta::Ptr> get_segments_meta() const;
|
||||
|
||||
Status add_column(const std::string &column_name,
|
||||
const FieldSchema::Ptr &column_schema,
|
||||
const std::string &expression, int concurrency);
|
||||
|
||||
Status alter_column(const std::string &column_name,
|
||||
const FieldSchema::Ptr &new_column_schema,
|
||||
int concurrency);
|
||||
|
||||
Status drop_column(const std::string &column_name);
|
||||
|
||||
private:
|
||||
std::unordered_map<SegmentID, Segment::Ptr> segments_map_;
|
||||
};
|
||||
} // namespace zvec
|
||||
@@ -0,0 +1,352 @@
|
||||
// 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 "sql_expr_parser.h"
|
||||
#include <cctype>
|
||||
#include <string>
|
||||
#include <arrow/result.h>
|
||||
#include <arrow/status.h>
|
||||
#include <arrow/type.h>
|
||||
|
||||
namespace zvec {
|
||||
|
||||
bool IsNumericType(const std::shared_ptr<arrow::DataType> &type) {
|
||||
return arrow::is_integer(type->id()) || arrow::is_floating(type->id());
|
||||
}
|
||||
|
||||
using arrow::compute::call;
|
||||
using arrow::compute::Expression;
|
||||
using arrow::compute::field_ref;
|
||||
using arrow::compute::literal;
|
||||
|
||||
class Parser {
|
||||
public:
|
||||
Parser(const std::string &expr, const std::shared_ptr<arrow::Schema> &schema)
|
||||
: expr_(expr), pos_(0), schema_(schema) {}
|
||||
|
||||
arrow::Result<Expression> Parse() {
|
||||
SkipWhitespace();
|
||||
ARROW_ASSIGN_OR_RAISE(auto e, ParseExpression());
|
||||
SkipWhitespace();
|
||||
if ((size_t)pos_ < expr_.size()) {
|
||||
return arrow::Status::Invalid("Unexpected character at position ", pos_,
|
||||
": ", expr_[pos_]);
|
||||
}
|
||||
return e;
|
||||
}
|
||||
|
||||
private:
|
||||
std::string expr_;
|
||||
int pos_;
|
||||
std::shared_ptr<arrow::Schema> schema_;
|
||||
|
||||
void SkipWhitespace() {
|
||||
while ((size_t)pos_ < expr_.size() && std::isspace(expr_[pos_])) {
|
||||
++pos_;
|
||||
}
|
||||
}
|
||||
|
||||
arrow::Result<Expression> ParseExpression() {
|
||||
SkipWhitespace();
|
||||
ARROW_ASSIGN_OR_RAISE(auto left, ParseTerm());
|
||||
SkipWhitespace();
|
||||
while ((size_t)pos_ < expr_.size() &&
|
||||
(expr_[pos_] == '+' || expr_[pos_] == '-')) {
|
||||
char op = expr_[pos_++];
|
||||
SkipWhitespace();
|
||||
ARROW_ASSIGN_OR_RAISE(auto right, ParseTerm());
|
||||
SkipWhitespace();
|
||||
auto func = (op == '+') ? "add" : "subtract";
|
||||
left = call(std::string(func), {left, right});
|
||||
}
|
||||
|
||||
return left;
|
||||
}
|
||||
|
||||
arrow::Result<Expression> ParseTerm() {
|
||||
SkipWhitespace();
|
||||
ARROW_ASSIGN_OR_RAISE(auto left, ParseFactor());
|
||||
SkipWhitespace();
|
||||
|
||||
while ((size_t)pos_ < expr_.size() &&
|
||||
(expr_[pos_] == '*' || expr_[pos_] == '/')) {
|
||||
char op = expr_[pos_++];
|
||||
SkipWhitespace();
|
||||
ARROW_ASSIGN_OR_RAISE(auto right, ParseFactor());
|
||||
SkipWhitespace();
|
||||
auto func = (op == '*') ? "multiply" : "divide";
|
||||
left = call(std::string(func), {left, right});
|
||||
}
|
||||
|
||||
return left;
|
||||
}
|
||||
|
||||
arrow::Result<Expression> ParseFactor() {
|
||||
SkipWhitespace();
|
||||
|
||||
if ((size_t)pos_ >= expr_.size()) {
|
||||
return arrow::Status::Invalid("Unexpected end of expression.");
|
||||
}
|
||||
|
||||
char c = expr_[pos_];
|
||||
|
||||
// Parenthetical expression
|
||||
if (c == '(') {
|
||||
++pos_;
|
||||
SkipWhitespace();
|
||||
ARROW_ASSIGN_OR_RAISE(auto inner, ParseExpression());
|
||||
SkipWhitespace();
|
||||
if ((size_t)pos_ >= expr_.size() || expr_[pos_] != ')') {
|
||||
return arrow::Status::Invalid("Mismatched parentheses.");
|
||||
}
|
||||
++pos_;
|
||||
SkipWhitespace();
|
||||
return inner;
|
||||
}
|
||||
|
||||
// Unary minus operator
|
||||
if (c == '-') {
|
||||
++pos_; // Skip the minus sign
|
||||
SkipWhitespace();
|
||||
ARROW_ASSIGN_OR_RAISE(auto operand, ParseFactor());
|
||||
return call("negate", {operand});
|
||||
}
|
||||
|
||||
// Unary plus operator (optional support)
|
||||
if (c == '+') {
|
||||
++pos_; // Skip the plus sign
|
||||
SkipWhitespace();
|
||||
return ParseFactor();
|
||||
}
|
||||
|
||||
// Numeric literal (integer or floating point)
|
||||
if (std::isdigit(c)) {
|
||||
return ParseNumber();
|
||||
}
|
||||
|
||||
// Column name (starts with letter or _)
|
||||
if (std::isalpha(c) || c == '_') {
|
||||
return ParseColumnName();
|
||||
}
|
||||
|
||||
return arrow::Status::Invalid("Unexpected character: '", std::string(1, c),
|
||||
"'");
|
||||
}
|
||||
|
||||
arrow::Result<Expression> ParseNumber() {
|
||||
int start = pos_;
|
||||
bool has_dot = false;
|
||||
bool has_exponent = false;
|
||||
|
||||
while ((size_t)pos_ < expr_.size()) {
|
||||
char c = expr_[pos_];
|
||||
if (std::isdigit(c)) {
|
||||
++pos_;
|
||||
} else if (c == '.' && !has_dot) {
|
||||
has_dot = true;
|
||||
++pos_;
|
||||
} else if ((c == 'e' || c == 'E') && !has_exponent) {
|
||||
has_exponent = true;
|
||||
++pos_;
|
||||
if ((size_t)pos_ < expr_.size() &&
|
||||
(expr_[pos_] == '+' || expr_[pos_] == '-')) {
|
||||
++pos_;
|
||||
}
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
std::string num_str = expr_.substr(start, pos_ - start);
|
||||
|
||||
if (!has_dot && !has_exponent) {
|
||||
try {
|
||||
int64_t value = std::stoll(num_str);
|
||||
return literal(value);
|
||||
} catch (...) {
|
||||
// fallback to double
|
||||
try {
|
||||
double value = std::stod(num_str);
|
||||
return literal(value);
|
||||
} catch (...) {
|
||||
return arrow::Status::Invalid("Invalid integer: ", num_str);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
try {
|
||||
double value = std::stod(num_str);
|
||||
return literal(value);
|
||||
} catch (...) {
|
||||
return arrow::Status::Invalid("Invalid float: ", num_str);
|
||||
}
|
||||
}
|
||||
return arrow::Status::Invalid("Failed to parse number: ", num_str);
|
||||
}
|
||||
|
||||
arrow::Result<Expression> ParseColumnName() {
|
||||
int start = pos_;
|
||||
while ((size_t)pos_ < expr_.size()) {
|
||||
char c = expr_[pos_];
|
||||
if (std::isalnum(c) || c == '_') {
|
||||
++pos_;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
std::string name = expr_.substr(start, pos_ - start);
|
||||
|
||||
auto field = schema_->GetFieldByName(name);
|
||||
if (!field) {
|
||||
return arrow::Status::Invalid("Column not found in schema: ", name);
|
||||
} else if (!IsNumericType(field->type())) {
|
||||
return arrow::Status::Invalid("Column is not numeric: ", name);
|
||||
}
|
||||
|
||||
return field_ref(name);
|
||||
}
|
||||
};
|
||||
|
||||
arrow::Result<Expression> CheckSupportedArithmeticExpression(
|
||||
const Expression &expr, const arrow::Schema &schema) {
|
||||
// Case 0: Literal, must be numeric type
|
||||
if (auto literal = expr.literal()) {
|
||||
auto type = literal->type();
|
||||
if (IsNumericType(type)) {
|
||||
return expr;
|
||||
} else {
|
||||
return arrow::Status::Invalid("Only numeric literals are allowed, got: ",
|
||||
literal->ToString());
|
||||
}
|
||||
}
|
||||
|
||||
// Case 1: Single column reference (e.g., col)
|
||||
if (auto field_ref = expr.field_ref()) {
|
||||
auto field = schema.GetFieldByName(*field_ref->name());
|
||||
if (!field) {
|
||||
return arrow::Status::Invalid("Field not found: ", *field_ref->name());
|
||||
}
|
||||
if (!IsNumericType(field->type())) {
|
||||
return arrow::Status::Invalid(
|
||||
"Only numeric columns are allowed, but got: ", field->ToString());
|
||||
}
|
||||
return expr; // Valid, return directly
|
||||
}
|
||||
|
||||
// Step 2: Handle function calls (unary, binary, etc.)
|
||||
if (auto call = expr.call()) {
|
||||
const auto &func_name = call->function_name;
|
||||
|
||||
// Case 2: Binary arithmetic operations (e.g., col + 1)
|
||||
if (func_name == "add" || func_name == "subtract" ||
|
||||
func_name == "multiply" || func_name == "divide") {
|
||||
if (call->arguments.size() != 2) {
|
||||
return arrow::Status::Invalid("Expected two arguments for '", func_name,
|
||||
"'");
|
||||
}
|
||||
|
||||
const auto &left = call->arguments[0];
|
||||
const auto &right = call->arguments[1];
|
||||
|
||||
// One must be field_ref, the other must be literal
|
||||
bool left_is_field = left.field_ref() != nullptr;
|
||||
bool right_is_literal = right.literal() != nullptr;
|
||||
|
||||
if (left_is_field && right_is_literal) {
|
||||
auto field = schema.GetFieldByName(*left.field_ref()->name());
|
||||
if (!field) {
|
||||
return arrow::Status::Invalid("Field not found: ",
|
||||
*left.field_ref()->name());
|
||||
}
|
||||
if (!IsNumericType(field->type())) {
|
||||
return arrow::Status::Invalid("Column is not numeric: ",
|
||||
field->ToString());
|
||||
}
|
||||
return expr;
|
||||
}
|
||||
|
||||
bool right_is_field = right.field_ref() != nullptr;
|
||||
bool left_is_literal = left.literal() != nullptr;
|
||||
|
||||
if (right_is_field && left_is_literal) {
|
||||
auto field = schema.GetFieldByName(*right.field_ref()->name());
|
||||
if (!field) {
|
||||
return arrow::Status::Invalid("Field not found: ",
|
||||
*right.field_ref()->name());
|
||||
}
|
||||
if (!IsNumericType(field->type())) {
|
||||
return arrow::Status::Invalid("Column is not numeric: ",
|
||||
field->ToString());
|
||||
}
|
||||
return expr;
|
||||
}
|
||||
|
||||
return arrow::Status::Invalid(
|
||||
"Only support binary operation between a column and a literal, got: ",
|
||||
expr.ToString());
|
||||
}
|
||||
|
||||
// Case 3: Unary operators (e.g., -col)
|
||||
if (func_name == "negate") {
|
||||
if (call->arguments.size() != 1) {
|
||||
return arrow::Status::Invalid("negate expects one argument");
|
||||
}
|
||||
const auto &arg = call->arguments[0];
|
||||
|
||||
// Check if argument is field_ref or literal
|
||||
if (auto field_ref = arg.field_ref()) {
|
||||
auto field = schema.GetFieldByName(*field_ref->name());
|
||||
if (!field) {
|
||||
return arrow::Status::Invalid("Field not found: ",
|
||||
*field_ref->name());
|
||||
}
|
||||
if (!IsNumericType(field->type())) {
|
||||
return arrow::Status::Invalid("Cannot negate non-numeric column: ",
|
||||
field->ToString());
|
||||
}
|
||||
return expr;
|
||||
} else if (auto literal = arg.literal()) {
|
||||
// Allow negation of literals
|
||||
if (IsNumericType(literal->type())) {
|
||||
return expr;
|
||||
} else {
|
||||
return arrow::Status::Invalid("Cannot negate non-numeric literal: ",
|
||||
literal->ToString());
|
||||
}
|
||||
} else {
|
||||
return arrow::Status::Invalid(
|
||||
"Only support negation of a column or numeric literal, got: ",
|
||||
arg.ToString());
|
||||
}
|
||||
}
|
||||
|
||||
// Unsupported functions
|
||||
return arrow::Status::Invalid("Unsupported function in expression: ",
|
||||
func_name);
|
||||
}
|
||||
|
||||
// Fallback error: unsupported expression form
|
||||
return arrow::Status::Invalid(
|
||||
"Only support: (1) single numeric column or literal, (2) column +/-/*/% "
|
||||
"literal, (3) -column. Got: ",
|
||||
expr.ToString());
|
||||
}
|
||||
|
||||
// Public interface function
|
||||
arrow::Result<Expression> ParseToExpression(
|
||||
const std::string &sql_expr, const std::shared_ptr<arrow::Schema> &schema) {
|
||||
Parser parser(sql_expr, schema);
|
||||
return parser.Parse();
|
||||
}
|
||||
|
||||
} // namespace zvec
|
||||
@@ -0,0 +1,30 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <arrow/compute/api.h>
|
||||
#include <arrow/status.h>
|
||||
|
||||
namespace zvec {
|
||||
|
||||
arrow::Result<arrow::compute::Expression> ParseToExpression(
|
||||
const std::string &sql_expr, const std::shared_ptr<arrow::Schema> &schema);
|
||||
|
||||
arrow::Result<arrow::compute::Expression> CheckSupportedArithmeticExpression(
|
||||
const arrow::compute::Expression &expr, const arrow::Schema &schema);
|
||||
|
||||
} // namespace zvec
|
||||
@@ -0,0 +1,196 @@
|
||||
// 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 "arrow_ipc_writer.h"
|
||||
#include <cstdint>
|
||||
#include <iostream>
|
||||
#include <arrow/compute/api_vector.h>
|
||||
|
||||
namespace zvec {
|
||||
|
||||
ArrowIpcWriter::ArrowIpcWriter(const std::string &filepath,
|
||||
int64_t max_rows_per_batch)
|
||||
: filepath_(filepath),
|
||||
max_rows_per_batch_(max_rows_per_batch),
|
||||
finalized_(false) {}
|
||||
|
||||
ArrowIpcWriter::~ArrowIpcWriter() {
|
||||
if (!finalized_ && writer_) {
|
||||
auto status = finalize();
|
||||
if (!status.ok()) {
|
||||
std::cerr << "Auto-finalize failed: " << status.ToString() << std::endl;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
arrow::Status ArrowIpcWriter::insert(
|
||||
std::shared_ptr<arrow::RecordBatchReader> reader,
|
||||
const IndexFilter::Ptr &filter) {
|
||||
if (!reader) {
|
||||
return arrow::Status::Invalid("RecordBatchReader is null");
|
||||
}
|
||||
|
||||
auto incoming_schema = reader->schema();
|
||||
if (!incoming_schema) {
|
||||
return arrow::Status::Invalid("Reader schema is null");
|
||||
}
|
||||
|
||||
if (!writer_) {
|
||||
schema_ = incoming_schema;
|
||||
|
||||
ARROW_ASSIGN_OR_RAISE(sink_, arrow::io::FileOutputStream::Open(filepath_));
|
||||
|
||||
auto writer = arrow::ipc::MakeFileWriter(sink_.get(), schema_);
|
||||
if (!writer.ok()) {
|
||||
return writer.status();
|
||||
}
|
||||
|
||||
writer_ = std::move(writer.ValueOrDie());
|
||||
|
||||
} else {
|
||||
if (!schema_->Equals(incoming_schema)) {
|
||||
return arrow::Status::Invalid("Schema mismatch in Insert()");
|
||||
}
|
||||
}
|
||||
|
||||
std::shared_ptr<arrow::RecordBatch> batch;
|
||||
while (true) {
|
||||
ARROW_ASSIGN_OR_RAISE(batch, reader->Next());
|
||||
if (!batch) break;
|
||||
if (batch->num_rows() == 0) continue;
|
||||
|
||||
if (max_rows_per_batch_ > 0 && batch->num_rows() > max_rows_per_batch_) {
|
||||
int64_t offset = 0;
|
||||
while (offset < batch->num_rows()) {
|
||||
int64_t length =
|
||||
std::min(max_rows_per_batch_, batch->num_rows() - offset);
|
||||
auto slice = batch->Slice(offset, length);
|
||||
ARROW_RETURN_NOT_OK(write_batch(*slice, filter));
|
||||
offset += length;
|
||||
}
|
||||
} else {
|
||||
ARROW_RETURN_NOT_OK(write_batch(*batch, filter));
|
||||
}
|
||||
|
||||
batch.reset();
|
||||
}
|
||||
|
||||
return arrow::Status::OK();
|
||||
}
|
||||
|
||||
arrow::Status ArrowIpcWriter::insert_batch(
|
||||
std::shared_ptr<arrow::RecordBatch> batch, const IndexFilter::Ptr &filter) {
|
||||
if (!batch) {
|
||||
return arrow::Status::Invalid("RecordBatch is null");
|
||||
}
|
||||
|
||||
if (batch->num_rows() == 0) {
|
||||
return arrow::Status::OK();
|
||||
}
|
||||
|
||||
auto incoming_schema = batch->schema();
|
||||
if (!incoming_schema) {
|
||||
return arrow::Status::Invalid("Reader schema is null");
|
||||
}
|
||||
|
||||
if (!writer_) {
|
||||
schema_ = incoming_schema;
|
||||
|
||||
ARROW_ASSIGN_OR_RAISE(sink_, arrow::io::FileOutputStream::Open(filepath_));
|
||||
|
||||
auto writer = arrow::ipc::MakeFileWriter(sink_.get(), schema_);
|
||||
if (!writer.ok()) {
|
||||
return writer.status();
|
||||
}
|
||||
|
||||
writer_ = std::move(writer.ValueOrDie());
|
||||
|
||||
} else {
|
||||
if (!schema_->Equals(incoming_schema)) {
|
||||
return arrow::Status::Invalid("Schema mismatch in Insert()");
|
||||
}
|
||||
}
|
||||
|
||||
if (max_rows_per_batch_ > 0 && batch->num_rows() > max_rows_per_batch_) {
|
||||
int64_t offset = 0;
|
||||
while (offset < batch->num_rows()) {
|
||||
int64_t length =
|
||||
std::min(max_rows_per_batch_, batch->num_rows() - offset);
|
||||
auto slice = batch->Slice(offset, length);
|
||||
|
||||
ARROW_RETURN_NOT_OK(write_batch(*slice, filter));
|
||||
|
||||
offset += length;
|
||||
}
|
||||
} else {
|
||||
ARROW_RETURN_NOT_OK(write_batch(*batch, filter));
|
||||
}
|
||||
|
||||
return arrow::Status::OK();
|
||||
}
|
||||
|
||||
arrow::Status ArrowIpcWriter::write_batch(const arrow::RecordBatch &batch,
|
||||
const IndexFilter::Ptr &filter) {
|
||||
if (!filter) {
|
||||
return writer_->WriteRecordBatch(batch);
|
||||
}
|
||||
|
||||
std::vector<int64_t> selected_indices;
|
||||
for (int64_t i = 0; i < batch.num_rows(); ++i) {
|
||||
if (filter->is_filtered(i)) {
|
||||
selected_indices.push_back(i);
|
||||
}
|
||||
}
|
||||
|
||||
if (selected_indices.empty()) {
|
||||
return arrow::Status::OK();
|
||||
}
|
||||
|
||||
arrow::Int64Builder builder;
|
||||
ARROW_RETURN_NOT_OK(builder.AppendValues(selected_indices));
|
||||
std::shared_ptr<arrow::Array> selection_array;
|
||||
ARROW_RETURN_NOT_OK(builder.Finish(&selection_array));
|
||||
|
||||
std::vector<std::shared_ptr<arrow::Array>> filtered_columns;
|
||||
for (int i = 0; i < batch.num_columns(); ++i) {
|
||||
arrow::Datum out;
|
||||
ARROW_ASSIGN_OR_RAISE(
|
||||
out, arrow::compute::Take(batch.column(i), selection_array));
|
||||
filtered_columns.push_back(out.make_array());
|
||||
}
|
||||
|
||||
auto filtered_batch = arrow::RecordBatch::Make(
|
||||
batch.schema(), static_cast<int64_t>(selected_indices.size()),
|
||||
filtered_columns);
|
||||
|
||||
return writer_->WriteRecordBatch(*filtered_batch);
|
||||
}
|
||||
|
||||
arrow::Status ArrowIpcWriter::finalize() {
|
||||
if (finalized_) return arrow::Status::OK();
|
||||
if (!writer_) {
|
||||
return arrow::Status::Invalid("No data written, cannot finalize");
|
||||
}
|
||||
|
||||
ARROW_RETURN_NOT_OK(writer_->Close());
|
||||
writer_.reset();
|
||||
|
||||
ARROW_RETURN_NOT_OK(sink_->Close());
|
||||
sink_.reset();
|
||||
|
||||
finalized_ = true;
|
||||
return arrow::Status::OK();
|
||||
}
|
||||
|
||||
} // namespace zvec
|
||||
@@ -0,0 +1,55 @@
|
||||
// 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.
|
||||
// arrow_ipc_writer.h
|
||||
#pragma once
|
||||
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <arrow/api.h>
|
||||
#include <arrow/io/api.h>
|
||||
#include <arrow/ipc/writer.h>
|
||||
#include "db/index/common/index_filter.h"
|
||||
#include "forward_writer.h"
|
||||
|
||||
namespace zvec {
|
||||
|
||||
class ArrowIpcWriter : public ForwardWriter {
|
||||
public:
|
||||
explicit ArrowIpcWriter(const std::string &filepath,
|
||||
int64_t max_rows_per_batch = 0);
|
||||
~ArrowIpcWriter();
|
||||
|
||||
arrow::Status insert(std::shared_ptr<arrow::RecordBatchReader> reader,
|
||||
const IndexFilter::Ptr &filter = nullptr) override;
|
||||
|
||||
arrow::Status insert_batch(std::shared_ptr<arrow::RecordBatch> batch,
|
||||
const IndexFilter::Ptr &filter = nullptr) override;
|
||||
|
||||
arrow::Status finalize() override;
|
||||
|
||||
private:
|
||||
arrow::Status write_batch(const arrow::RecordBatch &batch,
|
||||
const IndexFilter::Ptr &filter);
|
||||
|
||||
private:
|
||||
std::string filepath_;
|
||||
int64_t max_rows_per_batch_;
|
||||
|
||||
std::shared_ptr<arrow::io::FileOutputStream> sink_;
|
||||
std::shared_ptr<arrow::ipc::RecordBatchWriter> writer_;
|
||||
std::shared_ptr<arrow::Schema> schema_;
|
||||
bool finalized_;
|
||||
};
|
||||
|
||||
} // namespace zvec
|
||||
@@ -0,0 +1,59 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
#pragma once
|
||||
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <arrow/compute/api.h>
|
||||
#include <arrow/datum.h>
|
||||
#include <arrow/table_builder.h>
|
||||
#include <arrow/util/async_generator.h>
|
||||
#include "db/common/status.h"
|
||||
|
||||
namespace cp = arrow::compute;
|
||||
|
||||
using Table = arrow::Table;
|
||||
using RecordBatch = arrow::RecordBatch;
|
||||
using RecordBatchReader = arrow::RecordBatchReader;
|
||||
using RecordBatchBuilder = arrow::RecordBatchBuilder;
|
||||
using TablePtr = std::shared_ptr<Table>;
|
||||
using ExecBatchPtr = std::shared_ptr<arrow::compute::ExecBatch>;
|
||||
using RecordBatchPtr = std::shared_ptr<RecordBatch>;
|
||||
using RecordBatchReaderPtr = std::shared_ptr<RecordBatchReader>;
|
||||
using RecordBatchBuilderPtr = std::shared_ptr<RecordBatchBuilder>;
|
||||
|
||||
namespace zvec {
|
||||
|
||||
class BaseForwardStore {
|
||||
public:
|
||||
using Ptr = std::shared_ptr<BaseForwardStore>;
|
||||
|
||||
virtual Status Open() = 0;
|
||||
|
||||
virtual TablePtr fetch(const std::vector<std::string> &columns,
|
||||
const std::vector<int> &indices) = 0;
|
||||
|
||||
virtual ExecBatchPtr fetch(const std::vector<std::string> &columns,
|
||||
int index) = 0;
|
||||
|
||||
virtual RecordBatchReaderPtr scan(
|
||||
const std::vector<std::string> &columns) = 0;
|
||||
|
||||
virtual const std::shared_ptr<arrow::Schema> physic_schema() const = 0;
|
||||
|
||||
virtual TablePtr get_table() = 0;
|
||||
};
|
||||
|
||||
} // namespace zvec
|
||||
@@ -0,0 +1,381 @@
|
||||
// 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 "bufferpool_forward_store.h"
|
||||
#include <ailego/buffer/buffer_manager.h>
|
||||
#include <ailego/logger/logger.h>
|
||||
#include <arrow/acero/exec_plan.h>
|
||||
#include <arrow/compute/api.h>
|
||||
#include <arrow/filesystem/api.h>
|
||||
#include <arrow/ipc/reader.h>
|
||||
#include <arrow/ipc/writer.h>
|
||||
#include <arrow/result.h>
|
||||
#include <arrow/status.h>
|
||||
#include <parquet/arrow/reader.h>
|
||||
#include "storage/store_helper.h"
|
||||
#include "lazy_record_batch_reader.h"
|
||||
|
||||
|
||||
namespace zvec {
|
||||
|
||||
BufferPoolForwardStore::BufferPoolForwardStore(const std::string &uri)
|
||||
: file_path_(uri) {}
|
||||
|
||||
Status BufferPoolForwardStore::Open() {
|
||||
std::string uri = file_path_;
|
||||
auto status = CreateRandomAccessFileByUri(uri, &file_, &file_path_);
|
||||
if (!status.ok()) {
|
||||
return Status::InternalError("Failed to create random access uri: ", uri,
|
||||
" : ", status.ToString());
|
||||
}
|
||||
auto format = InferFileFormat(file_path_);
|
||||
if (format == FileFormat::PARQUET) {
|
||||
status = OpenParquet(file_);
|
||||
if (!status.ok()) {
|
||||
return Status::InternalError("Failed to open parquet file: ", file_path_,
|
||||
" : ", status.ToString());
|
||||
}
|
||||
} else {
|
||||
return Status::InternalError("Unsupported format, file: ", file_path_);
|
||||
}
|
||||
return Status::OK();
|
||||
}
|
||||
arrow::Status BufferPoolForwardStore::OpenParquet(
|
||||
const std::shared_ptr<arrow::io::RandomAccessFile> &file) {
|
||||
auto parquet_file_reader = parquet::ParquetFileReader::Open(file);
|
||||
ARROW_RETURN_NOT_OK(parquet::arrow::FileReader::Make(
|
||||
arrow::default_memory_pool(), std::move(parquet_file_reader),
|
||||
&parquet_reader_));
|
||||
|
||||
auto parquet_metadata = parquet_reader_->parquet_reader()->metadata();
|
||||
num_rows_ = parquet_metadata->num_rows();
|
||||
num_row_groups_ = parquet_metadata->num_row_groups();
|
||||
|
||||
// Initialize row group offsets and row counts
|
||||
int64_t offset = 0;
|
||||
for (int64_t rg = 0; rg < num_row_groups_; ++rg) {
|
||||
auto row_group_metadata = parquet_metadata->RowGroup(rg);
|
||||
int64_t num_rows_in_group = row_group_metadata->num_rows();
|
||||
row_group_row_nums_.push_back(num_rows_in_group);
|
||||
row_group_offsets_.push_back(offset);
|
||||
offset += num_rows_in_group;
|
||||
}
|
||||
|
||||
ARROW_RETURN_NOT_OK(parquet_reader_->GetSchema(&physic_schema_));
|
||||
|
||||
LOG_INFO("Opened Parquet with %lld rows, %d cols, %d row groups",
|
||||
static_cast<long long>(num_rows_), physic_schema_->num_fields(),
|
||||
parquet_metadata->num_row_groups());
|
||||
|
||||
return arrow::Status::OK();
|
||||
}
|
||||
|
||||
|
||||
bool BufferPoolForwardStore::validate(
|
||||
const std::vector<std::string> &columns) const {
|
||||
if (columns.empty()) {
|
||||
LOG_ERROR("Empty columns");
|
||||
return false;
|
||||
}
|
||||
// TODO : for persist segment, after add new column, this check is not
|
||||
// correct.
|
||||
for (auto &column : columns) {
|
||||
if (column == LOCAL_ROW_ID) {
|
||||
continue;
|
||||
}
|
||||
if (physic_schema_->GetFieldIndex(column) == -1) {
|
||||
LOG_ERROR("Validate failed. unknown column: %s", column.c_str());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
int BufferPoolForwardStore::FindRowGroupForRow(int64_t row) {
|
||||
auto it = std::upper_bound(row_group_offsets_.begin(),
|
||||
row_group_offsets_.end(), row);
|
||||
if (it == row_group_offsets_.begin()) {
|
||||
return 0;
|
||||
}
|
||||
return static_cast<int>(std::distance(row_group_offsets_.begin(), it) - 1);
|
||||
}
|
||||
|
||||
int64_t BufferPoolForwardStore::GetRowGroupOffset(int rg_id) {
|
||||
if (rg_id < 0 || rg_id >= static_cast<int>(row_group_offsets_.size())) {
|
||||
LOG_ERROR("Invalid row group id: %d, max: %zu", rg_id,
|
||||
row_group_offsets_.size());
|
||||
return -1;
|
||||
}
|
||||
return row_group_offsets_[rg_id];
|
||||
}
|
||||
|
||||
|
||||
TablePtr BufferPoolForwardStore::fetch(const std::vector<std::string> &columns,
|
||||
const std::vector<int> &indices) {
|
||||
if (!validate(columns)) {
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
if (indices.empty()) {
|
||||
arrow::ArrayVector empty_arrays;
|
||||
auto fields = SelectFields(physic_schema_, columns);
|
||||
for (const auto &field : fields) {
|
||||
empty_arrays.push_back(arrow::MakeEmptyArray(field->type()).ValueOrDie());
|
||||
}
|
||||
return arrow::Table::Make(std::make_shared<arrow::Schema>(fields),
|
||||
empty_arrays, 0);
|
||||
}
|
||||
|
||||
bool need_local_doc_id = false;
|
||||
std::vector<int> col_indices;
|
||||
std::vector<int> data_column_positions;
|
||||
std::vector<std::shared_ptr<arrow::Field>> all_fields(columns.size());
|
||||
|
||||
for (size_t i = 0; i < columns.size(); ++i) {
|
||||
if (columns[i] == LOCAL_ROW_ID) {
|
||||
need_local_doc_id = true;
|
||||
all_fields[i] = arrow::field(LOCAL_ROW_ID, arrow::uint64());
|
||||
} else {
|
||||
int idx = physic_schema_->GetFieldIndex(columns[i]);
|
||||
if (idx == -1) {
|
||||
LOG_ERROR("Unknown column: %s", columns[i].c_str());
|
||||
return nullptr;
|
||||
}
|
||||
col_indices.push_back(idx);
|
||||
data_column_positions.push_back(static_cast<int>(i));
|
||||
all_fields[i] = physic_schema_->GetFieldByName(columns[i]);
|
||||
}
|
||||
}
|
||||
|
||||
std::unordered_map<int, std::vector<std::pair<int, uint64_t>>> rg_to_local;
|
||||
std::vector<std::pair<int, int64_t>>
|
||||
local_doc_id_pairs; // (output_row, global_row)
|
||||
|
||||
int output_row = 0;
|
||||
for (int global_row : indices) {
|
||||
if (global_row < 0 || global_row >= num_rows_) {
|
||||
LOG_ERROR("Invalid row index: %d, max: %lld", global_row,
|
||||
static_cast<long long>(num_rows_));
|
||||
return nullptr;
|
||||
}
|
||||
int rg_id = FindRowGroupForRow(global_row);
|
||||
int64_t offset = GetRowGroupOffset(rg_id);
|
||||
if (offset == -1) {
|
||||
LOG_ERROR("Failed to get row group offset for row: %d", global_row);
|
||||
return nullptr;
|
||||
}
|
||||
uint64_t local_in_rg = global_row - offset;
|
||||
rg_to_local[rg_id].emplace_back(output_row, local_in_rg);
|
||||
|
||||
if (need_local_doc_id) {
|
||||
local_doc_id_pairs.emplace_back(output_row,
|
||||
static_cast<int64_t>(global_row));
|
||||
}
|
||||
++output_row;
|
||||
}
|
||||
|
||||
std::vector<std::vector<std::pair<int, std::shared_ptr<arrow::Scalar>>>>
|
||||
sorted_scalars(col_indices.size());
|
||||
|
||||
auto &buf_mgr = ailego::BufferManager::Instance();
|
||||
for (const auto &[rg_id, pairs] : rg_to_local) {
|
||||
for (size_t i = 0; i < col_indices.size(); ++i) {
|
||||
int col_idx = col_indices[i];
|
||||
auto buffer_id = ailego::BufferID::ParquetID(file_path_, col_idx, rg_id);
|
||||
auto buffer_handle = buf_mgr.acquire(buffer_id);
|
||||
auto col_chunked_array = buffer_handle.pin_parquet_data();
|
||||
|
||||
if (!col_chunked_array) {
|
||||
LOG_ERROR(
|
||||
"Failed to pin parquet data for file: %s, column: %d, row_group: "
|
||||
"%d",
|
||||
file_path_.c_str(), col_idx, rg_id);
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
if (col_chunked_array->num_chunks() == 0) {
|
||||
LOG_WARN(
|
||||
"No chunks in chunked array for file: %s, column: %d, row_group: "
|
||||
"%d",
|
||||
file_path_.c_str(), col_idx, rg_id);
|
||||
continue;
|
||||
}
|
||||
|
||||
auto &dst = sorted_scalars[i];
|
||||
for (const auto &[tmp_output_row, local_idx] : pairs) {
|
||||
if ((size_t)local_idx >= (size_t)col_chunked_array->length()) {
|
||||
LOG_ERROR("Local index %ld out of bounds for array length %zu",
|
||||
static_cast<long>(local_idx),
|
||||
(size_t)col_chunked_array->length());
|
||||
return nullptr;
|
||||
}
|
||||
auto scalar_result = col_chunked_array->GetScalar(local_idx);
|
||||
if (!scalar_result.ok()) {
|
||||
LOG_ERROR("Failed to get scalar for row %zu status: %s",
|
||||
(size_t)local_idx,
|
||||
scalar_result.status().ToString().c_str());
|
||||
}
|
||||
dst.emplace_back(tmp_output_row, std::move(scalar_result.ValueOrDie()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<std::shared_ptr<arrow::Array>> result_arrays(columns.size());
|
||||
for (size_t i = 0; i < sorted_scalars.size(); ++i) {
|
||||
auto &vec = sorted_scalars[i];
|
||||
std::sort(vec.begin(), vec.end());
|
||||
std::vector<std::shared_ptr<arrow::Scalar>> ordered_scalars;
|
||||
ordered_scalars.reserve(vec.size());
|
||||
for (auto &p : vec) {
|
||||
ordered_scalars.push_back(std::move(p.second));
|
||||
}
|
||||
|
||||
std::shared_ptr<arrow::Array> arr;
|
||||
auto status = ConvertScalarVectorToArrayByType(ordered_scalars, &arr);
|
||||
if (!status.ok()) {
|
||||
LOG_ERROR("ConvertScalarVectorToArrayByType failed: %s",
|
||||
status.message().c_str());
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
int position = data_column_positions[i];
|
||||
result_arrays[position] = std::move(arr);
|
||||
}
|
||||
|
||||
if (need_local_doc_id) {
|
||||
std::sort(local_doc_id_pairs.begin(), local_doc_id_pairs.end());
|
||||
std::vector<uint64_t> values;
|
||||
values.reserve(local_doc_id_pairs.size());
|
||||
for (const auto &p : local_doc_id_pairs) {
|
||||
values.push_back(p.second);
|
||||
}
|
||||
|
||||
// Create UInt64Array
|
||||
auto buffer_result = arrow::AllocateBuffer(values.size() * sizeof(uint64_t),
|
||||
arrow::default_memory_pool());
|
||||
if (!buffer_result.ok()) return nullptr;
|
||||
auto buffer = std::move(buffer_result.ValueOrDie());
|
||||
std::memcpy(buffer->mutable_data(), values.data(),
|
||||
values.size() * sizeof(uint64_t));
|
||||
|
||||
std::vector<std::shared_ptr<arrow::Buffer>> buffers;
|
||||
buffers.push_back(nullptr); // no null bitmap
|
||||
buffers.push_back(std::shared_ptr<arrow::Buffer>(buffer.release()));
|
||||
|
||||
auto data = arrow::ArrayData::Make(arrow::uint64(),
|
||||
static_cast<uint64_t>(values.size()),
|
||||
std::move(buffers), /*null_count=*/0);
|
||||
|
||||
for (size_t i = 0; i < columns.size(); ++i) {
|
||||
if (columns[i] == LOCAL_ROW_ID) {
|
||||
result_arrays[i] = std::make_shared<arrow::UInt64Array>(data);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<std::shared_ptr<arrow::ChunkedArray>> result_columns;
|
||||
result_columns.reserve(result_arrays.size());
|
||||
for (auto &arr : result_arrays) {
|
||||
result_columns.emplace_back(std::make_shared<arrow::ChunkedArray>(arr));
|
||||
}
|
||||
|
||||
auto out_schema = std::make_shared<arrow::Schema>(all_fields);
|
||||
return arrow::Table::Make(out_schema, result_columns,
|
||||
static_cast<int64_t>(indices.size()));
|
||||
}
|
||||
|
||||
ExecBatchPtr BufferPoolForwardStore::fetch(
|
||||
const std::vector<std::string> &columns, int index) {
|
||||
if (!validate(columns) || index < 0 || index >= num_rows_) {
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
std::vector<int> col_indices;
|
||||
for (const auto &col : columns) {
|
||||
int idx = physic_schema_->GetFieldIndex(col);
|
||||
if (idx == -1) {
|
||||
LOG_ERROR("Unknown column: %s", col.c_str());
|
||||
return nullptr;
|
||||
}
|
||||
col_indices.push_back(idx);
|
||||
}
|
||||
|
||||
int rg_id = FindRowGroupForRow(index);
|
||||
int64_t offset = GetRowGroupOffset(rg_id);
|
||||
|
||||
std::vector<arrow::Datum> scalars;
|
||||
auto &buf_mgr = ailego::BufferManager::Instance();
|
||||
for (size_t i = 0; i < col_indices.size(); ++i) {
|
||||
int col_idx = col_indices[i];
|
||||
auto buffer_id = ailego::BufferID::ParquetID(file_path_, col_idx, rg_id);
|
||||
auto buffer_handle = buf_mgr.acquire(buffer_id);
|
||||
auto col_chunked_array = buffer_handle.pin_parquet_data();
|
||||
|
||||
if (!col_chunked_array) {
|
||||
LOG_ERROR(
|
||||
"Failed to pin parquet data for file: %s, column: %d, row_group: "
|
||||
"%d",
|
||||
file_path_.c_str(), col_idx, rg_id);
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
if (col_chunked_array->num_chunks() == 0) {
|
||||
LOG_WARN(
|
||||
"No chunks in chunked array for file: %s, column: %d, row_group: "
|
||||
"%d",
|
||||
file_path_.c_str(), col_idx, rg_id);
|
||||
continue;
|
||||
}
|
||||
auto concat_result = arrow::Concatenate(col_chunked_array->chunks(),
|
||||
arrow::default_memory_pool());
|
||||
if (!concat_result.ok()) {
|
||||
LOG_ERROR("Concatenate failed for file: %s, column: %d, row_group: %d",
|
||||
file_path_.c_str(), col_idx, rg_id);
|
||||
return nullptr;
|
||||
}
|
||||
auto concat = concat_result.ValueOrDie();
|
||||
auto scalar_result = concat->GetScalar(index - offset);
|
||||
if (!scalar_result.ok()) {
|
||||
LOG_ERROR("Failed to get scalar for row %zu status: %s", (size_t)offset,
|
||||
scalar_result.status().ToString().c_str());
|
||||
}
|
||||
|
||||
scalars.emplace_back(std::move(scalar_result.ValueOrDie()));
|
||||
}
|
||||
|
||||
return std::make_shared<arrow::ExecBatch>(std::move(scalars), 1);
|
||||
}
|
||||
|
||||
RecordBatchReaderPtr BufferPoolForwardStore::scan(
|
||||
const std::vector<std::string> &columns) {
|
||||
if (!validate(columns)) {
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
// Create a new parquet reader for scanning
|
||||
std::unique_ptr<parquet::arrow::FileReader> parquet_reader;
|
||||
auto parquet_file_reader = parquet::ParquetFileReader::Open(file_);
|
||||
auto status = parquet::arrow::FileReader::Make(arrow::default_memory_pool(),
|
||||
std::move(parquet_file_reader),
|
||||
&parquet_reader);
|
||||
if (!status.ok()) {
|
||||
LOG_ERROR("Failed to create parquet reader: %s", status.message().c_str());
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
return std::make_shared<ParquetRecordBatchReader>(parquet_reader, columns,
|
||||
physic_schema_, file_path_);
|
||||
}
|
||||
|
||||
} // namespace zvec
|
||||
@@ -0,0 +1,131 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
#pragma once
|
||||
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <ailego/buffer/buffer_manager.h>
|
||||
#include <arrow/api.h>
|
||||
#include <arrow/compute/api.h>
|
||||
#include <arrow/filesystem/filesystem.h>
|
||||
#include <arrow/io/api.h>
|
||||
#include <arrow/ipc/reader.h>
|
||||
#include <arrow/util/async_generator.h>
|
||||
#include <parquet/arrow/reader.h>
|
||||
#include "db/common/status.h"
|
||||
#include "base_forward_store.h"
|
||||
|
||||
namespace zvec {
|
||||
|
||||
/// BufferPoolForwardStore implements a forward store that uses a buffer pool
|
||||
/// to efficiently manage data access from parquet files.
|
||||
class BufferPoolForwardStore
|
||||
: public BaseForwardStore,
|
||||
public std::enable_shared_from_this<BufferPoolForwardStore> {
|
||||
public:
|
||||
/// Pointer type for BufferPoolForwardStore instances
|
||||
using Ptr = std::shared_ptr<BufferPoolForwardStore>;
|
||||
|
||||
/// Constructor that initializes the store with a file URI
|
||||
/// \param uri The URI of the file to be accessed
|
||||
explicit BufferPoolForwardStore(const std::string &uri);
|
||||
|
||||
virtual ~BufferPoolForwardStore() = default;
|
||||
|
||||
Status Open() override;
|
||||
|
||||
/// Fetch specific columns and row indices from the data source
|
||||
/// \param columns The list of column names to fetch
|
||||
/// \param indices The list of row indices to fetch
|
||||
/// \return A table containing the requested data or nullptr on failure
|
||||
TablePtr fetch(const std::vector<std::string> &columns,
|
||||
const std::vector<int> &indices) override;
|
||||
|
||||
/// Fetch specific columns and row indices from the data source
|
||||
/// \param columns The list of column names to fetch
|
||||
/// \param index The row index to fetch
|
||||
/// \return An ExecBatch containing the requested data or nullptr on failure
|
||||
ExecBatchPtr fetch(const std::vector<std::string> &columns,
|
||||
int index) override;
|
||||
|
||||
/// Scan specified columns from the data source
|
||||
/// \param columns The list of column names to scan
|
||||
/// \return A RecordBatchReader for streaming the data or nullptr on failure
|
||||
RecordBatchReaderPtr scan(const std::vector<std::string> &columns) override;
|
||||
|
||||
/// Get the physical schema of the file
|
||||
/// \return A shared pointer to the arrow schema representing the physical
|
||||
/// structure of the data
|
||||
const std::shared_ptr<arrow::Schema> physic_schema() const override {
|
||||
return physic_schema_;
|
||||
}
|
||||
|
||||
TablePtr get_table() override {
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
private:
|
||||
/// Validate that the requested columns exist in the schema
|
||||
/// \param columns The list of column names to validate
|
||||
/// \return true if all columns are valid, false otherwise
|
||||
bool validate(const std::vector<std::string> &columns) const;
|
||||
|
||||
/// Open a parquet file and initialize metadata
|
||||
/// \param file The RandomAccessFile to read from
|
||||
/// \return arrow::Status indicating success or failure
|
||||
arrow::Status OpenParquet(
|
||||
const std::shared_ptr<arrow::io::RandomAccessFile> &file);
|
||||
|
||||
/// Find which row group contains a given row
|
||||
/// \param row The row index to locate
|
||||
/// \return The row group ID containing the row
|
||||
int FindRowGroupForRow(int64_t row);
|
||||
|
||||
/// Get the row offset for a given row group
|
||||
/// \param rg_id The row group ID
|
||||
/// \return The row offset of the row group, or -1 on error
|
||||
int64_t GetRowGroupOffset(int rg_id);
|
||||
|
||||
private:
|
||||
/// Physical schema of the file
|
||||
std::shared_ptr<arrow::Schema> physic_schema_;
|
||||
|
||||
/// Total number of rows in the file
|
||||
int64_t num_rows_ = 0;
|
||||
|
||||
/// Path to the file
|
||||
std::string file_path_;
|
||||
|
||||
// Parquet-specific members
|
||||
/// The RandomAccessFile for reading data
|
||||
std::shared_ptr<arrow::io::RandomAccessFile> file_;
|
||||
|
||||
/// The parquet file reader
|
||||
std::unique_ptr<parquet::arrow::FileReader> parquet_reader_;
|
||||
|
||||
/// Number of row groups in the file
|
||||
int64_t num_row_groups_ = 0;
|
||||
|
||||
/// Offsets of each row group
|
||||
std::vector<int64_t> row_group_offsets_;
|
||||
|
||||
/// Number of rows in each row group
|
||||
std::vector<int64_t> row_group_row_nums_;
|
||||
|
||||
/// Buffer manager for caching data
|
||||
std::shared_ptr<ailego::BufferManager> buffer_manager_;
|
||||
};
|
||||
|
||||
} // namespace zvec
|
||||
@@ -0,0 +1,138 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#include "chunked_file_writer.h"
|
||||
#include <fstream>
|
||||
#include <ailego/logger/logger.h>
|
||||
#include <arrow/ipc/writer.h>
|
||||
#include <parquet/arrow/writer.h>
|
||||
#include <parquet/exception.h>
|
||||
|
||||
|
||||
namespace zvec {
|
||||
|
||||
class IpcChunkedWriter : public ChunkedFileWriter {
|
||||
public:
|
||||
static arrow::Result<std::unique_ptr<IpcChunkedWriter>> Make(
|
||||
const std::string &path, const std::shared_ptr<arrow::Schema> &schema) {
|
||||
ARROW_ASSIGN_OR_RAISE(auto out_file,
|
||||
arrow::io::FileOutputStream::Open(path));
|
||||
|
||||
std::shared_ptr<arrow::ipc::RecordBatchWriter> writer;
|
||||
ARROW_ASSIGN_OR_RAISE(writer, arrow::ipc::MakeFileWriter(out_file, schema));
|
||||
|
||||
return std::make_unique<IpcChunkedWriter>(schema, std::move(out_file),
|
||||
std::move(writer));
|
||||
}
|
||||
|
||||
IpcChunkedWriter(std::shared_ptr<arrow::Schema> schema,
|
||||
std::shared_ptr<arrow::io::FileOutputStream> out_file,
|
||||
std::shared_ptr<arrow::ipc::RecordBatchWriter> writer)
|
||||
: ChunkedFileWriter(std::move(schema)),
|
||||
out_file_(std::move(out_file)),
|
||||
writer_(std::move(writer)) {}
|
||||
|
||||
arrow::Status Write(const arrow::RecordBatch &batch) override {
|
||||
return writer_->WriteRecordBatch(batch);
|
||||
}
|
||||
|
||||
arrow::Status Write(const arrow::Table &table) override {
|
||||
return writer_->WriteTable(table);
|
||||
}
|
||||
|
||||
arrow::Status Close() override {
|
||||
ARROW_RETURN_NOT_OK(writer_->Close());
|
||||
return out_file_->Close();
|
||||
}
|
||||
|
||||
private:
|
||||
std::shared_ptr<arrow::io::FileOutputStream> out_file_;
|
||||
std::shared_ptr<arrow::ipc::RecordBatchWriter> writer_;
|
||||
};
|
||||
|
||||
|
||||
class ParquetChunkedWriter : public ChunkedFileWriter {
|
||||
public:
|
||||
static arrow::Result<std::unique_ptr<ParquetChunkedWriter>> Make(
|
||||
const std::string &path, const std::shared_ptr<arrow::Schema> &schema) {
|
||||
ARROW_ASSIGN_OR_RAISE(auto out_file,
|
||||
arrow::io::FileOutputStream::Open(path));
|
||||
|
||||
parquet::WriterProperties::Builder builder;
|
||||
auto properties = builder.build();
|
||||
|
||||
std::shared_ptr<parquet::arrow::FileWriter> writer;
|
||||
ARROW_ASSIGN_OR_RAISE(writer, parquet::arrow::FileWriter::Open(
|
||||
*schema, arrow::default_memory_pool(),
|
||||
out_file, properties));
|
||||
|
||||
return std::make_unique<ParquetChunkedWriter>(schema, std::move(out_file),
|
||||
std::move(writer));
|
||||
}
|
||||
|
||||
ParquetChunkedWriter(std::shared_ptr<arrow::Schema> schema,
|
||||
std::shared_ptr<arrow::io::FileOutputStream> out_file,
|
||||
std::shared_ptr<parquet::arrow::FileWriter> writer)
|
||||
: ChunkedFileWriter(std::move(schema)),
|
||||
out_file_(std::move(out_file)),
|
||||
writer_(std::move(writer)) {}
|
||||
|
||||
arrow::Status Write(const arrow::RecordBatch &batch) override {
|
||||
return writer_->WriteRecordBatch(batch);
|
||||
}
|
||||
|
||||
arrow::Status Write(const arrow::Table &table) override {
|
||||
return writer_->WriteTable(table);
|
||||
}
|
||||
|
||||
arrow::Status Close() override {
|
||||
ARROW_RETURN_NOT_OK(writer_->Close());
|
||||
return out_file_->Close();
|
||||
}
|
||||
|
||||
private:
|
||||
std::shared_ptr<arrow::io::FileOutputStream> out_file_;
|
||||
std::shared_ptr<parquet::arrow::FileWriter> writer_;
|
||||
};
|
||||
|
||||
|
||||
std::unique_ptr<ChunkedFileWriter> ChunkedFileWriter::Open(
|
||||
const std::string &file_path, const std::shared_ptr<arrow::Schema> &schema,
|
||||
FileFormat format) {
|
||||
switch (format) {
|
||||
case FileFormat::IPC: {
|
||||
auto result = IpcChunkedWriter::Make(file_path, schema);
|
||||
if (!result.ok()) {
|
||||
LOG_ERROR("Failed to open IPC writer: %s",
|
||||
result.status().ToString().c_str());
|
||||
return nullptr;
|
||||
}
|
||||
return std::move(result).ValueUnsafe();
|
||||
}
|
||||
case FileFormat::PARQUET: {
|
||||
auto result = ParquetChunkedWriter::Make(file_path, schema);
|
||||
if (!result.ok()) {
|
||||
LOG_ERROR("Failed to open Parquet writer: %s",
|
||||
result.status().ToString().c_str());
|
||||
return nullptr;
|
||||
}
|
||||
return std::move(result).ValueUnsafe();
|
||||
}
|
||||
default:
|
||||
LOG_ERROR("Unsupported format");
|
||||
return nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace zvec
|
||||
@@ -0,0 +1,49 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <arrow/api.h>
|
||||
#include <arrow/io/api.h>
|
||||
#include <parquet/arrow/writer.h>
|
||||
#include "db/index/common/type.h"
|
||||
|
||||
namespace zvec {
|
||||
|
||||
class ChunkedFileWriter {
|
||||
public:
|
||||
using Ptr = std::unique_ptr<ChunkedFileWriter>;
|
||||
|
||||
static std::unique_ptr<ChunkedFileWriter> Open(
|
||||
const std::string &file_path,
|
||||
const std::shared_ptr<arrow::Schema> &schema, FileFormat format);
|
||||
|
||||
virtual arrow::Status Write(const arrow::RecordBatch &batch) = 0;
|
||||
|
||||
virtual arrow::Status Write(const arrow::Table &table) = 0;
|
||||
|
||||
virtual arrow::Status Close() = 0;
|
||||
|
||||
virtual ~ChunkedFileWriter() = default; // LCOV_EXCL_BR_LINE
|
||||
|
||||
protected:
|
||||
explicit ChunkedFileWriter(std::shared_ptr<arrow::Schema> schema)
|
||||
: schema_(std::move(schema)) {}
|
||||
|
||||
std::shared_ptr<arrow::Schema> schema_;
|
||||
};
|
||||
|
||||
} // namespace zvec
|
||||
@@ -0,0 +1,32 @@
|
||||
// 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.
|
||||
|
||||
// forward_writer.cc
|
||||
#include "forward_writer.h"
|
||||
#include "arrow_ipc_writer.h"
|
||||
#include "parquet_writer.h"
|
||||
|
||||
namespace zvec {
|
||||
|
||||
std::unique_ptr<ForwardWriter> ForwardWriter::CreateArrowIPCWriter(
|
||||
const std::string &filepath, int64_t max_rows_per_batch) {
|
||||
return std::make_unique<ArrowIpcWriter>(filepath, max_rows_per_batch);
|
||||
}
|
||||
|
||||
std::unique_ptr<ForwardWriter> ForwardWriter::CreateParquetWriter(
|
||||
const std::string &filepath, int64_t max_rows_per_batch) {
|
||||
return std::make_unique<ParquetWriter>(filepath, max_rows_per_batch);
|
||||
}
|
||||
|
||||
} // namespace zvec
|
||||
@@ -0,0 +1,45 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
#pragma once
|
||||
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <arrow/api.h>
|
||||
#include "db/index/common/index_filter.h"
|
||||
|
||||
namespace zvec {
|
||||
|
||||
class ForwardWriter {
|
||||
public:
|
||||
virtual ~ForwardWriter() = default;
|
||||
|
||||
// Factory methods
|
||||
static std::unique_ptr<ForwardWriter> CreateArrowIPCWriter(
|
||||
const std::string &filepath, int64_t max_rows_per_batch = 0);
|
||||
|
||||
static std::unique_ptr<ForwardWriter> CreateParquetWriter(
|
||||
const std::string &filepath, int64_t max_rows_per_batch = 0);
|
||||
|
||||
// Interface methods
|
||||
virtual arrow::Status insert(std::shared_ptr<arrow::RecordBatchReader> reader,
|
||||
const IndexFilter::Ptr &filter = nullptr) = 0;
|
||||
|
||||
virtual arrow::Status insert_batch(
|
||||
std::shared_ptr<arrow::RecordBatch> batch,
|
||||
const IndexFilter::Ptr &filter = nullptr) = 0;
|
||||
|
||||
virtual arrow::Status finalize() = 0;
|
||||
};
|
||||
|
||||
} // namespace zvec
|
||||
@@ -0,0 +1,185 @@
|
||||
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
#pragma once
|
||||
|
||||
#include <ailego/buffer/buffer_manager.h>
|
||||
#include <arrow/ipc/reader.h>
|
||||
#include <parquet/arrow/reader.h>
|
||||
#include "db/common/constants.h"
|
||||
|
||||
|
||||
namespace zvec {
|
||||
|
||||
class IPCRecordBatchReader : public arrow::RecordBatchReader {
|
||||
public:
|
||||
IPCRecordBatchReader(
|
||||
std::shared_ptr<arrow::ipc::RecordBatchFileReader> reader,
|
||||
const std::vector<std::string> &columns,
|
||||
std::shared_ptr<arrow::Schema> schema)
|
||||
: reader_(std::move(reader)),
|
||||
schema_(std::move(schema)),
|
||||
columns_(columns) {
|
||||
std::vector<std::shared_ptr<arrow::Field>> fields;
|
||||
for (const auto &col : columns) {
|
||||
int index = schema_->GetFieldIndex(col);
|
||||
if (index != -1) {
|
||||
fields.push_back(schema_->field(index));
|
||||
col_indices_.push_back(index);
|
||||
}
|
||||
}
|
||||
projected_schema_ = arrow::schema(fields);
|
||||
num_record_batches_ = reader_->num_record_batches();
|
||||
}
|
||||
|
||||
std::shared_ptr<arrow::Schema> schema() const override {
|
||||
return projected_schema_;
|
||||
}
|
||||
|
||||
arrow::Status ReadNext(std::shared_ptr<arrow::RecordBatch> *batch) override {
|
||||
if (current_batch_ >= num_record_batches_) {
|
||||
*batch = nullptr;
|
||||
return arrow::Status::OK();
|
||||
}
|
||||
|
||||
ARROW_ASSIGN_OR_RAISE(auto full_batch,
|
||||
reader_->ReadRecordBatch(current_batch_));
|
||||
current_batch_++;
|
||||
|
||||
std::vector<std::shared_ptr<arrow::Array>> projected_arrays;
|
||||
for (int index : col_indices_) {
|
||||
projected_arrays.push_back(full_batch->column(index));
|
||||
}
|
||||
|
||||
*batch = arrow::RecordBatch::Make(projected_schema_, full_batch->num_rows(),
|
||||
projected_arrays);
|
||||
return arrow::Status::OK();
|
||||
}
|
||||
|
||||
private:
|
||||
std::shared_ptr<arrow::ipc::RecordBatchFileReader> reader_;
|
||||
std::shared_ptr<arrow::Schema> schema_;
|
||||
std::shared_ptr<arrow::Schema> projected_schema_;
|
||||
std::vector<std::string> columns_;
|
||||
std::vector<int> col_indices_;
|
||||
int current_batch_ = 0;
|
||||
int num_record_batches_ = 0;
|
||||
};
|
||||
|
||||
|
||||
class ParquetRecordBatchReader : public arrow::RecordBatchReader {
|
||||
public:
|
||||
ParquetRecordBatchReader(std::unique_ptr<parquet::arrow::FileReader> &reader,
|
||||
const std::vector<std::string> &columns,
|
||||
std::shared_ptr<arrow::Schema> schema,
|
||||
const std::string &file_path, bool with_cache = true)
|
||||
: reader_(std::move(reader)),
|
||||
schema_(std::move(schema)),
|
||||
columns_(columns),
|
||||
file_path_(file_path),
|
||||
with_cache_(with_cache) {
|
||||
std::vector<std::shared_ptr<arrow::Field>> fields;
|
||||
for (const auto &col : columns) {
|
||||
int index = schema_->GetFieldIndex(col);
|
||||
if (index != -1) {
|
||||
fields.push_back(schema_->field(index));
|
||||
col_indices_.push_back(index);
|
||||
}
|
||||
}
|
||||
projected_schema_ = arrow::schema(fields);
|
||||
|
||||
auto parquet_metadata = reader_->parquet_reader()->metadata();
|
||||
total_rows_ = parquet_metadata->num_rows();
|
||||
num_row_groups_ = parquet_metadata->num_row_groups();
|
||||
int64_t offset = 0;
|
||||
for (int64_t rg = 0; rg < num_row_groups_; ++rg) {
|
||||
auto row_group_metadata = parquet_metadata->RowGroup(rg);
|
||||
int64_t num_rows_in_group = row_group_metadata->num_rows();
|
||||
row_group_row_nums_.push_back(num_rows_in_group);
|
||||
row_group_offsets_.push_back(offset);
|
||||
offset += num_rows_in_group;
|
||||
}
|
||||
}
|
||||
|
||||
std::shared_ptr<arrow::Schema> schema() const override {
|
||||
return projected_schema_;
|
||||
}
|
||||
|
||||
arrow::Status ReadNext(std::shared_ptr<arrow::RecordBatch> *batch) override {
|
||||
if (current_row_group_ >= num_row_groups_) {
|
||||
return arrow::Status::OK();
|
||||
}
|
||||
|
||||
int64_t rg_id = current_row_group_;
|
||||
int64_t num_rows_in_rg = row_group_row_nums_[rg_id];
|
||||
|
||||
std::vector<std::shared_ptr<arrow::Array>> chunks(col_indices_.size());
|
||||
if (with_cache_) {
|
||||
auto &buf_mgr = ailego::BufferManager::Instance();
|
||||
for (size_t col_idx = 0; col_idx < col_indices_.size(); ++col_idx) {
|
||||
auto buffer_id = ailego::BufferID::ParquetID(
|
||||
file_path_, col_indices_[col_idx], rg_id);
|
||||
auto buffer_handle = buf_mgr.acquire(buffer_id);
|
||||
auto col_chunked_array = buffer_handle.pin_parquet_data();
|
||||
if (col_chunked_array) {
|
||||
std::shared_ptr<arrow::Array> concat;
|
||||
auto concat_result = arrow::Concatenate(col_chunked_array->chunks(),
|
||||
arrow::default_memory_pool());
|
||||
if (!concat_result.ok()) {
|
||||
return concat_result.status();
|
||||
}
|
||||
concat = concat_result.ValueOrDie();
|
||||
chunks[col_idx] = concat;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
std::shared_ptr<arrow::Table> rg_table;
|
||||
ARROW_RETURN_NOT_OK(
|
||||
reader_->RowGroup(rg_id)->ReadTable(col_indices_, &rg_table));
|
||||
for (size_t i = 0; i < col_indices_.size(); ++i) {
|
||||
std::shared_ptr<arrow::Array> concat;
|
||||
auto concat_result = arrow::Concatenate(rg_table->column(i)->chunks(),
|
||||
arrow::default_memory_pool());
|
||||
if (!concat_result.ok()) {
|
||||
return concat_result.status();
|
||||
}
|
||||
concat = concat_result.ValueOrDie();
|
||||
chunks[i] = concat;
|
||||
}
|
||||
}
|
||||
|
||||
*batch =
|
||||
arrow::RecordBatch::Make(projected_schema_, num_rows_in_rg, chunks);
|
||||
current_row_group_++;
|
||||
return arrow::Status::OK();
|
||||
}
|
||||
|
||||
private:
|
||||
std::unique_ptr<parquet::arrow::FileReader> reader_;
|
||||
std::shared_ptr<arrow::Schema> schema_;
|
||||
std::shared_ptr<arrow::Schema> projected_schema_;
|
||||
std::vector<std::string> columns_;
|
||||
std::vector<int> col_indices_;
|
||||
std::string file_path_;
|
||||
|
||||
int64_t current_row_group_ = 0;
|
||||
int64_t num_row_groups_ = 0;
|
||||
int64_t total_rows_ = 0;
|
||||
std::vector<int64_t> row_group_offsets_;
|
||||
std::vector<int64_t> row_group_row_nums_;
|
||||
bool with_cache_;
|
||||
};
|
||||
|
||||
|
||||
} // namespace zvec
|
||||
@@ -0,0 +1,478 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#include "memory_forward_store.h"
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <ailego/logger/logger.h>
|
||||
#include <ailego/pattern/defer.h>
|
||||
#include <arrow/api.h>
|
||||
#include <arrow/builder.h>
|
||||
#include <arrow/compute/api.h>
|
||||
#include <arrow/io/file.h>
|
||||
#include <arrow/ipc/writer.h>
|
||||
#include <arrow/record_batch.h>
|
||||
#include <arrow/table.h>
|
||||
#include <arrow/util/async_generator.h>
|
||||
#include "db/common/constants.h"
|
||||
#include "db/index/storage/base_forward_store.h"
|
||||
|
||||
|
||||
namespace zvec {
|
||||
|
||||
MemForwardStore::MemForwardStore(
|
||||
const std::shared_ptr<CollectionSchema> &collection_schema,
|
||||
const std::string &path, const FileFormat format,
|
||||
const uint32_t max_buffer_size)
|
||||
: schema_(collection_schema),
|
||||
path_(path),
|
||||
format_(format),
|
||||
max_cache_size_(max_buffer_size / 100),
|
||||
max_buffer_size_(max_buffer_size) {
|
||||
cache_.reserve(128);
|
||||
}
|
||||
|
||||
Status MemForwardStore::Open() {
|
||||
arrow::FieldVector fields;
|
||||
auto status = ConvertCollectionSchemaToArrowFields(schema_, &fields);
|
||||
if (!status.ok()) {
|
||||
return Status::InternalError("convert schema to arrow fields failed ",
|
||||
status.ToString());
|
||||
}
|
||||
physic_schema_ = arrow::schema(fields);
|
||||
// Initialize file writer
|
||||
writer_ = ChunkedFileWriter::Open(path_, physic_schema_, format_);
|
||||
return Status::OK();
|
||||
}
|
||||
|
||||
RecordBatchBuilderPtr MemForwardStore::createBuilder() {
|
||||
auto result = arrow::RecordBatchBuilder::Make(physic_schema_,
|
||||
arrow::default_memory_pool());
|
||||
if (!result.ok()) {
|
||||
LOG_ERROR("failed to create RecordBatchBuilder: %s",
|
||||
result.status().ToString().c_str());
|
||||
return nullptr;
|
||||
}
|
||||
return std::move(result.ValueOrDie());
|
||||
}
|
||||
|
||||
|
||||
bool MemForwardStore::validate(const std::vector<std::string> &columns) const {
|
||||
if (columns.empty()) {
|
||||
LOG_ERROR("empty columns");
|
||||
return false;
|
||||
}
|
||||
for (auto &column : columns) {
|
||||
if (column == LOCAL_ROW_ID) {
|
||||
continue;
|
||||
}
|
||||
if (physic_schema_->GetFieldIndex(column) == -1) {
|
||||
LOG_ERROR("validate failed. unknown column: %s", column.c_str());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
// Notice: This function just convert the docs to arrow::ArrayBuilder, not clean
|
||||
// the cache_.
|
||||
arrow::Status MemForwardStore::convertToBuilder(
|
||||
RecordBatchBuilderPtr &rb_builder) {
|
||||
for (const auto &doc : cache_) {
|
||||
auto &fields = physic_schema_->fields();
|
||||
|
||||
// global doc_id
|
||||
auto gid_builder =
|
||||
dynamic_cast<arrow::UInt64Builder *>(rb_builder->GetField(0));
|
||||
ARROW_RETURN_NOT_OK(gid_builder->Append(doc.doc_id()));
|
||||
|
||||
// user id(pk)
|
||||
auto uid_builder =
|
||||
dynamic_cast<arrow::StringBuilder *>(rb_builder->GetField(1));
|
||||
ARROW_RETURN_NOT_OK(uid_builder->Append(doc.pk()));
|
||||
|
||||
// other fields
|
||||
for (size_t idx = 2; idx < fields.size(); ++idx) {
|
||||
auto field = fields[idx];
|
||||
auto builder = rb_builder->GetField(idx);
|
||||
ARROW_RETURN_NOT_OK(AppendFieldValueToBuilder(doc, field, builder));
|
||||
}
|
||||
}
|
||||
return arrow::Status::OK();
|
||||
}
|
||||
|
||||
Status MemForwardStore::insert(const Doc &doc) {
|
||||
std::lock_guard lock(cache_mtx_);
|
||||
cache_.emplace_back(doc);
|
||||
num_rows_++;
|
||||
auto doc_bytes = doc.memory_usage();
|
||||
total_cache_bytes_ = total_cache_bytes_ + (uint32_t)doc_bytes;
|
||||
if (total_cache_bytes_ < max_cache_size_) {
|
||||
return Status::OK();
|
||||
}
|
||||
// Flush cache when it reaches max size
|
||||
auto rb_builder = createBuilder();
|
||||
auto status = convertToBuilder(rb_builder);
|
||||
if (!status.ok()) {
|
||||
return Status::InternalError("convertToBuilder error: ", status.ToString());
|
||||
}
|
||||
auto result = rb_builder->Flush(false);
|
||||
if (!result.ok()) {
|
||||
return Status::InternalError("flush error: ", result.status().ToString());
|
||||
}
|
||||
auto batch = result.ValueOrDie();
|
||||
int64_t rb_size = MemorySize(*batch);
|
||||
batches_.push_back(batch);
|
||||
|
||||
total_rb_bytes_ = total_rb_bytes_ + (uint32_t)rb_size;
|
||||
cache_.clear();
|
||||
total_cache_bytes_ = 0;
|
||||
|
||||
return Status::OK();
|
||||
}
|
||||
|
||||
arrow::Result<RecordBatchPtr> MemForwardStore::convertToRecordBatch() {
|
||||
auto rb_builder = createBuilder();
|
||||
ARROW_RETURN_NOT_OK(convertToBuilder(rb_builder));
|
||||
ARROW_ASSIGN_OR_RAISE(auto batch, rb_builder->Flush(false));
|
||||
return batch;
|
||||
}
|
||||
|
||||
arrow::Result<TablePtr> MemForwardStore::convertToTable(
|
||||
const std::vector<std::string> &columns, const std::vector<int> &indices) {
|
||||
std::shared_ptr<arrow::RecordBatch> batch;
|
||||
ARROW_ASSIGN_OR_RAISE(batch, convertToRecordBatch());
|
||||
std::vector<std::shared_ptr<arrow::RecordBatch>> all_batches = batches_;
|
||||
if (batch->num_rows() > 0) {
|
||||
all_batches.push_back(batch);
|
||||
}
|
||||
|
||||
if (all_batches.empty()) {
|
||||
return arrow::Table::MakeEmpty(physic_schema_, nullptr);
|
||||
}
|
||||
|
||||
// Combine all batches into a single table
|
||||
std::shared_ptr<arrow::Table> combined_table;
|
||||
ARROW_ASSIGN_OR_RAISE(combined_table,
|
||||
arrow::Table::FromRecordBatches(all_batches));
|
||||
|
||||
std::shared_ptr<arrow::Table> filtered_table = combined_table;
|
||||
if (!indices.empty()) {
|
||||
// Filter rows by indices if provided
|
||||
std::shared_ptr<arrow::Array> index_array;
|
||||
arrow::Int32Builder builder;
|
||||
ARROW_RETURN_NOT_OK(builder.AppendValues(indices));
|
||||
ARROW_RETURN_NOT_OK(builder.Finish(&index_array));
|
||||
|
||||
arrow::Datum input_datum(combined_table);
|
||||
arrow::Datum index_datum(index_array);
|
||||
|
||||
arrow::compute::ExecContext ctx;
|
||||
arrow::Datum result_datum;
|
||||
ARROW_ASSIGN_OR_RAISE(
|
||||
result_datum,
|
||||
arrow::compute::Take(input_datum, index_datum,
|
||||
arrow::compute::TakeOptions::Defaults(), &ctx));
|
||||
filtered_table = result_datum.table();
|
||||
}
|
||||
|
||||
std::shared_ptr<arrow::Table> selected_table = filtered_table;
|
||||
if (!columns.empty()) {
|
||||
// Select only specified columns
|
||||
std::vector<int> column_indices;
|
||||
for (const auto &column_name : columns) {
|
||||
if (column_name == LOCAL_ROW_ID) continue;
|
||||
int index = filtered_table->schema()->GetFieldIndex(column_name);
|
||||
if (index != -1) {
|
||||
column_indices.push_back(index);
|
||||
}
|
||||
}
|
||||
|
||||
if (!column_indices.empty()) {
|
||||
ARROW_ASSIGN_OR_RAISE(selected_table,
|
||||
filtered_table->SelectColumns(column_indices));
|
||||
}
|
||||
}
|
||||
return selected_table;
|
||||
}
|
||||
|
||||
Status MemForwardStore::flush() {
|
||||
std::lock_guard lock(cache_mtx_);
|
||||
|
||||
if (cache_.empty() && batches_.empty()) {
|
||||
return Status::OK();
|
||||
}
|
||||
|
||||
auto result = convertToRecordBatch();
|
||||
if (!result.ok()) {
|
||||
return Status::InternalError("failed to convert cache to RecordBatch: ",
|
||||
result.status().ToString());
|
||||
}
|
||||
|
||||
auto cache_batch = result.ValueOrDie();
|
||||
if (cache_batch->num_rows() > 0) {
|
||||
batches_.push_back(cache_batch);
|
||||
cache_.clear();
|
||||
}
|
||||
|
||||
bool has_incr = false;
|
||||
size_t start_index = flushed_batches_;
|
||||
|
||||
while (start_index < batches_.size()) {
|
||||
std::vector<std::shared_ptr<arrow::RecordBatch>> batches_to_merge;
|
||||
int64_t total_rows = 0;
|
||||
size_t end_index = start_index;
|
||||
|
||||
while (end_index < batches_.size()) {
|
||||
auto ¤t_batch = batches_[end_index];
|
||||
int64_t current_rows = current_batch->num_rows();
|
||||
|
||||
if (current_rows >= kMaxRecordBatchNumRows) {
|
||||
if (batches_to_merge.empty()) {
|
||||
batches_to_merge.push_back(current_batch);
|
||||
end_index++;
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
if (!batches_to_merge.empty() &&
|
||||
total_rows + current_rows > kMaxRecordBatchNumRows) {
|
||||
break;
|
||||
}
|
||||
|
||||
batches_to_merge.push_back(current_batch);
|
||||
total_rows += current_rows;
|
||||
end_index++;
|
||||
}
|
||||
|
||||
if (!batches_to_merge.empty()) {
|
||||
std::shared_ptr<arrow::RecordBatch> batch_to_write;
|
||||
|
||||
if (batches_to_merge.size() == 1) {
|
||||
batch_to_write = batches_to_merge[0];
|
||||
} else {
|
||||
std::shared_ptr<arrow::Table> table;
|
||||
auto status =
|
||||
arrow::Table::FromRecordBatches(batches_to_merge).Value(&table);
|
||||
if (!status.ok()) {
|
||||
return Status::InternalError("failed to merge batches: ",
|
||||
status.ToString());
|
||||
}
|
||||
|
||||
result = table->CombineChunksToBatch();
|
||||
if (!result.ok()) {
|
||||
return Status::InternalError("failed to combine chunks: ",
|
||||
result.status().ToString());
|
||||
}
|
||||
batch_to_write = result.ValueOrDie();
|
||||
}
|
||||
|
||||
auto status = writer_->Write(*batch_to_write);
|
||||
if (!status.ok()) {
|
||||
return Status::InternalError("failed to write RecordBatch to file: ",
|
||||
status.ToString());
|
||||
}
|
||||
|
||||
flushed_batches_ = end_index;
|
||||
has_incr = true;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
|
||||
start_index = end_index;
|
||||
}
|
||||
|
||||
if (has_incr) {
|
||||
LOG_INFO("successfully flushed %u batches to %s", flushed_batches_,
|
||||
path_.c_str());
|
||||
}
|
||||
return Status::OK();
|
||||
}
|
||||
|
||||
Status MemForwardStore::close() {
|
||||
if (!cache_.empty() || !batches_.empty()) {
|
||||
flush();
|
||||
}
|
||||
if (writer_) {
|
||||
auto status = writer_->Close();
|
||||
if (!status.ok()) {
|
||||
LOG_WARN("failed to close writer: %s", status.ToString().c_str());
|
||||
}
|
||||
writer_.reset();
|
||||
}
|
||||
batches_.clear();
|
||||
cache_.clear();
|
||||
return Status::OK();
|
||||
}
|
||||
|
||||
TablePtr MemForwardStore::get_table() {
|
||||
std::lock_guard lock(cache_mtx_);
|
||||
std::shared_ptr<arrow::RecordBatch> batch =
|
||||
convertToRecordBatch().ValueOrDie();
|
||||
std::vector<std::shared_ptr<arrow::RecordBatch>> all_batches = batches_;
|
||||
if (batch->num_rows() > 0) {
|
||||
all_batches.push_back(batch);
|
||||
}
|
||||
|
||||
if (all_batches.empty()) {
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
return arrow::Table::FromRecordBatches(all_batches).ValueOrDie();
|
||||
}
|
||||
|
||||
TablePtr MemForwardStore::fetch(const std::vector<std::string> &columns,
|
||||
const std::vector<int> &indices) {
|
||||
std::lock_guard lock(cache_mtx_);
|
||||
|
||||
if (!validate(columns)) {
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
if (indices.empty()) {
|
||||
arrow::ArrayVector empty_arrays;
|
||||
auto fields = SelectFields(physic_schema_, columns);
|
||||
for (const auto &field : fields) {
|
||||
empty_arrays.push_back(arrow::MakeEmptyArray(field->type()).ValueOrDie());
|
||||
}
|
||||
return arrow::Table::Make(std::make_shared<arrow::Schema>(fields),
|
||||
empty_arrays, 0);
|
||||
}
|
||||
|
||||
bool need_local_doc_id = false;
|
||||
std::vector<std::string> data_columns;
|
||||
std::vector<bool> is_local_row_id(columns.size(), false);
|
||||
|
||||
for (size_t i = 0; i < columns.size(); ++i) {
|
||||
if (columns[i] == LOCAL_ROW_ID) {
|
||||
need_local_doc_id = true;
|
||||
is_local_row_id[i] = true;
|
||||
} else {
|
||||
data_columns.push_back(columns[i]);
|
||||
}
|
||||
}
|
||||
|
||||
auto result = convertToTable(data_columns, indices);
|
||||
if (!result.ok()) {
|
||||
LOG_ERROR("failed to convert to table: %s",
|
||||
result.status().ToString().c_str());
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
auto data_table = result.ValueOrDie();
|
||||
if (!need_local_doc_id) {
|
||||
return data_table;
|
||||
}
|
||||
|
||||
std::vector<std::shared_ptr<arrow::ChunkedArray>> result_columns(
|
||||
columns.size());
|
||||
std::vector<std::shared_ptr<arrow::Field>> result_fields(columns.size());
|
||||
|
||||
size_t data_col_idx = 0;
|
||||
for (size_t i = 0; i < columns.size(); ++i) {
|
||||
if (is_local_row_id[i]) {
|
||||
continue;
|
||||
}
|
||||
|
||||
result_columns[i] = data_table->column(data_col_idx);
|
||||
result_fields[i] = data_table->schema()->field(data_col_idx);
|
||||
data_col_idx++;
|
||||
}
|
||||
|
||||
if (need_local_doc_id) {
|
||||
std::shared_ptr<arrow::Array> rowid_array;
|
||||
arrow::UInt64Builder builder;
|
||||
|
||||
std::vector<uint64_t> indices_i64(indices.begin(), indices.end());
|
||||
auto status = builder.AppendValues(indices_i64);
|
||||
|
||||
if (!status.ok()) {
|
||||
LOG_ERROR("failed to append rowid values: %s", status.ToString().c_str());
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
status = builder.Finish(&rowid_array);
|
||||
if (!status.ok()) {
|
||||
LOG_ERROR("failed to finish rowid array: %s", status.ToString().c_str());
|
||||
return nullptr;
|
||||
}
|
||||
auto rowid_chunked = std::make_shared<arrow::ChunkedArray>(rowid_array);
|
||||
|
||||
for (size_t i = 0; i < columns.size(); ++i) {
|
||||
if (is_local_row_id[i]) {
|
||||
result_columns[i] = rowid_chunked;
|
||||
result_fields[i] = arrow::field(LOCAL_ROW_ID, arrow::uint64());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
auto new_schema = arrow::schema(result_fields);
|
||||
return arrow::Table::Make(new_schema, result_columns, data_table->num_rows());
|
||||
}
|
||||
|
||||
ExecBatchPtr MemForwardStore::fetch(const std::vector<std::string> &columns,
|
||||
int index) {
|
||||
std::lock_guard lock(cache_mtx_);
|
||||
|
||||
if (!validate(columns)) {
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
auto result = convertToTable(columns, std::vector<int>{index});
|
||||
if (!result.ok()) {
|
||||
LOG_ERROR("failed to convert to table: %s",
|
||||
result.status().ToString().c_str());
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
auto table = result.ValueOrDie();
|
||||
|
||||
// Extract scalars
|
||||
std::vector<arrow::Datum> scalars;
|
||||
scalars.reserve(columns.size());
|
||||
for (const auto &column : columns) {
|
||||
const auto &array = table->GetColumnByName(column);
|
||||
auto scalar_result = array->GetScalar(0);
|
||||
if (!scalar_result.ok()) {
|
||||
LOG_ERROR("failed to get column %s scalar from array: %s", column.c_str(),
|
||||
scalar_result.status().ToString().c_str());
|
||||
return nullptr;
|
||||
}
|
||||
scalars.emplace_back(std::move(scalar_result.ValueOrDie()));
|
||||
}
|
||||
|
||||
return std::make_shared<arrow::ExecBatch>(std::move(scalars), 1);
|
||||
}
|
||||
|
||||
RecordBatchReaderPtr MemForwardStore::scan(
|
||||
const std::vector<std::string> &columns) {
|
||||
std::lock_guard lock(cache_mtx_);
|
||||
|
||||
if (!validate(columns)) {
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
auto result = convertToTable(columns, {});
|
||||
if (!result.ok()) {
|
||||
LOG_ERROR("failed to convert to table: %s",
|
||||
result.status().ToString().c_str());
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
return std::make_shared<arrow::TableBatchReader>(result.ValueOrDie());
|
||||
}
|
||||
|
||||
} // namespace zvec
|
||||
@@ -0,0 +1,193 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
#pragma once
|
||||
|
||||
#include <iostream>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <arrow/compute/api.h>
|
||||
#include <arrow/table_builder.h>
|
||||
#include <arrow/util/async_generator.h>
|
||||
#include "db/common/status.h"
|
||||
#include "db/index/common/doc.h"
|
||||
#include "base_forward_store.h"
|
||||
#include "chunked_file_writer.h"
|
||||
#include "store_helper.h"
|
||||
|
||||
namespace zvec {
|
||||
|
||||
/// MemForwardStore implements a forward store that keeps data in memory
|
||||
/// and can flush data to disk when needed.
|
||||
class MemForwardStore : public BaseForwardStore {
|
||||
public:
|
||||
/// Pointer type for MemForwardStore instances
|
||||
using Ptr = std::shared_ptr<MemForwardStore>;
|
||||
|
||||
/// Constructor that initializes the store with collection schema and settings
|
||||
/// \param collection_schema The schema for the collection
|
||||
/// \param path The path where data will be stored
|
||||
/// \param format The file format for persistence
|
||||
/// \param max_cache_rows Maximum number of rows to keep in cache
|
||||
/// \param max_rows Maximum number of rows allowed in the store
|
||||
MemForwardStore(const std::shared_ptr<CollectionSchema> &collection_schema,
|
||||
const std::string &path, const FileFormat format,
|
||||
const uint32_t max_buffer_size = 100 * 1024 * 1024);
|
||||
|
||||
virtual ~MemForwardStore() {
|
||||
close();
|
||||
}
|
||||
|
||||
/// Check if the store is full
|
||||
/// \return true if the store has reached its maximum capacity
|
||||
bool is_full() {
|
||||
return total_bytes() >= max_buffer_size_;
|
||||
}
|
||||
|
||||
/// Open the store
|
||||
/// \return 0 on success, non-zero on failure
|
||||
Status Open() override;
|
||||
|
||||
/// Insert a document into the store
|
||||
/// \param doc The document to insert
|
||||
/// \return 0 on success, non-zero on failure
|
||||
Status insert(const Doc &doc);
|
||||
|
||||
/// Flush cached data to disk
|
||||
/// \return 0 on success, non-zero on failure
|
||||
Status flush();
|
||||
|
||||
/// Close the store and flush any remaining data
|
||||
/// \return 0 on success, non-zero on failure
|
||||
Status close();
|
||||
|
||||
public:
|
||||
/// Get the path of the store
|
||||
/// \return The path where data is stored
|
||||
const std::string path() const {
|
||||
return path_;
|
||||
}
|
||||
|
||||
/// Get the total bytes of the store
|
||||
uint32_t total_bytes() const {
|
||||
return total_cache_bytes_ + total_rb_bytes_;
|
||||
}
|
||||
|
||||
/// Get the total number of rows in the store
|
||||
uint32_t num_rows() const {
|
||||
return num_rows_;
|
||||
}
|
||||
|
||||
public:
|
||||
/// Fetch specific columns and row indices from the data source
|
||||
/// \param columns The list of column names to fetch
|
||||
/// \param indices The list of row indices to fetch
|
||||
/// \return A table containing the requested data or nullptr on failure
|
||||
TablePtr fetch(const std::vector<std::string> &columns,
|
||||
const std::vector<int> &indices) override;
|
||||
|
||||
/// Fetch specific columns and row indices from the data source
|
||||
/// \param columns The list of column names to fetch
|
||||
/// \param index The row index to fetch
|
||||
/// \return An ExecBatch containing the requested data or nullptr on failure
|
||||
ExecBatchPtr fetch(const std::vector<std::string> &columns,
|
||||
int index) override;
|
||||
|
||||
/// Scan specified columns from the data source
|
||||
/// \param columns The list of column names to scan
|
||||
/// \return A RecordBatchReader for streaming the data or nullptr on failure
|
||||
RecordBatchReaderPtr scan(const std::vector<std::string> &columns) override;
|
||||
|
||||
/// Get the physical schema of the file
|
||||
/// \return A shared pointer to the arrow schema representing the physical
|
||||
/// structure of the data
|
||||
const std::shared_ptr<arrow::Schema> physic_schema() const override {
|
||||
return physic_schema_;
|
||||
}
|
||||
|
||||
TablePtr get_table() override;
|
||||
|
||||
private:
|
||||
/// Create a RecordBatchBuilder for this store
|
||||
/// \return A new RecordBatchBuilder
|
||||
RecordBatchBuilderPtr createBuilder();
|
||||
|
||||
/// Convert internal data to a RecordBatch
|
||||
/// \return A Result containing the RecordBatch or an error status
|
||||
arrow::Result<RecordBatchPtr> convertToRecordBatch();
|
||||
|
||||
/// Convert internal data to a Table
|
||||
/// \param columns The list of column names to include
|
||||
/// \param indices The list of row indices to include
|
||||
/// \return A Result containing the Table or an error status
|
||||
arrow::Result<TablePtr> convertToTable(
|
||||
const std::vector<std::string> &columns, const std::vector<int> &indices);
|
||||
|
||||
/// Convert internal data to a RecordBatchBuilder
|
||||
/// \param builder The builder to populate
|
||||
/// \return arrow::Status indicating success or failure
|
||||
arrow::Status convertToBuilder(RecordBatchBuilderPtr &builder);
|
||||
|
||||
/// Validate that the requested columns exist in the schema
|
||||
/// \param columns The list of column names to validate
|
||||
/// \return true if all columns are valid, false otherwise
|
||||
bool validate(const std::vector<std::string> &columns) const;
|
||||
|
||||
private:
|
||||
/// Mutex to protect cache access
|
||||
std::mutex cache_mtx_;
|
||||
|
||||
/// Cache of documents waiting to be flushed
|
||||
std::vector<Doc> cache_;
|
||||
|
||||
/// Batches of data that have been flushed
|
||||
std::vector<RecordBatchPtr> batches_;
|
||||
|
||||
/// Collection schema
|
||||
std::shared_ptr<CollectionSchema> schema_;
|
||||
|
||||
/// Physical schema
|
||||
std::shared_ptr<arrow::Schema> physic_schema_;
|
||||
|
||||
/// Total RecordBatch bytes in the store
|
||||
uint32_t total_rb_bytes_{0};
|
||||
|
||||
/// Total cache doc bytes
|
||||
uint32_t total_cache_bytes_{0};
|
||||
|
||||
/// Total number of rows in the store
|
||||
uint32_t num_rows_{0};
|
||||
|
||||
/// Path where data is stored
|
||||
std::string path_;
|
||||
|
||||
/// File format for persistence
|
||||
FileFormat format_;
|
||||
|
||||
/// Number of batches that have been flushed
|
||||
uint32_t flushed_batches_{0};
|
||||
|
||||
/// Writer for chunked files
|
||||
ChunkedFileWriter::Ptr writer_;
|
||||
|
||||
|
||||
/// Maximum size of cache, default 1MB
|
||||
uint32_t max_cache_size_{1048576};
|
||||
|
||||
/// Maximum size of the buffer, default 100MB
|
||||
uint32_t max_buffer_size_{104857600};
|
||||
};
|
||||
|
||||
} // namespace zvec
|
||||
@@ -0,0 +1,571 @@
|
||||
// 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 "mmap_forward_store.h"
|
||||
#include <memory>
|
||||
#include <ailego/logger/logger.h>
|
||||
#include <arrow/acero/options.h>
|
||||
#include <arrow/compute/api.h>
|
||||
#include <arrow/datum.h>
|
||||
#include <arrow/filesystem/localfs.h>
|
||||
#include "storage/base_forward_store.h"
|
||||
#include "lazy_record_batch_reader.h"
|
||||
|
||||
|
||||
namespace zvec {
|
||||
|
||||
MmapForwardStore::MmapForwardStore(const std::string &uri) : file_path_(uri) {}
|
||||
|
||||
Status MmapForwardStore::Open() {
|
||||
std::string uri = file_path_;
|
||||
auto status = CreateRandomAccessFileByUri(uri, &file_, &file_path_);
|
||||
if (!status.ok()) {
|
||||
LOG_ERROR("Failed to create random access uri: %s : %s", uri.c_str(),
|
||||
status.ToString().c_str());
|
||||
return Status::InvalidArgument(status.ToString());
|
||||
}
|
||||
format_ = InferFileFormat(file_path_);
|
||||
switch (format_) {
|
||||
case FileFormat::PARQUET: {
|
||||
status = OpenParquet(file_);
|
||||
if (!status.ok()) {
|
||||
LOG_ERROR("Failed to open parquet file: %s : %s", file_path_.c_str(),
|
||||
status.ToString().c_str());
|
||||
return Status::InternalError(status.ToString());
|
||||
}
|
||||
break;
|
||||
}
|
||||
case FileFormat::IPC: {
|
||||
status = OpenIPC(file_);
|
||||
if (!status.ok()) {
|
||||
LOG_ERROR("Failed to open ipc file: %s : %s", file_path_.c_str(),
|
||||
status.ToString().c_str());
|
||||
return Status::InternalError(status.ToString());
|
||||
}
|
||||
break;
|
||||
}
|
||||
default:
|
||||
LOG_ERROR("Unknown file format: %s", uri.c_str());
|
||||
return Status::InvalidArgument("Unknown file format: ", uri);
|
||||
break;
|
||||
}
|
||||
return Status::OK();
|
||||
}
|
||||
|
||||
arrow::Status MmapForwardStore::OpenParquet(
|
||||
const std::shared_ptr<arrow::io::RandomAccessFile> &file) {
|
||||
auto parquet_file_reader = parquet::ParquetFileReader::Open(file);
|
||||
ARROW_RETURN_NOT_OK(parquet::arrow::FileReader::Make(
|
||||
arrow::default_memory_pool(), std::move(parquet_file_reader),
|
||||
&parquet_reader_));
|
||||
|
||||
auto parquet_metadata = parquet_reader_->parquet_reader()->metadata();
|
||||
num_rows_ = parquet_metadata->num_rows();
|
||||
num_row_groups_ = parquet_metadata->num_row_groups();
|
||||
|
||||
// Initialize row group offsets and row counts
|
||||
int64_t offset = 0;
|
||||
for (int64_t rg = 0; rg < num_row_groups_; ++rg) {
|
||||
auto row_group_metadata = parquet_metadata->RowGroup(rg);
|
||||
int64_t num_rows_in_group = row_group_metadata->num_rows();
|
||||
row_group_row_nums_.push_back(num_rows_in_group);
|
||||
row_group_offsets_.push_back(offset);
|
||||
offset += num_rows_in_group;
|
||||
}
|
||||
|
||||
ARROW_RETURN_NOT_OK(parquet_reader_->GetSchema(&physic_schema_));
|
||||
|
||||
LOG_INFO("Opened Parquet with %lld rows, %d cols, %d row groups",
|
||||
static_cast<long long>(num_rows_), physic_schema_->num_fields(),
|
||||
parquet_metadata->num_row_groups());
|
||||
|
||||
return arrow::Status::OK();
|
||||
}
|
||||
|
||||
arrow::Status MmapForwardStore::OpenIPC(
|
||||
const std::shared_ptr<arrow::io::RandomAccessFile> &file) {
|
||||
std::shared_ptr<arrow::ipc::RecordBatchFileReader> reader;
|
||||
arrow::Result<std::shared_ptr<arrow::ipc::RecordBatchFileReader>> result =
|
||||
arrow::ipc::RecordBatchFileReader::Open(file);
|
||||
ARROW_RETURN_NOT_OK(result.status());
|
||||
reader = std::move(result).ValueOrDie();
|
||||
ipc_file_reader_ = std::move(reader);
|
||||
PARQUET_ASSIGN_OR_THROW(table_, ipc_file_reader_->ToTable());
|
||||
|
||||
if (table_->num_columns() == 0) {
|
||||
return arrow::Status::Invalid("IPC file has no columns");
|
||||
}
|
||||
|
||||
auto chunked_array = table_->column(0);
|
||||
for (int i = 0; i < chunked_array->num_chunks(); ++i) {
|
||||
auto chunk = chunked_array->chunk(i);
|
||||
|
||||
if (chunk->length() == 0) {
|
||||
return arrow::Status::Invalid("Encountered empty chunk at index %d", i);
|
||||
}
|
||||
|
||||
chunk_index_map_.emplace_back(num_rows_, num_rows_ + chunk->length() - 1);
|
||||
num_rows_ += chunk->length();
|
||||
|
||||
// Check if all chunks have the same size except possibly the last one
|
||||
if (fixed_batch_size_ == -1) {
|
||||
fixed_batch_size_ = chunk->length();
|
||||
} else if (fixed_batch_size_ != chunk->length()) {
|
||||
if (i != chunked_array->num_chunks() - 1) {
|
||||
is_fixed_batch_size_ = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
physic_schema_ = ipc_file_reader_->schema();
|
||||
LOG_INFO(
|
||||
"Opened IPC with %lld rows, %d cols, %d chunks, is_fixed_batch_size[%d] "
|
||||
"fixed_batch_size[%lld] physic_schema: %s",
|
||||
static_cast<long long>(num_rows_), physic_schema_->num_fields(),
|
||||
chunked_array->num_chunks(), is_fixed_batch_size_,
|
||||
static_cast<long long>(fixed_batch_size_),
|
||||
physic_schema_->ToString().c_str());
|
||||
|
||||
return arrow::Status::OK();
|
||||
}
|
||||
|
||||
bool MmapForwardStore::validate(const std::vector<std::string> &columns) const {
|
||||
if (columns.empty()) {
|
||||
LOG_ERROR("Empty columns");
|
||||
return false;
|
||||
}
|
||||
for (auto &column : columns) {
|
||||
if (column == LOCAL_ROW_ID) {
|
||||
continue;
|
||||
}
|
||||
if (physic_schema_->GetFieldIndex(column) == -1) {
|
||||
LOG_ERROR("Validate failed. unknown column: %s", column.c_str());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
RecordBatchReaderPtr MmapForwardStore::ScanParquet(
|
||||
const std::vector<std::string> &columns) {
|
||||
// Create a new parquet reader for scanning
|
||||
std::unique_ptr<parquet::arrow::FileReader> parquet_reader;
|
||||
auto parquet_file_reader = parquet::ParquetFileReader::Open(file_);
|
||||
auto status = parquet::arrow::FileReader::Make(arrow::default_memory_pool(),
|
||||
std::move(parquet_file_reader),
|
||||
&parquet_reader);
|
||||
if (!status.ok()) {
|
||||
LOG_ERROR("Failed to create parquet reader: %s", status.message().c_str());
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
auto rb_reader = std::make_shared<ParquetRecordBatchReader>(
|
||||
parquet_reader, columns, physic_schema_, file_path_, false);
|
||||
return rb_reader;
|
||||
}
|
||||
|
||||
RecordBatchReaderPtr MmapForwardStore::ScanIPC(
|
||||
const std::vector<std::string> &columns) {
|
||||
std::vector<int> col_indices;
|
||||
for (auto &column : columns) {
|
||||
int idx = physic_schema_->GetFieldIndex(column);
|
||||
if (idx == -1) continue;
|
||||
col_indices.push_back(idx);
|
||||
}
|
||||
|
||||
auto result = table_->SelectColumns(col_indices);
|
||||
if (!result.ok()) {
|
||||
LOG_ERROR("Failed to select columns: %s",
|
||||
result.status().message().c_str());
|
||||
return nullptr;
|
||||
}
|
||||
auto sub_table = std::move(result).ValueOrDie();
|
||||
|
||||
return std::make_shared<arrow::TableBatchReader>(sub_table);
|
||||
}
|
||||
|
||||
TablePtr MmapForwardStore::FetchParquet(const std::vector<std::string> &columns,
|
||||
const std::vector<int> &indices) {
|
||||
bool need_local_doc_id = false;
|
||||
std::vector<int> col_indices;
|
||||
std::vector<int> data_column_positions;
|
||||
|
||||
for (size_t i = 0; i < columns.size(); ++i) {
|
||||
if (columns[i] == LOCAL_ROW_ID) {
|
||||
need_local_doc_id = true;
|
||||
} else {
|
||||
int idx = physic_schema_->GetFieldIndex(columns[i]);
|
||||
if (idx == -1) return nullptr;
|
||||
col_indices.push_back(idx);
|
||||
data_column_positions.push_back(static_cast<int>(i));
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<std::vector<std::pair<int, std::shared_ptr<arrow::Scalar>>>>
|
||||
sorted_scalars(col_indices.size());
|
||||
std::vector<std::pair<int, int64_t>> local_doc_id_pairs;
|
||||
|
||||
// Group by row group, but keep track of original output position
|
||||
std::unordered_map<int, std::vector<std::pair<int, uint64_t>>> rg_to_local;
|
||||
int output_row = 0;
|
||||
for (int global_row : indices) {
|
||||
if (global_row < 0 || global_row >= num_rows_) return nullptr;
|
||||
int rg_id = FindRowGroupForRow(global_row);
|
||||
int64_t offset = GetRowGroupOffset(rg_id);
|
||||
uint64_t local_in_rg = global_row - offset;
|
||||
rg_to_local[rg_id].emplace_back(output_row, local_in_rg);
|
||||
if (need_local_doc_id) {
|
||||
local_doc_id_pairs.emplace_back(output_row, global_row);
|
||||
}
|
||||
++output_row;
|
||||
}
|
||||
|
||||
// Read each row group and extract scalars at required positions
|
||||
for (const auto &[rg_id, pairs] : rg_to_local) {
|
||||
std::shared_ptr<arrow::Table> rg_table;
|
||||
auto status =
|
||||
parquet_reader_->RowGroup(rg_id)->ReadTable(col_indices, &rg_table);
|
||||
if (!status.ok()) {
|
||||
LOG_ERROR("Failed to read row group %d", rg_id);
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
// Concatenate chunks for faster random access
|
||||
std::vector<std::shared_ptr<arrow::Array>> flat_columns;
|
||||
for (const auto &col : rg_table->columns()) {
|
||||
auto flat_result =
|
||||
arrow::Concatenate(col->chunks(), arrow::default_memory_pool());
|
||||
if (!flat_result.ok()) {
|
||||
LOG_ERROR("Failed to concatenate chunks for rg {%d} status:%s", rg_id,
|
||||
flat_result.status().message().c_str());
|
||||
return nullptr;
|
||||
}
|
||||
flat_columns.push_back(flat_result.ValueOrDie());
|
||||
}
|
||||
|
||||
// Extract scalars for this RG
|
||||
for (size_t i = 0; i < col_indices.size(); ++i) {
|
||||
auto &dst = sorted_scalars[i];
|
||||
const auto &array = flat_columns[i];
|
||||
|
||||
for (const auto &[output_row_tmp, local_idx] : pairs) {
|
||||
auto scalar_result = array->GetScalar(local_idx);
|
||||
if (!scalar_result.ok()) {
|
||||
LOG_ERROR("Failed to get scalar for row %zu status: %s",
|
||||
(size_t)local_idx,
|
||||
scalar_result.status().ToString().c_str());
|
||||
}
|
||||
dst.emplace_back(output_row_tmp, scalar_result.ValueOrDie());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<std::shared_ptr<arrow::Array>> result_arrays(columns.size());
|
||||
|
||||
for (size_t i = 0; i < sorted_scalars.size(); ++i) {
|
||||
auto &vec = sorted_scalars[i];
|
||||
std::sort(vec.begin(), vec.end());
|
||||
std::vector<std::shared_ptr<arrow::Scalar>> ordered_scalars;
|
||||
ordered_scalars.reserve(vec.size());
|
||||
for (auto &p : vec) {
|
||||
ordered_scalars.push_back(std::move(p.second));
|
||||
}
|
||||
|
||||
std::shared_ptr<arrow::Array> arr;
|
||||
auto status = ConvertScalarVectorToArrayByType(ordered_scalars, &arr);
|
||||
if (!status.ok()) {
|
||||
LOG_ERROR("ConvertScalarVectorToArrayByType failed: %s",
|
||||
status.message().c_str());
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
int position = data_column_positions[i];
|
||||
result_arrays[position] = std::move(arr);
|
||||
}
|
||||
|
||||
if (need_local_doc_id) {
|
||||
std::sort(local_doc_id_pairs.begin(), local_doc_id_pairs.end());
|
||||
std::vector<uint64_t> values;
|
||||
values.reserve(local_doc_id_pairs.size());
|
||||
for (const auto &p : local_doc_id_pairs) {
|
||||
values.push_back(p.second);
|
||||
}
|
||||
|
||||
// Create UInt64Array
|
||||
auto buffer_result = arrow::AllocateBuffer(values.size() * sizeof(uint64_t),
|
||||
arrow::default_memory_pool());
|
||||
if (!buffer_result.ok()) return nullptr;
|
||||
auto buffer = std::move(buffer_result.ValueOrDie());
|
||||
std::memcpy(buffer->mutable_data(), values.data(),
|
||||
values.size() * sizeof(uint64_t));
|
||||
|
||||
std::vector<std::shared_ptr<arrow::Buffer>> buffers;
|
||||
buffers.push_back(nullptr); // no null bitmap
|
||||
buffers.push_back(std::shared_ptr<arrow::Buffer>(buffer.release()));
|
||||
|
||||
auto data = arrow::ArrayData::Make(arrow::uint64(),
|
||||
static_cast<uint64_t>(values.size()),
|
||||
std::move(buffers), /*null_count=*/0);
|
||||
|
||||
for (size_t i = 0; i < columns.size(); ++i) {
|
||||
if (columns[i] == LOCAL_ROW_ID) {
|
||||
result_arrays[i] = std::make_shared<arrow::UInt64Array>(data);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<std::shared_ptr<arrow::Field>> selected_fields;
|
||||
for (const auto &col : columns) {
|
||||
if (col == LOCAL_ROW_ID) {
|
||||
selected_fields.push_back(arrow::field(LOCAL_ROW_ID, arrow::uint64()));
|
||||
} else {
|
||||
selected_fields.push_back(physic_schema_->GetFieldByName(col));
|
||||
}
|
||||
}
|
||||
|
||||
auto out_schema = std::make_shared<arrow::Schema>(selected_fields);
|
||||
|
||||
std::vector<std::shared_ptr<arrow::ChunkedArray>> chunks;
|
||||
chunks.reserve(result_arrays.size());
|
||||
for (auto &arr : result_arrays) {
|
||||
chunks.emplace_back(std::make_shared<arrow::ChunkedArray>(arr));
|
||||
}
|
||||
|
||||
return arrow::Table::Make(out_schema, chunks,
|
||||
static_cast<int64_t>(indices.size()));
|
||||
}
|
||||
|
||||
ExecBatchPtr MmapForwardStore::FetchParquet(
|
||||
const std::vector<std::string> &columns, int index) {
|
||||
std::vector<int> col_indices;
|
||||
for (const auto &col : columns) {
|
||||
int idx = physic_schema_->GetFieldIndex(col);
|
||||
if (idx == -1) return nullptr;
|
||||
col_indices.push_back(idx);
|
||||
}
|
||||
|
||||
int rg_id = FindRowGroupForRow(index);
|
||||
int64_t offset = GetRowGroupOffset(rg_id);
|
||||
uint64_t local_in_rg = index - offset;
|
||||
|
||||
std::shared_ptr<arrow::Table> rg_table;
|
||||
auto status =
|
||||
parquet_reader_->RowGroup(rg_id)->ReadTable(col_indices, &rg_table);
|
||||
if (!status.ok()) {
|
||||
LOG_ERROR("Failed to read row group %d", rg_id);
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
// Extract scalars
|
||||
std::vector<arrow::Datum> scalars;
|
||||
scalars.reserve(columns.size());
|
||||
for (const auto &column : columns) {
|
||||
const auto &array = rg_table->GetColumnByName(column);
|
||||
auto scalar_result = array->GetScalar(local_in_rg);
|
||||
scalars.emplace_back(std::move(scalar_result.ValueOrDie()));
|
||||
}
|
||||
|
||||
return std::make_shared<arrow::ExecBatch>(std::move(scalars), 1);
|
||||
}
|
||||
|
||||
TablePtr MmapForwardStore::FetchIPC(const std::vector<std::string> &columns,
|
||||
const std::vector<int> &indices) {
|
||||
std::vector<std::pair<int64_t, int64_t>> indices_in_table;
|
||||
auto chunked_array = table_->column(0);
|
||||
for (const auto &target_index : indices) {
|
||||
int target_chunk_index = -1;
|
||||
int64_t offset_in_chunk = -1;
|
||||
if (FindTargetChunk(target_index, chunked_array->num_chunks(),
|
||||
&target_chunk_index, &offset_in_chunk)) {
|
||||
indices_in_table.emplace_back(target_chunk_index, offset_in_chunk);
|
||||
} else {
|
||||
LOG_ERROR("Failed to find target chunk for index %d", target_index);
|
||||
return nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<std::shared_ptr<arrow::ChunkedArray>> result_columns;
|
||||
std::vector<std::shared_ptr<arrow::Field>> result_fields;
|
||||
|
||||
for (size_t i = 0; i < columns.size(); ++i) {
|
||||
if (columns[i] == LOCAL_ROW_ID) {
|
||||
std::shared_ptr<arrow::Array> array;
|
||||
arrow::UInt64Builder builder;
|
||||
std::vector<uint64_t> u64_indices(indices.begin(), indices.end());
|
||||
auto status = builder.AppendValues(u64_indices);
|
||||
if (!status.ok()) {
|
||||
LOG_ERROR("Failed to append values to UInt64Builder: %s",
|
||||
status.ToString().c_str());
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
status = builder.Finish(&array);
|
||||
if (!status.ok()) {
|
||||
LOG_ERROR("Failed to finish UInt64Builder: %s",
|
||||
status.ToString().c_str());
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
result_columns.push_back(std::make_shared<arrow::ChunkedArray>(array));
|
||||
result_fields.push_back(
|
||||
arrow::field(LOCAL_ROW_ID, arrow::uint64(), false));
|
||||
} else {
|
||||
std::shared_ptr<arrow::Array> array;
|
||||
auto col_array = table_->GetColumnByName(columns[i]);
|
||||
auto status =
|
||||
BuildArrayFromIndicesWithType(col_array, indices_in_table, &array);
|
||||
if (!status.ok()) {
|
||||
LOG_ERROR("BuildArrayFromIndices failed: %s",
|
||||
status.ToString().c_str());
|
||||
return nullptr;
|
||||
}
|
||||
result_columns.push_back(std::make_shared<arrow::ChunkedArray>(array));
|
||||
result_fields.push_back(physic_schema_->GetFieldByName(columns[i]));
|
||||
}
|
||||
}
|
||||
|
||||
auto result_schema = std::make_shared<arrow::Schema>(result_fields);
|
||||
return arrow::Table::Make(result_schema, result_columns, indices.size());
|
||||
}
|
||||
|
||||
ExecBatchPtr MmapForwardStore::FetchIPC(const std::vector<std::string> &columns,
|
||||
int index) {
|
||||
// Extract scalars
|
||||
std::vector<arrow::Datum> scalars;
|
||||
scalars.reserve(columns.size());
|
||||
for (size_t col_idx = 0; col_idx < columns.size(); ++col_idx) {
|
||||
//! NOTICE: no need to check LOCAL_ROW_ID here
|
||||
int field_index = table_->schema()->GetFieldIndex(columns[col_idx]);
|
||||
auto chunked_array = table_->column(field_index);
|
||||
auto scalar_result = chunked_array->GetScalar(index);
|
||||
if (scalar_result.ok()) {
|
||||
scalars.push_back(scalar_result.ValueOrDie());
|
||||
} else {
|
||||
LOG_ERROR("Get scalar failed for column %zu, row %d: %s", col_idx, index,
|
||||
scalar_result.status().ToString().c_str());
|
||||
return nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
return std::make_shared<arrow::ExecBatch>(std::move(scalars), 1);
|
||||
}
|
||||
|
||||
int MmapForwardStore::FindRowGroupForRow(int64_t row) {
|
||||
auto it = std::upper_bound(row_group_offsets_.begin(),
|
||||
row_group_offsets_.end(), row);
|
||||
if (it == row_group_offsets_.begin()) {
|
||||
return 0;
|
||||
}
|
||||
return static_cast<int>(std::distance(row_group_offsets_.begin(), it) - 1);
|
||||
}
|
||||
|
||||
int64_t MmapForwardStore::GetRowGroupOffset(int rg_id) {
|
||||
return row_group_offsets_[rg_id];
|
||||
}
|
||||
|
||||
bool MmapForwardStore::FindTargetChunk(int target_index, int num_chunks,
|
||||
int *target_chunk_index,
|
||||
int64_t *offset_in_chunk) {
|
||||
if (target_index < 0 || target_index >= num_rows_) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (is_fixed_batch_size_ && fixed_batch_size_ > 0) {
|
||||
// direct calculation
|
||||
int chunk_index = target_index / fixed_batch_size_;
|
||||
if (chunk_index < 0 || chunk_index >= num_chunks) {
|
||||
return false;
|
||||
}
|
||||
*target_chunk_index = chunk_index;
|
||||
*offset_in_chunk = target_index % fixed_batch_size_;
|
||||
return true;
|
||||
} else {
|
||||
// binary search
|
||||
int left = 0;
|
||||
int right = num_chunks - 1;
|
||||
|
||||
while (left <= right) {
|
||||
int mid = left + (right - left) / 2;
|
||||
const auto &range = chunk_index_map_[mid];
|
||||
|
||||
if (target_index >= range.first && target_index <= range.second) {
|
||||
*target_chunk_index = mid;
|
||||
*offset_in_chunk = target_index - range.first;
|
||||
return true;
|
||||
} else if (target_index < range.first) {
|
||||
right = mid - 1;
|
||||
} else {
|
||||
left = mid + 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
TablePtr MmapForwardStore::fetch(const std::vector<std::string> &columns,
|
||||
const std::vector<int> &indices) {
|
||||
if (!validate(columns)) {
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
if (indices.empty()) {
|
||||
arrow::ArrayVector empty_arrays;
|
||||
auto fields = SelectFields(physic_schema_, columns);
|
||||
for (const auto &field : fields) {
|
||||
empty_arrays.push_back(arrow::MakeEmptyArray(field->type()).ValueOrDie());
|
||||
}
|
||||
return arrow::Table::Make(std::make_shared<arrow::Schema>(fields),
|
||||
empty_arrays, 0);
|
||||
}
|
||||
|
||||
if (format_ == FileFormat::PARQUET) {
|
||||
return FetchParquet(columns, indices);
|
||||
} else {
|
||||
return FetchIPC(columns, indices);
|
||||
}
|
||||
}
|
||||
|
||||
ExecBatchPtr MmapForwardStore::fetch(const std::vector<std::string> &columns,
|
||||
int index) {
|
||||
if (!validate(columns)) {
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
if (index < 0 || index >= num_rows_) {
|
||||
LOG_ERROR("Invalid global row: %d", index);
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
if (format_ == FileFormat::PARQUET) {
|
||||
return FetchParquet(columns, index);
|
||||
} else {
|
||||
return FetchIPC(columns, index);
|
||||
}
|
||||
}
|
||||
|
||||
RecordBatchReaderPtr MmapForwardStore::scan(
|
||||
const std::vector<std::string> &columns) {
|
||||
if (!validate(columns)) {
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
if (format_ == FileFormat::PARQUET) {
|
||||
return ScanParquet(columns);
|
||||
} else {
|
||||
return ScanIPC(columns);
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace zvec
|
||||
@@ -0,0 +1,204 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
#pragma once
|
||||
|
||||
#include <iostream>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
#include <unordered_set>
|
||||
#include <vector>
|
||||
#include <arrow/api.h>
|
||||
#include <arrow/chunked_array.h>
|
||||
#include <arrow/compute/api.h>
|
||||
#include <arrow/dataset/api.h>
|
||||
#include <arrow/filesystem/api.h>
|
||||
#include <arrow/io/file.h>
|
||||
#include <arrow/ipc/reader.h>
|
||||
#include <arrow/result.h>
|
||||
#include <arrow/status.h>
|
||||
#include <arrow/table.h>
|
||||
#include <arrow/util/async_generator.h>
|
||||
#include <parquet/arrow/reader.h>
|
||||
#include <parquet/column_reader.h>
|
||||
#include <parquet/exception.h>
|
||||
#include "db/common/status.h"
|
||||
#include "base_forward_store.h"
|
||||
#include "store_helper.h"
|
||||
|
||||
namespace zvec {
|
||||
|
||||
/// MmapForwardStore implements a forward store that uses memory mapping
|
||||
/// to efficiently access data from parquet or IPC files.
|
||||
class MmapForwardStore : public BaseForwardStore {
|
||||
public:
|
||||
/// Pointer type for MmapForwardStore instances
|
||||
using Ptr = std::shared_ptr<MmapForwardStore>;
|
||||
|
||||
/// Constructor that initializes the store with a file URI
|
||||
/// \param uri The URI of the file to be accessed
|
||||
MmapForwardStore(const std::string &uri);
|
||||
virtual ~MmapForwardStore() {}
|
||||
|
||||
Status Open() override;
|
||||
|
||||
/// Fetch specific columns and row indices from the data source
|
||||
/// \param columns The list of column names to fetch
|
||||
/// \param indices The list of row indices to fetch
|
||||
/// \return A table containing the requested data or nullptr on failure
|
||||
TablePtr fetch(const std::vector<std::string> &columns,
|
||||
const std::vector<int> &indices) override;
|
||||
|
||||
/// Fetch specific columns and a single row index from the data source
|
||||
/// \param columns The list of column names to fetch
|
||||
/// \param index The row index to fetch
|
||||
/// \return An ExecBatch containing the requested data or nullptr on failure
|
||||
ExecBatchPtr fetch(const std::vector<std::string> &columns,
|
||||
int index) override;
|
||||
|
||||
/// Scan specified columns from the data source
|
||||
/// \param columns The list of column names to scan
|
||||
/// \return A RecordBatchReader for streaming the data or nullptr on failure
|
||||
RecordBatchReaderPtr scan(const std::vector<std::string> &columns) override;
|
||||
|
||||
/// Get the physical schema of the file
|
||||
/// \return A shared pointer to the arrow schema representing the physical
|
||||
/// structure of the data
|
||||
const std::shared_ptr<arrow::Schema> physic_schema() const override {
|
||||
return physic_schema_;
|
||||
}
|
||||
|
||||
TablePtr get_table() override {
|
||||
return table_;
|
||||
}
|
||||
|
||||
private:
|
||||
/// Validate that the requested columns exist in the schema
|
||||
/// \param columns The list of column names to validate
|
||||
/// \return true if all columns are valid, false otherwise
|
||||
bool validate(const std::vector<std::string> &columns) const;
|
||||
|
||||
private:
|
||||
/// Open a parquet file and initialize metadata
|
||||
/// \param file The RandomAccessFile to read from
|
||||
/// \return arrow::Status indicating success or failure
|
||||
arrow::Status OpenParquet(
|
||||
const std::shared_ptr<arrow::io::RandomAccessFile> &file);
|
||||
|
||||
/// Open an IPC file and initialize metadata
|
||||
/// \param file The RandomAccessFile to read from
|
||||
/// \return arrow::Status indicating success or failure
|
||||
arrow::Status OpenIPC(
|
||||
const std::shared_ptr<arrow::io::RandomAccessFile> &file);
|
||||
|
||||
/// Fetch data from a parquet file
|
||||
/// \param columns The list of column names to fetch
|
||||
/// \param indices The list of row indices to fetch
|
||||
/// \return A table containing the requested data or nullptr on failure
|
||||
TablePtr FetchParquet(const std::vector<std::string> &columns,
|
||||
const std::vector<int> &indices);
|
||||
|
||||
/// Fetch specific columns and a single row index from parquet file
|
||||
/// \param columns The list of column names to fetch
|
||||
/// \param index The row index to fetch
|
||||
/// \return An ExecBatch containing the requested data or nullptr on failure
|
||||
ExecBatchPtr FetchParquet(const std::vector<std::string> &columns, int index);
|
||||
|
||||
/// Fetch data from an IPC file
|
||||
/// \param columns The list of column names to fetch
|
||||
/// \param indices The list of row indices to fetch
|
||||
/// \return A table containing the requested data or nullptr on failure
|
||||
TablePtr FetchIPC(const std::vector<std::string> &columns,
|
||||
const std::vector<int> &indices);
|
||||
|
||||
/// Fetch specific columns and a single row index from IPC file
|
||||
/// \param columns The list of column names to fetch
|
||||
/// \param index The row index to fetch
|
||||
/// \return An ExecBatch containing the requested data or nullptr on failure
|
||||
ExecBatchPtr FetchIPC(const std::vector<std::string> &columns, int index);
|
||||
|
||||
/// Scan data from a parquet file
|
||||
/// \param columns The list of column names to scan
|
||||
/// \return A RecordBatchReader for streaming the data or nullptr on failure
|
||||
RecordBatchReaderPtr ScanParquet(const std::vector<std::string> &columns);
|
||||
|
||||
/// Scan data from an IPC file
|
||||
/// \param columns The list of column names to scan
|
||||
/// \return A RecordBatchReader for streaming the data or nullptr on failure
|
||||
RecordBatchReaderPtr ScanIPC(const std::vector<std::string> &columns);
|
||||
|
||||
/// Find which row group contains a given row
|
||||
/// \param row The row index to locate
|
||||
/// \return The row group ID containing the row
|
||||
int FindRowGroupForRow(int64_t row);
|
||||
|
||||
/// Get the row offset for a given row group
|
||||
/// \param rg_id The row group ID
|
||||
/// \return The row offset of the row group, or -1 on error
|
||||
int64_t GetRowGroupOffset(int rg_id);
|
||||
|
||||
/// Find the chunk that contains a target row index using binary search
|
||||
/// \param target_index The row index to locate
|
||||
/// \param num_chunks The total number of chunks in the array
|
||||
/// \param target_chunk_index Output parameter for the index of the chunk
|
||||
/// containing the target
|
||||
/// \param offset_in_chunk Output parameter for the offset within the found
|
||||
/// chunk
|
||||
/// \return true if the target chunk was found, false otherwise
|
||||
bool FindTargetChunk(int target_index, int num_chunks,
|
||||
int *target_chunk_index, int64_t *offset_in_chunk);
|
||||
|
||||
private:
|
||||
/// Format of the file being accessed
|
||||
FileFormat format_;
|
||||
|
||||
/// Physical schema of the file
|
||||
std::shared_ptr<arrow::Schema> physic_schema_;
|
||||
|
||||
/// Total number of rows in the file
|
||||
int64_t num_rows_{0};
|
||||
|
||||
/// Path to the file
|
||||
std::string file_path_;
|
||||
|
||||
// Parquet-specific members
|
||||
/// The RandomAccessFile for reading data
|
||||
std::shared_ptr<arrow::io::RandomAccessFile> file_;
|
||||
|
||||
/// The parquet file reader
|
||||
std::unique_ptr<parquet::arrow::FileReader> parquet_reader_;
|
||||
|
||||
/// Number of row groups in the file
|
||||
int64_t num_row_groups_{0};
|
||||
|
||||
/// Offsets of each row group
|
||||
std::vector<int64_t> row_group_offsets_;
|
||||
|
||||
/// Number of rows in each row group
|
||||
std::vector<int64_t> row_group_row_nums_;
|
||||
|
||||
// IPC-specific members
|
||||
/// The IPC file reader
|
||||
std::shared_ptr<arrow::ipc::RecordBatchFileReader> ipc_file_reader_;
|
||||
|
||||
std::shared_ptr<arrow::Table> table_;
|
||||
|
||||
std::vector<std::pair<int64_t, int64_t>> chunk_index_map_;
|
||||
|
||||
// For performance tuning
|
||||
bool is_fixed_batch_size_{true};
|
||||
int64_t fixed_batch_size_{-1};
|
||||
};
|
||||
|
||||
} // namespace zvec
|
||||
@@ -0,0 +1,185 @@
|
||||
// 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 "parquet_writer.h"
|
||||
#include <cstdint>
|
||||
#include <iostream>
|
||||
#include <arrow/compute/api_vector.h>
|
||||
|
||||
namespace zvec {
|
||||
|
||||
ParquetWriter::ParquetWriter(const std::string &filepath,
|
||||
int64_t max_rows_per_group)
|
||||
: filepath_(filepath), max_rows_per_group_(max_rows_per_group) {}
|
||||
|
||||
ParquetWriter::~ParquetWriter() {
|
||||
if (!finalized_ && writer_) {
|
||||
auto status = finalize();
|
||||
if (!status.ok()) {
|
||||
std::cerr << "Auto-finalize failed: " << status.ToString() << std::endl;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
arrow::Status ParquetWriter::insert(
|
||||
std::shared_ptr<arrow::RecordBatchReader> reader,
|
||||
const IndexFilter::Ptr &filter) {
|
||||
if (!reader) {
|
||||
return arrow::Status::Invalid("RecordBatchReader is null");
|
||||
}
|
||||
|
||||
if (!writer_) {
|
||||
auto schema = reader->schema();
|
||||
if (!schema) {
|
||||
return arrow::Status::Invalid("Reader schema is null");
|
||||
}
|
||||
|
||||
ARROW_ASSIGN_OR_RAISE(outfile_,
|
||||
arrow::io::FileOutputStream::Open(filepath_));
|
||||
|
||||
parquet::WriterProperties::Builder builder;
|
||||
std::shared_ptr<parquet::WriterProperties> props = builder.build();
|
||||
|
||||
auto writer = parquet::arrow::FileWriter::Open(
|
||||
*schema, arrow::default_memory_pool(), outfile_, props);
|
||||
ARROW_RETURN_NOT_OK(writer);
|
||||
writer_ = std::move(writer.ValueOrDie());
|
||||
}
|
||||
|
||||
std::shared_ptr<arrow::RecordBatch> batch;
|
||||
while (true) {
|
||||
ARROW_ASSIGN_OR_RAISE(batch, reader->Next());
|
||||
if (!batch) break;
|
||||
|
||||
if (batch->num_rows() == 0) continue;
|
||||
|
||||
if (max_rows_per_group_ > 0 && batch->num_rows() > max_rows_per_group_) {
|
||||
int64_t offset = 0;
|
||||
while (offset < batch->num_rows()) {
|
||||
int64_t length =
|
||||
std::min(max_rows_per_group_, batch->num_rows() - offset);
|
||||
auto slice = batch->Slice(offset, length);
|
||||
ARROW_RETURN_NOT_OK(write_batch(*slice, filter));
|
||||
offset += length;
|
||||
}
|
||||
} else {
|
||||
ARROW_RETURN_NOT_OK(write_batch(*batch, filter));
|
||||
}
|
||||
|
||||
batch.reset();
|
||||
}
|
||||
|
||||
return arrow::Status::OK();
|
||||
}
|
||||
|
||||
arrow::Status ParquetWriter::insert_batch(
|
||||
std::shared_ptr<arrow::RecordBatch> batch, const IndexFilter::Ptr &filter) {
|
||||
if (!batch) {
|
||||
return arrow::Status::Invalid("RecordBatch is null");
|
||||
}
|
||||
|
||||
if (batch->num_rows() == 0) {
|
||||
return arrow::Status::OK();
|
||||
}
|
||||
|
||||
if (!writer_) {
|
||||
auto schema = batch->schema();
|
||||
|
||||
ARROW_ASSIGN_OR_RAISE(outfile_,
|
||||
arrow::io::FileOutputStream::Open(filepath_));
|
||||
|
||||
parquet::WriterProperties::Builder builder;
|
||||
std::shared_ptr<parquet::WriterProperties> props = builder.build();
|
||||
|
||||
auto writer = parquet::arrow::FileWriter::Open(
|
||||
*schema, arrow::default_memory_pool(), outfile_, props);
|
||||
ARROW_RETURN_NOT_OK(writer);
|
||||
writer_ = std::move(writer.ValueOrDie());
|
||||
}
|
||||
|
||||
if (max_rows_per_group_ > 0 && batch->num_rows() > max_rows_per_group_) {
|
||||
int64_t offset = 0;
|
||||
while (offset < batch->num_rows()) {
|
||||
int64_t length =
|
||||
std::min(max_rows_per_group_, batch->num_rows() - offset);
|
||||
auto slice = batch->Slice(offset, length);
|
||||
|
||||
ARROW_RETURN_NOT_OK(write_batch(*slice, filter));
|
||||
|
||||
offset += length;
|
||||
}
|
||||
} else {
|
||||
ARROW_RETURN_NOT_OK(write_batch(*batch, filter));
|
||||
}
|
||||
|
||||
return arrow::Status::OK();
|
||||
}
|
||||
|
||||
arrow::Status ParquetWriter::write_batch(const arrow::RecordBatch &batch,
|
||||
const IndexFilter::Ptr &filter) {
|
||||
if (!filter) {
|
||||
return writer_->WriteRecordBatch(batch);
|
||||
}
|
||||
|
||||
std::vector<int64_t> selected_indices;
|
||||
for (int64_t i = 0; i < batch.num_rows(); ++i) {
|
||||
if (filter->is_filtered(i)) {
|
||||
selected_indices.push_back(i);
|
||||
}
|
||||
}
|
||||
|
||||
if (selected_indices.empty()) {
|
||||
return arrow::Status::OK();
|
||||
}
|
||||
|
||||
arrow::Int64Builder builder;
|
||||
ARROW_RETURN_NOT_OK(builder.AppendValues(selected_indices));
|
||||
std::shared_ptr<arrow::Array> selection_array;
|
||||
ARROW_RETURN_NOT_OK(builder.Finish(&selection_array));
|
||||
|
||||
std::vector<std::shared_ptr<arrow::Array>> filtered_columns;
|
||||
for (int i = 0; i < batch.num_columns(); ++i) {
|
||||
arrow::Datum out;
|
||||
ARROW_ASSIGN_OR_RAISE(
|
||||
out, arrow::compute::Take(batch.column(i), selection_array));
|
||||
filtered_columns.push_back(out.make_array());
|
||||
}
|
||||
|
||||
auto filtered_batch = arrow::RecordBatch::Make(
|
||||
batch.schema(), static_cast<int64_t>(selected_indices.size()),
|
||||
filtered_columns);
|
||||
|
||||
return writer_->WriteRecordBatch(*filtered_batch);
|
||||
}
|
||||
|
||||
arrow::Status ParquetWriter::finalize() {
|
||||
if (finalized_) {
|
||||
return arrow::Status::OK();
|
||||
}
|
||||
if (!writer_) {
|
||||
return arrow::Status::Invalid(
|
||||
"No data written, cannot finalize empty file");
|
||||
}
|
||||
|
||||
ARROW_RETURN_NOT_OK(writer_->Close());
|
||||
writer_.reset();
|
||||
|
||||
ARROW_RETURN_NOT_OK(outfile_->Close());
|
||||
outfile_.reset();
|
||||
|
||||
finalized_ = true;
|
||||
return arrow::Status::OK();
|
||||
}
|
||||
|
||||
} // namespace zvec
|
||||
@@ -0,0 +1,55 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
#pragma once
|
||||
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <arrow/api.h>
|
||||
#include <arrow/io/api.h>
|
||||
#include <arrow/status.h>
|
||||
#include <parquet/arrow/writer.h>
|
||||
#include "db/index/common/index_filter.h"
|
||||
#include "forward_writer.h"
|
||||
|
||||
namespace zvec {
|
||||
|
||||
class ParquetWriter : public ForwardWriter {
|
||||
public:
|
||||
explicit ParquetWriter(const std::string &filepath,
|
||||
int64_t max_rows_per_group = 0);
|
||||
|
||||
~ParquetWriter();
|
||||
|
||||
arrow::Status insert(std::shared_ptr<arrow::RecordBatchReader> reader,
|
||||
const IndexFilter::Ptr &filter = nullptr) override;
|
||||
|
||||
arrow::Status insert_batch(std::shared_ptr<arrow::RecordBatch> batch,
|
||||
const IndexFilter::Ptr &filter = nullptr) override;
|
||||
|
||||
arrow::Status finalize() override;
|
||||
|
||||
private:
|
||||
arrow::Status write_batch(const arrow::RecordBatch &batch,
|
||||
const IndexFilter::Ptr &filter);
|
||||
|
||||
private:
|
||||
std::string filepath_;
|
||||
int64_t max_rows_per_group_ = 0;
|
||||
|
||||
std::shared_ptr<arrow::io::FileOutputStream> outfile_;
|
||||
std::unique_ptr<parquet::arrow::FileWriter> writer_;
|
||||
bool finalized_ = false;
|
||||
};
|
||||
|
||||
} // namespace zvec
|
||||
@@ -0,0 +1,954 @@
|
||||
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <algorithm>
|
||||
#include <filesystem>
|
||||
#include <iostream>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <arrow/api.h>
|
||||
#include <arrow/compute/api.h>
|
||||
#include <arrow/dataset/api.h>
|
||||
#include <arrow/filesystem/api.h>
|
||||
#include <arrow/io/file.h>
|
||||
#include <arrow/ipc/reader.h>
|
||||
#include <arrow/result.h>
|
||||
#include <arrow/status.h>
|
||||
#include <parquet/arrow/reader.h>
|
||||
#include "db/common/file_helper.h"
|
||||
#include "db/index/common/doc.h"
|
||||
#include "db/index/common/meta.h"
|
||||
#include "db/index/common/schema.h"
|
||||
#include "chunked_file_writer.h"
|
||||
|
||||
|
||||
namespace zvec {
|
||||
|
||||
inline FileFormat InferFileFormat(const std::string &file_path) {
|
||||
std::string ext = std::filesystem::path(file_path).extension();
|
||||
std::transform(ext.begin(), ext.end(), ext.begin(), ::tolower);
|
||||
if (ext == ".parquet") {
|
||||
return FileFormat::PARQUET;
|
||||
} else if (ext == ".feather" || ext == ".ipc" || ext == ".arrow") {
|
||||
return FileFormat::IPC;
|
||||
} else {
|
||||
return FileFormat::UNKNOWN;
|
||||
}
|
||||
}
|
||||
|
||||
inline arrow::Status ConvertFieldSchemaToArrowField(
|
||||
const FieldSchema *field, std::shared_ptr<arrow::Field> *out) {
|
||||
switch (field->data_type()) {
|
||||
case DataType::BINARY:
|
||||
*out = arrow::field(field->name(), arrow::binary(), field->nullable());
|
||||
break;
|
||||
case DataType::STRING:
|
||||
*out = arrow::field(field->name(), arrow::utf8(), field->nullable());
|
||||
break;
|
||||
case DataType::BOOL:
|
||||
*out = arrow::field(field->name(), arrow::boolean(), field->nullable());
|
||||
break;
|
||||
case DataType::INT32:
|
||||
*out = arrow::field(field->name(), arrow::int32(), field->nullable());
|
||||
break;
|
||||
case DataType::INT64:
|
||||
*out = arrow::field(field->name(), arrow::int64(), field->nullable());
|
||||
break;
|
||||
case DataType::UINT32:
|
||||
*out = arrow::field(field->name(), arrow::uint32(), field->nullable());
|
||||
break;
|
||||
case DataType::UINT64:
|
||||
*out = arrow::field(field->name(), arrow::uint64(), field->nullable());
|
||||
break;
|
||||
case DataType::FLOAT:
|
||||
*out = arrow::field(field->name(), arrow::float32(), field->nullable());
|
||||
break;
|
||||
case DataType::DOUBLE:
|
||||
*out = arrow::field(field->name(), arrow::float64(), field->nullable());
|
||||
break;
|
||||
case DataType::ARRAY_BINARY:
|
||||
*out = arrow::field(field->name(), arrow::list(arrow::binary()),
|
||||
field->nullable());
|
||||
break;
|
||||
case DataType::ARRAY_STRING:
|
||||
*out = arrow::field(field->name(), arrow::list(arrow::utf8()),
|
||||
field->nullable());
|
||||
break;
|
||||
case DataType::ARRAY_BOOL:
|
||||
*out = arrow::field(field->name(), arrow::list(arrow::boolean()),
|
||||
field->nullable());
|
||||
break;
|
||||
case DataType::ARRAY_INT32:
|
||||
*out = arrow::field(field->name(), arrow::list(arrow::int32()),
|
||||
field->nullable());
|
||||
break;
|
||||
case DataType::ARRAY_INT64:
|
||||
*out = arrow::field(field->name(), arrow::list(arrow::int64()),
|
||||
field->nullable());
|
||||
break;
|
||||
case DataType::ARRAY_UINT32:
|
||||
*out = arrow::field(field->name(), arrow::list(arrow::uint32()),
|
||||
field->nullable());
|
||||
break;
|
||||
case DataType::ARRAY_UINT64:
|
||||
*out = arrow::field(field->name(), arrow::list(arrow::uint64()),
|
||||
field->nullable());
|
||||
break;
|
||||
case DataType::ARRAY_FLOAT:
|
||||
*out = arrow::field(field->name(), arrow::list(arrow::float32()),
|
||||
field->nullable());
|
||||
break;
|
||||
case DataType::ARRAY_DOUBLE:
|
||||
*out = arrow::field(field->name(), arrow::list(arrow::float64()),
|
||||
field->nullable());
|
||||
break;
|
||||
default:
|
||||
return arrow::Status::Invalid(
|
||||
"Unsupported data type ",
|
||||
DataTypeCodeBook::AsString(field->data_type()));
|
||||
}
|
||||
|
||||
return arrow::Status::OK();
|
||||
}
|
||||
|
||||
inline arrow::Status ConvertCollectionSchemaToArrowFields(
|
||||
const CollectionSchema::Ptr &schema, arrow::FieldVector *out) {
|
||||
arrow::FieldVector fields;
|
||||
fields.push_back(arrow::field(GLOBAL_DOC_ID, arrow::uint64(), false));
|
||||
fields.push_back(arrow::field(USER_ID, arrow::utf8(), false));
|
||||
for (auto &field : schema->forward_fields()) {
|
||||
std::shared_ptr<arrow::Field> arrow_field;
|
||||
ARROW_RETURN_NOT_OK(
|
||||
ConvertFieldSchemaToArrowField(field.get(), &arrow_field));
|
||||
fields.push_back(arrow_field);
|
||||
}
|
||||
*out = std::move(fields);
|
||||
return arrow::Status::OK();
|
||||
}
|
||||
|
||||
template <typename BuilderType, typename ScalarType>
|
||||
inline arrow::Status ConvertScalarVectorToArray(
|
||||
std::vector<std::shared_ptr<arrow::Scalar>> ordered_scalars,
|
||||
std::shared_ptr<arrow::Array> *out) {
|
||||
std::shared_ptr<arrow::Array> arr;
|
||||
BuilderType builder;
|
||||
for (const auto &scalar : ordered_scalars) {
|
||||
if (scalar == nullptr || scalar->is_valid == false) {
|
||||
ARROW_RETURN_NOT_OK(builder.AppendNull());
|
||||
continue;
|
||||
}
|
||||
auto status =
|
||||
builder.Append(dynamic_cast<const ScalarType &>(*scalar).value);
|
||||
}
|
||||
ARROW_RETURN_NOT_OK(builder.Finish(&arr));
|
||||
*out = arr;
|
||||
return arrow::Status::OK();
|
||||
}
|
||||
|
||||
template <>
|
||||
inline arrow::Status
|
||||
ConvertScalarVectorToArray<arrow::StringBuilder, arrow::StringScalar>(
|
||||
std::vector<std::shared_ptr<arrow::Scalar>> ordered_scalars,
|
||||
std::shared_ptr<arrow::Array> *out) {
|
||||
std::shared_ptr<arrow::Array> arr;
|
||||
arrow::StringBuilder builder;
|
||||
for (const auto &scalar : ordered_scalars) {
|
||||
if (scalar == nullptr || scalar->is_valid == false) {
|
||||
ARROW_RETURN_NOT_OK(builder.AppendNull());
|
||||
continue;
|
||||
}
|
||||
const auto &str = dynamic_cast<const arrow::StringScalar &>(*scalar).value;
|
||||
ARROW_RETURN_NOT_OK(
|
||||
builder.Append(str->data(), static_cast<int>(str->size())));
|
||||
}
|
||||
ARROW_RETURN_NOT_OK(builder.Finish(&arr));
|
||||
*out = arr;
|
||||
return arrow::Status::OK();
|
||||
}
|
||||
|
||||
template <>
|
||||
inline arrow::Status
|
||||
ConvertScalarVectorToArray<arrow::BinaryBuilder, arrow::BinaryScalar>(
|
||||
std::vector<std::shared_ptr<arrow::Scalar>> ordered_scalars,
|
||||
std::shared_ptr<arrow::Array> *out) {
|
||||
std::shared_ptr<arrow::Array> arr;
|
||||
arrow::BinaryBuilder builder;
|
||||
for (const auto &scalar : ordered_scalars) {
|
||||
if (scalar == nullptr || scalar->is_valid == false) {
|
||||
ARROW_RETURN_NOT_OK(builder.AppendNull());
|
||||
continue;
|
||||
}
|
||||
const auto &binary_scalar =
|
||||
dynamic_cast<const arrow::BinaryScalar &>(*scalar);
|
||||
if (binary_scalar.value) {
|
||||
ARROW_RETURN_NOT_OK(
|
||||
builder.Append(binary_scalar.value->data(),
|
||||
static_cast<int>(binary_scalar.value->size())));
|
||||
} else {
|
||||
ARROW_RETURN_NOT_OK(builder.AppendEmptyValue());
|
||||
}
|
||||
}
|
||||
ARROW_RETURN_NOT_OK(builder.Finish(&arr));
|
||||
*out = arr;
|
||||
return arrow::Status::OK();
|
||||
}
|
||||
|
||||
inline arrow::Status ConvertScalarVectorToArrayByType(
|
||||
std::vector<std::shared_ptr<arrow::Scalar>> ordered_scalars,
|
||||
std::shared_ptr<arrow::Array> *out) {
|
||||
auto type = ordered_scalars.empty() ? nullptr : ordered_scalars[0]->type;
|
||||
if (type == nullptr)
|
||||
return arrow::Status::Invalid("Cannot convert empty vector to array");
|
||||
arrow::Status status;
|
||||
switch (type->id()) {
|
||||
case arrow::Type::BINARY:
|
||||
status =
|
||||
ConvertScalarVectorToArray<arrow::BinaryBuilder, arrow::BinaryScalar>(
|
||||
ordered_scalars, out);
|
||||
break;
|
||||
case arrow::Type::BOOL:
|
||||
status = ConvertScalarVectorToArray<arrow::BooleanBuilder,
|
||||
arrow::BooleanScalar>(ordered_scalars,
|
||||
out);
|
||||
break;
|
||||
case arrow::Type::INT32:
|
||||
status =
|
||||
ConvertScalarVectorToArray<arrow::Int32Builder, arrow::Int32Scalar>(
|
||||
ordered_scalars, out);
|
||||
break;
|
||||
case arrow::Type::UINT32:
|
||||
status =
|
||||
ConvertScalarVectorToArray<arrow::UInt32Builder, arrow::UInt32Scalar>(
|
||||
ordered_scalars, out);
|
||||
break;
|
||||
case arrow::Type::INT64:
|
||||
status =
|
||||
ConvertScalarVectorToArray<arrow::Int64Builder, arrow::Int64Scalar>(
|
||||
ordered_scalars, out);
|
||||
break;
|
||||
case arrow::Type::UINT64:
|
||||
status =
|
||||
ConvertScalarVectorToArray<arrow::UInt64Builder, arrow::UInt64Scalar>(
|
||||
ordered_scalars, out);
|
||||
break;
|
||||
case arrow::Type::FLOAT:
|
||||
status =
|
||||
ConvertScalarVectorToArray<arrow::FloatBuilder, arrow::FloatScalar>(
|
||||
ordered_scalars, out);
|
||||
break;
|
||||
case arrow::Type::DOUBLE:
|
||||
status =
|
||||
ConvertScalarVectorToArray<arrow::DoubleBuilder, arrow::DoubleScalar>(
|
||||
ordered_scalars, out);
|
||||
break;
|
||||
case arrow::Type::STRING:
|
||||
status =
|
||||
ConvertScalarVectorToArray<arrow::StringBuilder, arrow::StringScalar>(
|
||||
ordered_scalars, out);
|
||||
break;
|
||||
case arrow::Type::LIST: {
|
||||
if (ordered_scalars.empty()) {
|
||||
return arrow::Status::Invalid(
|
||||
"Cannot convert empty vector to list array");
|
||||
}
|
||||
|
||||
auto list_type = std::dynamic_pointer_cast<arrow::ListType>(type);
|
||||
if (!list_type) {
|
||||
return arrow::Status::TypeError("Expected ListType for LIST scalar");
|
||||
}
|
||||
|
||||
std::unique_ptr<arrow::ArrayBuilder> value_builder;
|
||||
ARROW_RETURN_NOT_OK(arrow::MakeBuilder(arrow::default_memory_pool(),
|
||||
list_type->value_type(),
|
||||
&value_builder));
|
||||
|
||||
arrow::ListBuilder builder(arrow::default_memory_pool(),
|
||||
std::move(value_builder), list_type);
|
||||
|
||||
for (const auto &scalar : ordered_scalars) {
|
||||
if (scalar == nullptr || scalar->is_valid == false) {
|
||||
ARROW_RETURN_NOT_OK(builder.AppendNull());
|
||||
continue;
|
||||
}
|
||||
|
||||
auto list_scalar = std::dynamic_pointer_cast<arrow::ListScalar>(scalar);
|
||||
if (!list_scalar) {
|
||||
return arrow::Status::TypeError("Expected ListScalar for LIST type");
|
||||
}
|
||||
|
||||
ARROW_RETURN_NOT_OK(builder.Append());
|
||||
auto value_builder_ptr = builder.value_builder();
|
||||
ARROW_RETURN_NOT_OK(value_builder_ptr->AppendArraySlice(
|
||||
*list_scalar->value->data(), 0, list_scalar->value->length()));
|
||||
}
|
||||
|
||||
std::shared_ptr<arrow::Array> arr;
|
||||
ARROW_RETURN_NOT_OK(builder.Finish(&arr));
|
||||
*out = arr;
|
||||
return arrow::Status::OK();
|
||||
}
|
||||
default:
|
||||
// TODO other type
|
||||
return arrow::Status::NotImplemented("Unsupported type");
|
||||
}
|
||||
|
||||
return status;
|
||||
}
|
||||
|
||||
template <typename ArrowBuilderType, typename ValueType>
|
||||
inline arrow::Status AppendValue(ArrowBuilderType *builder, const Doc &doc,
|
||||
std::shared_ptr<arrow::Field> field) {
|
||||
auto value = doc.get<ValueType>(field->name());
|
||||
if (!value.has_value()) {
|
||||
return builder->AppendNull();
|
||||
}
|
||||
return builder->Append(value.value());
|
||||
}
|
||||
|
||||
inline arrow::Status AppendFieldValueToBuilder(
|
||||
const Doc &doc, const std::shared_ptr<arrow::Field> &field,
|
||||
arrow::ArrayBuilder *builder) {
|
||||
auto type = field->type()->id();
|
||||
switch (type) {
|
||||
case arrow::Type::STRING: {
|
||||
auto string_builder = dynamic_cast<arrow::StringBuilder *>(builder);
|
||||
return AppendValue<arrow::StringBuilder, std::string>(string_builder, doc,
|
||||
field);
|
||||
}
|
||||
case arrow::Type::INT32: {
|
||||
auto int32_builder = dynamic_cast<arrow::Int32Builder *>(builder);
|
||||
return AppendValue<arrow::Int32Builder, int32_t>(int32_builder, doc,
|
||||
field);
|
||||
}
|
||||
case arrow::Type::INT64: {
|
||||
auto int64_builder = dynamic_cast<arrow::Int64Builder *>(builder);
|
||||
return AppendValue<arrow::Int64Builder, int64_t>(int64_builder, doc,
|
||||
field);
|
||||
}
|
||||
case arrow::Type::UINT32: {
|
||||
auto uint32_builder = dynamic_cast<arrow::UInt32Builder *>(builder);
|
||||
return AppendValue<arrow::UInt32Builder, uint32_t>(uint32_builder, doc,
|
||||
field);
|
||||
}
|
||||
case arrow::Type::UINT64: {
|
||||
auto uint64_builder = dynamic_cast<arrow::UInt64Builder *>(builder);
|
||||
return AppendValue<arrow::UInt64Builder, uint64_t>(uint64_builder, doc,
|
||||
field);
|
||||
}
|
||||
case arrow::Type::DOUBLE: {
|
||||
auto double_builder = dynamic_cast<arrow::DoubleBuilder *>(builder);
|
||||
return AppendValue<arrow::DoubleBuilder, double>(double_builder, doc,
|
||||
field);
|
||||
}
|
||||
case arrow::Type::FLOAT: {
|
||||
auto float_builder = dynamic_cast<arrow::FloatBuilder *>(builder);
|
||||
return AppendValue<arrow::FloatBuilder, float>(float_builder, doc, field);
|
||||
}
|
||||
case arrow::Type::BOOL: {
|
||||
auto bool_builder = dynamic_cast<arrow::BooleanBuilder *>(builder);
|
||||
return AppendValue<arrow::BooleanBuilder, bool>(bool_builder, doc, field);
|
||||
}
|
||||
case arrow::Type::BINARY: {
|
||||
auto binary_builder = dynamic_cast<arrow::BinaryBuilder *>(builder);
|
||||
return AppendValue<arrow::BinaryBuilder, std::string>(binary_builder, doc,
|
||||
field);
|
||||
}
|
||||
case arrow::Type::LIST: {
|
||||
auto list_builder = dynamic_cast<arrow::ListBuilder *>(builder);
|
||||
auto list_type =
|
||||
std::dynamic_pointer_cast<arrow::ListType>(field->type());
|
||||
|
||||
if (!list_type) {
|
||||
return arrow::Status::TypeError("Field type is not ListType");
|
||||
}
|
||||
|
||||
auto value_type = list_type->value_type()->id();
|
||||
|
||||
switch (value_type) {
|
||||
case arrow::Type::BINARY: {
|
||||
auto value = doc.get<std::vector<std::string>>(field->name());
|
||||
if (!value.has_value()) {
|
||||
return list_builder->AppendNull();
|
||||
}
|
||||
|
||||
const auto &list_value = value.value();
|
||||
auto binary_builder = dynamic_cast<arrow::BinaryBuilder *>(
|
||||
list_builder->value_builder());
|
||||
|
||||
ARROW_RETURN_NOT_OK(list_builder->Append());
|
||||
for (const auto &item : list_value) {
|
||||
ARROW_RETURN_NOT_OK(binary_builder->Append(item));
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case arrow::Type::BOOL: {
|
||||
auto value = doc.get<std::vector<bool>>(field->name());
|
||||
if (!value.has_value()) {
|
||||
return list_builder->AppendNull();
|
||||
}
|
||||
|
||||
const auto &list_value = value.value();
|
||||
auto bool_builder = dynamic_cast<arrow::BooleanBuilder *>(
|
||||
list_builder->value_builder());
|
||||
|
||||
ARROW_RETURN_NOT_OK(list_builder->Append());
|
||||
for (const auto &item : list_value) {
|
||||
ARROW_RETURN_NOT_OK(bool_builder->Append(item));
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case arrow::Type::INT32: {
|
||||
auto value = doc.get<std::vector<int32_t>>(field->name());
|
||||
if (!value.has_value()) {
|
||||
return list_builder->AppendNull();
|
||||
}
|
||||
|
||||
const auto &list_value = value.value();
|
||||
auto int32_builder = dynamic_cast<arrow::Int32Builder *>(
|
||||
list_builder->value_builder());
|
||||
|
||||
ARROW_RETURN_NOT_OK(list_builder->Append());
|
||||
for (const auto &item : list_value) {
|
||||
ARROW_RETURN_NOT_OK(int32_builder->Append(item));
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case arrow::Type::INT64: {
|
||||
auto value = doc.get<std::vector<int64_t>>(field->name());
|
||||
if (!value.has_value()) {
|
||||
return list_builder->AppendNull();
|
||||
}
|
||||
|
||||
const auto &list_value = value.value();
|
||||
auto int64_builder = dynamic_cast<arrow::Int64Builder *>(
|
||||
list_builder->value_builder());
|
||||
|
||||
ARROW_RETURN_NOT_OK(list_builder->Append());
|
||||
for (const auto &item : list_value) {
|
||||
ARROW_RETURN_NOT_OK(int64_builder->Append(item));
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case arrow::Type::UINT32: {
|
||||
auto value = doc.get<std::vector<uint32_t>>(field->name());
|
||||
if (!value.has_value()) {
|
||||
return list_builder->AppendNull();
|
||||
}
|
||||
|
||||
const auto &list_value = value.value();
|
||||
auto uint32_builder = dynamic_cast<arrow::UInt32Builder *>(
|
||||
list_builder->value_builder());
|
||||
|
||||
ARROW_RETURN_NOT_OK(list_builder->Append());
|
||||
for (const auto &item : list_value) {
|
||||
ARROW_RETURN_NOT_OK(uint32_builder->Append(item));
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case arrow::Type::UINT64: {
|
||||
auto value = doc.get<std::vector<uint64_t>>(field->name());
|
||||
if (!value.has_value()) {
|
||||
return list_builder->AppendNull();
|
||||
}
|
||||
|
||||
const auto &list_value = value.value();
|
||||
auto uint64_builder = dynamic_cast<arrow::UInt64Builder *>(
|
||||
list_builder->value_builder());
|
||||
|
||||
ARROW_RETURN_NOT_OK(list_builder->Append());
|
||||
for (const auto &item : list_value) {
|
||||
ARROW_RETURN_NOT_OK(uint64_builder->Append(item));
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case arrow::Type::FLOAT: {
|
||||
auto value = doc.get<std::vector<float>>(field->name());
|
||||
if (!value.has_value()) {
|
||||
return list_builder->AppendNull();
|
||||
}
|
||||
|
||||
const auto &list_value = value.value();
|
||||
auto float_builder = dynamic_cast<arrow::FloatBuilder *>(
|
||||
list_builder->value_builder());
|
||||
|
||||
ARROW_RETURN_NOT_OK(list_builder->Append());
|
||||
for (const auto &item : list_value) {
|
||||
ARROW_RETURN_NOT_OK(float_builder->Append(item));
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case arrow::Type::DOUBLE: {
|
||||
auto value = doc.get<std::vector<double>>(field->name());
|
||||
if (!value.has_value()) {
|
||||
return list_builder->AppendNull();
|
||||
}
|
||||
|
||||
const auto &list_value = value.value();
|
||||
auto double_builder = dynamic_cast<arrow::DoubleBuilder *>(
|
||||
list_builder->value_builder());
|
||||
|
||||
ARROW_RETURN_NOT_OK(list_builder->Append());
|
||||
for (const auto &item : list_value) {
|
||||
ARROW_RETURN_NOT_OK(double_builder->Append(item));
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case arrow::Type::STRING: {
|
||||
auto value = doc.get<std::vector<std::string>>(field->name());
|
||||
if (!value.has_value()) {
|
||||
return list_builder->AppendNull();
|
||||
}
|
||||
|
||||
const auto &list_value = value.value();
|
||||
auto string_builder = dynamic_cast<arrow::StringBuilder *>(
|
||||
list_builder->value_builder());
|
||||
|
||||
ARROW_RETURN_NOT_OK(list_builder->Append());
|
||||
for (const auto &item : list_value) {
|
||||
ARROW_RETURN_NOT_OK(string_builder->Append(item));
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
default:
|
||||
return arrow::Status::NotImplemented(
|
||||
"unsupported list element type: ", value_type);
|
||||
}
|
||||
|
||||
return arrow::Status::OK();
|
||||
}
|
||||
default:
|
||||
return arrow::Status::NotImplemented("unsupported type: ", type,
|
||||
", field: ", field->name());
|
||||
}
|
||||
}
|
||||
|
||||
template <typename ArrowArrayType, typename BuilderType>
|
||||
inline arrow::Status BuildArrayFromIndices(
|
||||
const std::shared_ptr<arrow::ChunkedArray> &chunked_array,
|
||||
const std::vector<std::pair<int64_t, int64_t>> &indices_in_chunked_array,
|
||||
std::shared_ptr<arrow::Array> *out_array) {
|
||||
BuilderType builder;
|
||||
ARROW_RETURN_NOT_OK(
|
||||
builder.Reserve(static_cast<int64_t>(indices_in_chunked_array.size())));
|
||||
|
||||
int64_t last_chunk_index = -1;
|
||||
const ArrowArrayType *cached_chunk{nullptr};
|
||||
|
||||
bool no_null = chunked_array->null_count() == 0;
|
||||
for (const auto &pair : indices_in_chunked_array) {
|
||||
if (pair.first != last_chunk_index) {
|
||||
const auto &chunk = chunked_array->chunk(pair.first);
|
||||
cached_chunk = static_cast<const ArrowArrayType *>(chunk.get());
|
||||
last_chunk_index = pair.first;
|
||||
}
|
||||
|
||||
if (no_null || !cached_chunk->IsNull(pair.second)) {
|
||||
ARROW_RETURN_NOT_OK(builder.Append(cached_chunk->Value(pair.second)));
|
||||
} else {
|
||||
ARROW_RETURN_NOT_OK(builder.AppendNull());
|
||||
}
|
||||
}
|
||||
|
||||
return builder.Finish(out_array);
|
||||
}
|
||||
|
||||
template <>
|
||||
inline arrow::Status
|
||||
BuildArrayFromIndices<arrow::StringArray, arrow::StringBuilder>(
|
||||
const std::shared_ptr<arrow::ChunkedArray> &chunked_array,
|
||||
const std::vector<std::pair<int64_t, int64_t>> &indices_in_chunked_array,
|
||||
std::shared_ptr<arrow::Array> *out_array) {
|
||||
arrow::StringBuilder builder;
|
||||
ARROW_RETURN_NOT_OK(
|
||||
builder.Reserve(static_cast<int64_t>(indices_in_chunked_array.size())));
|
||||
|
||||
bool no_null = chunked_array->null_count() == 0;
|
||||
const arrow::StringArray *cached_chunk{nullptr};
|
||||
|
||||
int64_t last_chunk_index = -1;
|
||||
int64_t data_size = 0;
|
||||
for (const auto &pair : indices_in_chunked_array) {
|
||||
if (pair.first != last_chunk_index) {
|
||||
const auto &chunk = chunked_array->chunk(pair.first);
|
||||
cached_chunk = static_cast<const arrow::StringArray *>(chunk.get());
|
||||
last_chunk_index = pair.first;
|
||||
}
|
||||
|
||||
if (no_null || !cached_chunk->IsNull(pair.second)) {
|
||||
data_size += cached_chunk->Value(pair.second).size();
|
||||
}
|
||||
}
|
||||
ARROW_RETURN_NOT_OK(builder.ReserveData(data_size));
|
||||
|
||||
|
||||
last_chunk_index = -1;
|
||||
for (const auto &pair : indices_in_chunked_array) {
|
||||
if (pair.first != last_chunk_index) {
|
||||
const auto &chunk = chunked_array->chunk(pair.first);
|
||||
cached_chunk = static_cast<const arrow::StringArray *>(chunk.get());
|
||||
last_chunk_index = pair.first;
|
||||
}
|
||||
|
||||
if (no_null || !cached_chunk->IsNull(pair.second)) {
|
||||
ARROW_RETURN_NOT_OK(builder.Append(cached_chunk->Value(pair.second)));
|
||||
} else {
|
||||
ARROW_RETURN_NOT_OK(builder.AppendNull());
|
||||
}
|
||||
}
|
||||
|
||||
return builder.Finish(out_array);
|
||||
}
|
||||
|
||||
inline arrow::Status BuildListArrayFromIndices(
|
||||
const std::shared_ptr<arrow::ChunkedArray> &chunked_array,
|
||||
const std::vector<std::pair<int64_t, int64_t>> &indices_in_chunked_array,
|
||||
const std::shared_ptr<arrow::ListType> &list_type,
|
||||
std::shared_ptr<arrow::Array> *out_array) {
|
||||
std::unique_ptr<arrow::ArrayBuilder> value_builder;
|
||||
ARROW_RETURN_NOT_OK(arrow::MakeBuilder(
|
||||
arrow::default_memory_pool(), list_type->value_type(), &value_builder));
|
||||
|
||||
arrow::ListBuilder builder(arrow::default_memory_pool(),
|
||||
std::move(value_builder), list_type);
|
||||
ARROW_RETURN_NOT_OK(
|
||||
builder.Reserve(static_cast<int64_t>(indices_in_chunked_array.size())));
|
||||
|
||||
int64_t last_chunk_index = -1;
|
||||
const arrow::ListArray *cached_chunk{nullptr};
|
||||
|
||||
for (const auto &pair : indices_in_chunked_array) {
|
||||
if (pair.first != last_chunk_index) {
|
||||
const auto &chunk = chunked_array->chunk(pair.first);
|
||||
cached_chunk = std::static_pointer_cast<arrow::ListArray>(chunk).get();
|
||||
last_chunk_index = pair.first;
|
||||
}
|
||||
|
||||
if (cached_chunk->IsValid(pair.second)) {
|
||||
auto offset = cached_chunk->value_offset(pair.second);
|
||||
auto length = cached_chunk->value_length(pair.second);
|
||||
|
||||
ARROW_RETURN_NOT_OK(builder.Append());
|
||||
auto value_builder_ptr = builder.value_builder();
|
||||
auto values = cached_chunk->values();
|
||||
ARROW_RETURN_NOT_OK(
|
||||
value_builder_ptr->AppendArraySlice(*values->data(), offset, length));
|
||||
} else {
|
||||
ARROW_RETURN_NOT_OK(builder.AppendNull());
|
||||
}
|
||||
}
|
||||
|
||||
return builder.Finish(out_array);
|
||||
}
|
||||
|
||||
inline arrow::Status BuildArrayFromIndicesWithType(
|
||||
const std::shared_ptr<arrow::ChunkedArray> &chunked_array,
|
||||
const std::vector<std::pair<int64_t, int64_t>> &indices_in_table,
|
||||
std::shared_ptr<arrow::Array> *out_array) {
|
||||
auto col_data_type = chunked_array->type();
|
||||
switch (col_data_type->id()) {
|
||||
case arrow::Type::STRING:
|
||||
return BuildArrayFromIndices<arrow::StringArray, arrow::StringBuilder>(
|
||||
chunked_array, indices_in_table, out_array);
|
||||
case arrow::Type::INT32:
|
||||
return BuildArrayFromIndices<arrow::Int32Array, arrow::Int32Builder>(
|
||||
chunked_array, indices_in_table, out_array);
|
||||
case arrow::Type::INT64:
|
||||
return BuildArrayFromIndices<arrow::Int64Array, arrow::Int64Builder>(
|
||||
chunked_array, indices_in_table, out_array);
|
||||
case arrow::Type::UINT32:
|
||||
return BuildArrayFromIndices<arrow::UInt32Array, arrow::UInt32Builder>(
|
||||
chunked_array, indices_in_table, out_array);
|
||||
case arrow::Type::UINT64:
|
||||
return BuildArrayFromIndices<arrow::UInt64Array, arrow::UInt64Builder>(
|
||||
chunked_array, indices_in_table, out_array);
|
||||
case arrow::Type::DOUBLE:
|
||||
return BuildArrayFromIndices<arrow::DoubleArray, arrow::DoubleBuilder>(
|
||||
chunked_array, indices_in_table, out_array);
|
||||
case arrow::Type::FLOAT:
|
||||
return BuildArrayFromIndices<arrow::FloatArray, arrow::FloatBuilder>(
|
||||
chunked_array, indices_in_table, out_array);
|
||||
case arrow::Type::BOOL:
|
||||
return BuildArrayFromIndices<arrow::BooleanArray, arrow::BooleanBuilder>(
|
||||
chunked_array, indices_in_table, out_array);
|
||||
case arrow::Type::BINARY:
|
||||
return BuildArrayFromIndices<arrow::BinaryArray, arrow::BinaryBuilder>(
|
||||
chunked_array, indices_in_table, out_array);
|
||||
case arrow::Type::LIST: {
|
||||
auto list_type =
|
||||
std::dynamic_pointer_cast<arrow::ListType>(col_data_type);
|
||||
return BuildListArrayFromIndices(chunked_array, indices_in_table,
|
||||
list_type, out_array);
|
||||
}
|
||||
default:
|
||||
return arrow::Status::NotImplemented("Unsupported element type: ",
|
||||
col_data_type->name().c_str());
|
||||
}
|
||||
}
|
||||
|
||||
inline arrow::Status CreateRandomAccessFileByUri(
|
||||
const std::string &uri,
|
||||
std::shared_ptr<arrow::io::RandomAccessFile> *out_file,
|
||||
std::string *out_file_path) {
|
||||
std::string path_from_uri, file_path;
|
||||
std::shared_ptr<arrow::fs::FileSystem> fs;
|
||||
auto maybe_fs = arrow::fs::FileSystemFromUri(uri, &path_from_uri);
|
||||
|
||||
if (maybe_fs.ok()) {
|
||||
fs = maybe_fs.ValueOrDie();
|
||||
*out_file_path = path_from_uri;
|
||||
} else {
|
||||
arrow::fs::LocalFileSystemOptions options;
|
||||
options.use_mmap = true;
|
||||
fs = std::make_shared<arrow::fs::LocalFileSystem>(options);
|
||||
if (uri.length() >= 2 && uri.substr(0, 2) == "./") {
|
||||
*out_file_path = uri.substr(2);
|
||||
} else {
|
||||
*out_file_path = uri;
|
||||
}
|
||||
}
|
||||
|
||||
auto result = fs->OpenInputFile(*out_file_path);
|
||||
if (!result.ok()) {
|
||||
return result.status();
|
||||
}
|
||||
*out_file = result.ValueOrDie();
|
||||
return arrow::Status::OK();
|
||||
}
|
||||
|
||||
inline std::vector<std::shared_ptr<arrow::Field>> SelectFields(
|
||||
const std::shared_ptr<arrow::Schema> &schema,
|
||||
const std::vector<std::string> &column_names) {
|
||||
std::vector<std::shared_ptr<arrow::Field>> fields;
|
||||
for (const auto &name : column_names) {
|
||||
if (name == LOCAL_ROW_ID) {
|
||||
fields.push_back(arrow::field(LOCAL_ROW_ID, arrow::uint64()));
|
||||
} else {
|
||||
fields.push_back(schema->field(schema->GetFieldIndex(name)));
|
||||
}
|
||||
}
|
||||
return fields;
|
||||
}
|
||||
|
||||
inline arrow::Result<std::shared_ptr<arrow::Array>> SelectArrayByIndices(
|
||||
const std::shared_ptr<arrow::Array> &arr,
|
||||
const std::vector<int32_t> &indices) {
|
||||
arrow::Int32Builder builder;
|
||||
ARROW_RETURN_NOT_OK(builder.AppendValues(indices));
|
||||
std::shared_ptr<arrow::Array> indices_array;
|
||||
ARROW_RETURN_NOT_OK(builder.Finish(&indices_array));
|
||||
|
||||
return arrow::compute::Take(*arr, *indices_array);
|
||||
}
|
||||
|
||||
inline arrow::Result<std::shared_ptr<arrow::dataset::Dataset>>
|
||||
ReadBlocksAsDataset(const std::vector<BlockMeta> &scalar_blocks,
|
||||
const std::string &base_path, uint32_t collection_id,
|
||||
bool use_parquet) {
|
||||
auto fs = std::make_shared<arrow::fs::LocalFileSystem>();
|
||||
auto pool = arrow::default_memory_pool();
|
||||
|
||||
if (scalar_blocks.empty()) {
|
||||
return arrow::Status::Invalid("No block metadata provided");
|
||||
}
|
||||
|
||||
using ColData = std::pair<std::shared_ptr<arrow::Field>,
|
||||
std::shared_ptr<arrow::ChunkedArray>>;
|
||||
std::map<uint64_t, std::map<std::string, ColData>> segments;
|
||||
std::map<uint64_t, uint32_t> segment_doc_count;
|
||||
std::set<uint64_t> ordered_min_ids;
|
||||
|
||||
for (const auto &block : scalar_blocks) {
|
||||
if (block.doc_count_ == 0 || block.columns_.empty()) continue;
|
||||
|
||||
uint64_t start_row = block.min_doc_id_;
|
||||
uint32_t expected_count = block.doc_count_;
|
||||
|
||||
std::string filepath = FileHelper::MakeForwardBlockPath(
|
||||
base_path, collection_id, block.id_, use_parquet);
|
||||
|
||||
try {
|
||||
auto file_info = fs->GetFileInfo(filepath).ValueOrDie();
|
||||
auto file = fs->OpenInputFile(file_info.path()).ValueOrDie();
|
||||
|
||||
std::shared_ptr<arrow::Table> table;
|
||||
|
||||
if (use_parquet) {
|
||||
std::unique_ptr<parquet::arrow::FileReader> reader;
|
||||
reader = parquet::arrow::OpenFile(file, pool).ValueOrDie();
|
||||
ARROW_RETURN_NOT_OK(reader->ReadTable(&table));
|
||||
} else {
|
||||
auto reader =
|
||||
arrow::ipc::RecordBatchFileReader::Open(file).ValueOrDie();
|
||||
|
||||
std::vector<std::shared_ptr<arrow::RecordBatch>> batches;
|
||||
for (int i = 0; i < reader->num_record_batches(); ++i) {
|
||||
auto batch = reader->ReadRecordBatch(i).ValueOrDie();
|
||||
batches.push_back(batch);
|
||||
}
|
||||
|
||||
table = arrow::Table::FromRecordBatches(batches).ValueOrDie();
|
||||
}
|
||||
|
||||
if (segments.find(start_row) == segments.end()) {
|
||||
segments[start_row] = {};
|
||||
segment_doc_count[start_row] = expected_count;
|
||||
ordered_min_ids.insert(start_row);
|
||||
}
|
||||
|
||||
for (int i = 0; i < table->num_columns(); ++i) {
|
||||
const auto &field = table->schema()->field(i);
|
||||
auto original_chunked_array = table->column(i);
|
||||
|
||||
segments[start_row][field->name()] = {field, original_chunked_array};
|
||||
}
|
||||
} catch (const std::exception &e) {
|
||||
return arrow::Status::IOError("Failed to read block ",
|
||||
std::to_string(block.id_), ": ", e.what());
|
||||
}
|
||||
}
|
||||
|
||||
if (segments.empty()) {
|
||||
return arrow::Status::Invalid("No valid data blocks found");
|
||||
}
|
||||
|
||||
std::vector<uint64_t> sorted_starts(ordered_min_ids.begin(),
|
||||
ordered_min_ids.end());
|
||||
std::sort(sorted_starts.begin(), sorted_starts.end());
|
||||
|
||||
std::vector<std::shared_ptr<arrow::Table>> segment_tables;
|
||||
for (uint64_t start_row : sorted_starts) {
|
||||
auto &col_map = segments[start_row];
|
||||
uint32_t count = segment_doc_count[start_row];
|
||||
|
||||
std::vector<std::shared_ptr<arrow::Field>> fields;
|
||||
std::vector<std::shared_ptr<arrow::ChunkedArray>> columns;
|
||||
|
||||
for (const auto &kv : col_map) {
|
||||
fields.push_back(kv.second.first);
|
||||
columns.push_back(kv.second.second);
|
||||
}
|
||||
|
||||
auto schema = std::make_shared<arrow::Schema>(fields);
|
||||
std::shared_ptr<arrow::Table> table =
|
||||
arrow::Table::Make(schema, columns, count);
|
||||
if (!table) {
|
||||
return arrow::Status::Invalid(
|
||||
"Failed to create table from schema and columns");
|
||||
}
|
||||
segment_tables.push_back(table);
|
||||
}
|
||||
|
||||
ARROW_ASSIGN_OR_RAISE(auto final_table,
|
||||
arrow::ConcatenateTables(segment_tables));
|
||||
auto dataset = std::make_shared<arrow::dataset::InMemoryDataset>(final_table);
|
||||
return dataset;
|
||||
}
|
||||
|
||||
inline arrow::Result<std::shared_ptr<arrow::Table>>
|
||||
EvaluateExpressionWithDataset(
|
||||
const std::shared_ptr<arrow::dataset::Dataset> &dataset,
|
||||
const std::string &new_column_name, const arrow::compute::Expression &expr,
|
||||
const std::shared_ptr<arrow::DataType> &expected_type) {
|
||||
auto new_scan_result = dataset->NewScan();
|
||||
if (!new_scan_result.ok()) {
|
||||
return arrow::Status::Invalid("Failed to create scanner builder");
|
||||
}
|
||||
auto scanner_builder = std::move(new_scan_result.ValueOrDie());
|
||||
|
||||
arrow::compute::CastOptions cast_options;
|
||||
cast_options.to_type = expected_type;
|
||||
cast_options.allow_int_overflow = true;
|
||||
cast_options.allow_float_truncate = true;
|
||||
arrow::Expression cast_expr = call("cast", {expr}, cast_options);
|
||||
|
||||
auto status = scanner_builder->Project({cast_expr}, {new_column_name});
|
||||
if (!status.ok()) {
|
||||
return arrow::Status::Invalid("Failed to project expression: ",
|
||||
status.ToString());
|
||||
}
|
||||
auto scanner_result = scanner_builder->Finish();
|
||||
if (!scanner_result.ok()) {
|
||||
return arrow::Status::Invalid("Failed to finish scanner builder: ",
|
||||
scanner_result.status().ToString());
|
||||
}
|
||||
auto scanner = std::move(scanner_result.ValueOrDie());
|
||||
|
||||
auto to_table_result = scanner->ToTable();
|
||||
if (!to_table_result.ok()) {
|
||||
return arrow::Status::Invalid("Failed to convert scanner to table: ",
|
||||
to_table_result.status().ToString());
|
||||
}
|
||||
auto result_table = std::move(to_table_result.ValueOrDie());
|
||||
return result_table;
|
||||
}
|
||||
|
||||
inline arrow::Status WriteColumnInBlocks(
|
||||
const std::string &column_name,
|
||||
const std::shared_ptr<arrow::ChunkedArray> &data,
|
||||
const std::vector<BlockMeta> &blocks, const std::string &base_path,
|
||||
uint32_t segment_id, std::function<BlockID()> allocate_block_id,
|
||||
bool use_parquet, std::vector<BlockMeta> *out) {
|
||||
int offset = 0;
|
||||
for (const auto &block : blocks) {
|
||||
auto slice = data->Slice(offset, block.doc_count_);
|
||||
auto field = arrow::field(column_name, slice->type());
|
||||
auto physic_schema = arrow::schema({field});
|
||||
auto table = arrow::Table::Make(arrow::schema({field}), {slice});
|
||||
|
||||
BlockID block_id = allocate_block_id();
|
||||
std::string path = FileHelper::MakeForwardBlockPath(base_path, segment_id,
|
||||
block_id, use_parquet);
|
||||
auto writer = ChunkedFileWriter::Open(
|
||||
path, physic_schema,
|
||||
use_parquet ? FileFormat::PARQUET : FileFormat::IPC);
|
||||
ARROW_RETURN_NOT_OK(writer->Write(*table));
|
||||
ARROW_RETURN_NOT_OK(writer->Close());
|
||||
|
||||
BlockMeta new_block(block_id, BlockType::SCALAR, block.min_doc_id_,
|
||||
block.max_doc_id_, block.doc_count_, {column_name});
|
||||
|
||||
out->push_back(new_block);
|
||||
|
||||
offset += block.doc_count_;
|
||||
}
|
||||
return arrow::Status::OK();
|
||||
}
|
||||
|
||||
inline int64_t MemorySize(const arrow::RecordBatch &batch) {
|
||||
int64_t total = 0;
|
||||
for (int i = 0; i < batch.num_columns(); ++i) {
|
||||
const auto &array = batch.column(i);
|
||||
const auto &data = array->data();
|
||||
for (const auto &buffer : data->buffers) {
|
||||
if (buffer) {
|
||||
total += buffer->size();
|
||||
}
|
||||
}
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
} // namespace zvec
|
||||
@@ -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 "local_wal_file.h"
|
||||
#include <unistd.h>
|
||||
#include <ailego/hash/crc32c.h>
|
||||
#include <ailego/logger/logger.h>
|
||||
#include "db/common/error_code.h"
|
||||
#include "db/common/file_helper.h"
|
||||
#include "db/common/typedef.h"
|
||||
|
||||
#define MAX_RECORD_SIZE 4194304 // 4Mb
|
||||
|
||||
namespace zvec {
|
||||
|
||||
int LocalWalFile::append(std::string &&data) {
|
||||
WalRecord record;
|
||||
record.length_ = data.size();
|
||||
record.crc_ = ailego::Crc32c::Hash(
|
||||
reinterpret_cast<const void *>(data.data()), record.length_, 0);
|
||||
record.content_ = std::forward<std::string>(data);
|
||||
|
||||
if (write_record(record) < 0) {
|
||||
WLOG_ERROR("Wal write record error. record.length_[%zu]",
|
||||
(size_t)record.length_);
|
||||
return -1;
|
||||
}
|
||||
// if max_docs_wal_flush_ is 0, no need flush
|
||||
if (max_docs_wal_flush_ != 0 && docs_count_ >= max_docs_wal_flush_) {
|
||||
if (!file_.flush()) {
|
||||
WLOG_ERROR("Wal flush error. docs_count_[%zu] max_docs_wal_flush_[%zu]",
|
||||
(size_t)docs_count_, (size_t)max_docs_wal_flush_);
|
||||
}
|
||||
docs_count_ = 0;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
std::string LocalWalFile::next() {
|
||||
WalRecord record;
|
||||
if (read_record(record) > 0) {
|
||||
uint32_t tmp_crc = ailego::Crc32c::Hash(
|
||||
reinterpret_cast<const void *>(record.content_.data()), record.length_,
|
||||
0);
|
||||
if (tmp_crc == record.crc_) {
|
||||
return std::move(record.content_);
|
||||
} else {
|
||||
WLOG_ERROR(
|
||||
"Wal next error. record.length_[%zu] crc_[%zu] != tmp_crc[%zu]",
|
||||
(size_t)record.length_, (size_t)record.crc_, (size_t)tmp_crc);
|
||||
}
|
||||
}
|
||||
// end of file or read error
|
||||
return std::string();
|
||||
}
|
||||
|
||||
int LocalWalFile::open(const WalOptions &wal_option) {
|
||||
CHECK_STATUS(opened_, false);
|
||||
if (wal_option.create_new) {
|
||||
if (FileHelper::FileExists(wal_path_)) {
|
||||
WLOG_ERROR("Wal open error. file already exist create_new[%d]",
|
||||
wal_option.create_new);
|
||||
return -1;
|
||||
}
|
||||
|
||||
if (!file_.create(wal_path_, false)) {
|
||||
WLOG_ERROR("Wal create error. create_new[%d]", wal_option.create_new);
|
||||
return -1;
|
||||
}
|
||||
|
||||
// write wal header
|
||||
int write_size = file_.write((const void *)&header_, sizeof(header_));
|
||||
if (write_size != sizeof(header_)) {
|
||||
WLOG_ERROR("Wal write header error. create_new[%d]",
|
||||
wal_option.create_new);
|
||||
return -1;
|
||||
}
|
||||
|
||||
} else {
|
||||
if (!FileHelper::FileExists(wal_path_)) {
|
||||
WLOG_ERROR("Wal open error. file is not exist create_new[%d]",
|
||||
wal_option.create_new);
|
||||
return -1;
|
||||
}
|
||||
|
||||
if (!file_.open(wal_path_.c_str(), false)) {
|
||||
WLOG_ERROR("Wal open error. create_new[%d]", wal_option.create_new);
|
||||
return -1;
|
||||
}
|
||||
|
||||
// open default for write
|
||||
file_.seek(0, ailego::File::Origin::End);
|
||||
}
|
||||
|
||||
max_docs_wal_flush_ = wal_option.max_docs_wal_flush;
|
||||
opened_ = true;
|
||||
|
||||
WLOG_INFO("Wal open success. create_new[%d]", wal_option.create_new);
|
||||
return 0;
|
||||
}
|
||||
|
||||
int LocalWalFile::close() {
|
||||
CHECK_STATUS(opened_, true);
|
||||
file_.close();
|
||||
WLOG_INFO("Wal close success");
|
||||
opened_ = false;
|
||||
return 0;
|
||||
}
|
||||
|
||||
int LocalWalFile::remove() {
|
||||
if (opened_) {
|
||||
close();
|
||||
}
|
||||
if (FileHelper::FileExists(wal_path_)) {
|
||||
FileHelper::RemoveFile(wal_path_);
|
||||
WLOG_INFO("Wal remove success.");
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
int LocalWalFile::flush() {
|
||||
CHECK_STATUS(opened_, true);
|
||||
if (!file_.flush()) {
|
||||
WLOG_ERROR("Wal flush error.");
|
||||
return -1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
int LocalWalFile::prepare_for_read() {
|
||||
CHECK_STATUS(opened_, true);
|
||||
if (!file_.seek(0, ailego::File::Origin::Begin)) {
|
||||
return -1;
|
||||
}
|
||||
int read_size = file_.read((void *)&header_, sizeof(header_));
|
||||
if (read_size != sizeof(header_)) {
|
||||
WLOG_ERROR("Wal read header error.");
|
||||
return -1;
|
||||
}
|
||||
if (header_.wal_version != 0UL) {
|
||||
WLOG_ERROR("Wal version not support error.");
|
||||
return -1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
//! Return 1 if success or -1 if write error
|
||||
int LocalWalFile::write_record(WalRecord &record) {
|
||||
CHECK_STATUS(opened_, true);
|
||||
|
||||
int write_size = 0;
|
||||
int ret = -1;
|
||||
|
||||
std::lock_guard<std::mutex> lock(file_mutex_);
|
||||
do {
|
||||
write_size = file_.write((const void *)&record.length_, LENGTH_SIZE);
|
||||
if (write_size != LENGTH_SIZE) {
|
||||
WLOG_ERROR("Wal write error. record.length_ error write_size[%d]",
|
||||
write_size);
|
||||
break;
|
||||
}
|
||||
|
||||
write_size = file_.write((const void *)&record.crc_, CRC_SIZE);
|
||||
if (write_size != CRC_SIZE) {
|
||||
WLOG_ERROR("Wal write error. record.crc_ error write_size[%d]",
|
||||
write_size);
|
||||
break;
|
||||
}
|
||||
|
||||
write_size =
|
||||
file_.write((const void *)record.content_.data(), record.length_);
|
||||
if (write_size != (int)record.length_) {
|
||||
WLOG_ERROR("Wal write error. record.content_ error write_size[%d]",
|
||||
write_size);
|
||||
break;
|
||||
}
|
||||
ret = 1; // write one record success
|
||||
docs_count_++;
|
||||
} while (false);
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
//! Return 1 if success or 0 if eof or -1 if read error
|
||||
int LocalWalFile::read_record(WalRecord &record) {
|
||||
CHECK_STATUS(opened_, true);
|
||||
|
||||
int read_size = 0;
|
||||
std::string err_msg;
|
||||
int ret = -1;
|
||||
|
||||
do {
|
||||
read_size =
|
||||
file_.read(reinterpret_cast<void *>(&record.length_), LENGTH_SIZE);
|
||||
if (read_size == 0) {
|
||||
ret = 0;
|
||||
WLOG_INFO("Wal read finished. end of file");
|
||||
break;
|
||||
}
|
||||
|
||||
if (read_size != LENGTH_SIZE) {
|
||||
WLOG_ERROR("Wal read error. record.length_ error read_size[%d]",
|
||||
read_size);
|
||||
break;
|
||||
}
|
||||
|
||||
read_size = file_.read(reinterpret_cast<void *>(&record.crc_), CRC_SIZE);
|
||||
if (read_size != CRC_SIZE) {
|
||||
WLOG_ERROR("Wal read error. record.crc_ error read_size[%d]", read_size);
|
||||
break;
|
||||
}
|
||||
|
||||
// resize may crash if record.length_ very large
|
||||
if (record.length_ <= 0 || record.length_ > MAX_RECORD_SIZE) {
|
||||
WLOG_ERROR("Wal read error. record.length_ value error read_size[%d]",
|
||||
read_size);
|
||||
break;
|
||||
}
|
||||
|
||||
record.content_.resize(record.length_);
|
||||
read_size = file_.read((void *)const_cast<char *>(record.content_.data()),
|
||||
record.length_);
|
||||
if (read_size != (int)record.length_) {
|
||||
WLOG_ERROR("Wal read error. record.content_ error read_size[%d]",
|
||||
read_size);
|
||||
break;
|
||||
}
|
||||
ret = 1; // read one record success
|
||||
} while (false);
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
}; // namespace zvec
|
||||
@@ -0,0 +1,99 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
#pragma once
|
||||
|
||||
#include <atomic>
|
||||
#include <condition_variable>
|
||||
#include <deque>
|
||||
#include <fstream>
|
||||
#include <mutex>
|
||||
#include <thread>
|
||||
#include <unordered_map>
|
||||
#include <ailego/io/file.h>
|
||||
#include "wal_file.h"
|
||||
|
||||
namespace zvec {
|
||||
|
||||
/*
|
||||
* Wal Header info
|
||||
*/
|
||||
struct WalHeader {
|
||||
uint64_t wal_version{0U};
|
||||
uint64_t reserved_[7];
|
||||
};
|
||||
|
||||
static_assert(sizeof(WalHeader) % 64 == 0,
|
||||
"Wal Header must be aligned with 64 bytes");
|
||||
|
||||
class WalRecord {
|
||||
public:
|
||||
uint32_t length_;
|
||||
uint32_t crc_;
|
||||
std::string content_;
|
||||
};
|
||||
|
||||
class LocalWalFile : public WalFile {
|
||||
public:
|
||||
LocalWalFile(const LocalWalFile &) = delete;
|
||||
LocalWalFile &operator=(const LocalWalFile &) = delete;
|
||||
|
||||
//! Constructor
|
||||
LocalWalFile(const std::string &wal_path) : wal_path_(wal_path) {}
|
||||
|
||||
//! Destructor
|
||||
~LocalWalFile() {
|
||||
if (opened_) {
|
||||
close();
|
||||
}
|
||||
}
|
||||
|
||||
public:
|
||||
int append(std::string &&data) override;
|
||||
int prepare_for_read() override;
|
||||
std::string next() override;
|
||||
|
||||
public:
|
||||
int open(const WalOptions &wal_option) override;
|
||||
|
||||
int close() override;
|
||||
|
||||
int flush() override;
|
||||
|
||||
int remove() override;
|
||||
|
||||
bool has_record() override {
|
||||
return file_.size() > sizeof(header_);
|
||||
}
|
||||
|
||||
private:
|
||||
int write_record(WalRecord &record);
|
||||
int read_record(WalRecord &record);
|
||||
|
||||
private:
|
||||
ailego::File file_;
|
||||
const static int32_t LENGTH_SIZE{4};
|
||||
const static int32_t CRC_SIZE{4};
|
||||
|
||||
private:
|
||||
std::string wal_path_{};
|
||||
std::mutex file_mutex_;
|
||||
uint32_t max_docs_wal_flush_{0};
|
||||
std::atomic<uint64_t> docs_count_{0UL};
|
||||
WalHeader header_;
|
||||
|
||||
bool opened_{false};
|
||||
};
|
||||
|
||||
|
||||
}; // namespace zvec
|
||||
@@ -0,0 +1,33 @@
|
||||
// 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 "wal_file.h"
|
||||
#include "local_wal_file.h"
|
||||
|
||||
namespace zvec {
|
||||
|
||||
WalFilePtr WalFile::Create(const std::string &wal_path) {
|
||||
return std::make_shared<LocalWalFile>(wal_path);
|
||||
}
|
||||
|
||||
int WalFile::CreateAndOpen(const std::string &wal_path,
|
||||
const WalOptions &wal_options,
|
||||
WalFilePtr *wal_file) {
|
||||
*wal_file = std::make_shared<LocalWalFile>(wal_path);
|
||||
|
||||
return (*wal_file)->open(wal_options);
|
||||
}
|
||||
|
||||
|
||||
}; // namespace zvec
|
||||
@@ -0,0 +1,68 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
#pragma once
|
||||
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
|
||||
namespace zvec {
|
||||
|
||||
class WalFile;
|
||||
|
||||
using WalFilePtr = std::shared_ptr<WalFile>;
|
||||
|
||||
struct WalOptions {
|
||||
uint32_t max_docs_wal_flush{0};
|
||||
bool create_new{false};
|
||||
};
|
||||
|
||||
class WalFile {
|
||||
public:
|
||||
//! Constructor
|
||||
WalFile() {}
|
||||
|
||||
//! Destructor
|
||||
virtual ~WalFile() {} // LCOV_EXCL_LINE
|
||||
|
||||
//! Create an instance
|
||||
static WalFilePtr Create(const std::string &wal_path);
|
||||
|
||||
//! Crate an instance and open
|
||||
static int CreateAndOpen(const std::string &wal_path,
|
||||
const WalOptions &wal_options, WalFilePtr *wal_file);
|
||||
|
||||
public:
|
||||
virtual int append(std::string &&data) = 0;
|
||||
virtual int prepare_for_read() = 0;
|
||||
virtual std::string next() = 0;
|
||||
|
||||
public:
|
||||
//! Open and initialize WalFile
|
||||
virtual int open(const WalOptions &wal_options) = 0;
|
||||
|
||||
//! Close WalFile
|
||||
virtual int close() = 0;
|
||||
|
||||
//! Remove wal disk file
|
||||
virtual int remove() = 0;
|
||||
|
||||
//! Flush WalFile's memory to disk file
|
||||
virtual int flush() = 0;
|
||||
|
||||
virtual bool has_record() = 0;
|
||||
};
|
||||
|
||||
}; // namespace zvec
|
||||
@@ -0,0 +1,174 @@
|
||||
syntax = "proto3";
|
||||
|
||||
package zvec.proto;
|
||||
|
||||
option cc_enable_arenas = true;
|
||||
|
||||
// The Go package name, refers to
|
||||
// https://developers.google.com/protocol-buffers/docs/reference/go-generated#package
|
||||
option go_package = "proxima/zvec/proto";
|
||||
|
||||
/*! Types of Data
|
||||
*/
|
||||
enum DataType {
|
||||
DT_UNDEFINED = 0;
|
||||
|
||||
DT_BINARY = 1;
|
||||
DT_STRING = 2;
|
||||
DT_BOOL = 3;
|
||||
DT_INT32 = 4;
|
||||
DT_INT64 = 5;
|
||||
DT_UINT32 = 6;
|
||||
DT_UINT64 = 7;
|
||||
DT_FLOAT = 8;
|
||||
DT_DOUBLE = 9;
|
||||
|
||||
DT_VECTOR_BINARY32 = 20;
|
||||
DT_VECTOR_BINARY64 = 21;
|
||||
DT_VECTOR_FP16 = 22;
|
||||
DT_VECTOR_FP32 = 23;
|
||||
DT_VECTOR_FP64 = 24;
|
||||
DT_VECTOR_INT4 = 25;
|
||||
DT_VECTOR_INT8 = 26;
|
||||
DT_VECTOR_INT16 = 27;
|
||||
|
||||
DT_SPARSE_VECTOR_FP16 = 30;
|
||||
DT_SPARSE_VECTOR_FP32 = 31;
|
||||
|
||||
// ARRAY
|
||||
DT_ARRAY_BINARY = 40;
|
||||
DT_ARRAY_STRING = 41;
|
||||
DT_ARRAY_BOOL = 42;
|
||||
DT_ARRAY_INT32 = 43;
|
||||
DT_ARRAY_INT64 = 44;
|
||||
DT_ARRAY_UINT32 = 45;
|
||||
DT_ARRAY_UINT64 = 46;
|
||||
DT_ARRAY_FLOAT = 47;
|
||||
DT_ARRAY_DOUBLE = 48;
|
||||
};
|
||||
|
||||
enum IndexType {
|
||||
// Undefined
|
||||
IT_UNDEFINED = 0;
|
||||
// Proxima HNSW Index
|
||||
IT_HNSW = 1;
|
||||
// Proxima IVF Index
|
||||
IT_IVF = 2;
|
||||
// Proxima FLAT Index
|
||||
IT_FLAT = 3;
|
||||
// Invert Index
|
||||
IT_INVERT = 10;
|
||||
};
|
||||
|
||||
enum QuantizeType {
|
||||
QT_UNDEFINED = 0;
|
||||
QT_FP16 = 1;
|
||||
QT_INT8 = 2;
|
||||
QT_INT4 = 3;
|
||||
};
|
||||
|
||||
enum MetricType {
|
||||
MT_UNDEFINED = 0;
|
||||
MT_L2 = 1;
|
||||
MT_IP = 2;
|
||||
MT_COSINE = 3;
|
||||
};
|
||||
|
||||
message InvertIndexParams { bool enable_range_optimization = 1; };
|
||||
|
||||
message BaseIndexParams {
|
||||
MetricType metric_type = 1;
|
||||
QuantizeType quantize_type = 2;
|
||||
};
|
||||
|
||||
message HnswIndexParams {
|
||||
BaseIndexParams base = 1;
|
||||
int32 m = 2;
|
||||
int32 ef_construction = 3;
|
||||
};
|
||||
|
||||
message FlatIndexParams {
|
||||
BaseIndexParams base = 1;
|
||||
}
|
||||
|
||||
message IVFIndexParams {
|
||||
BaseIndexParams base = 1;
|
||||
int32 n_list = 2;
|
||||
int32 n_iters = 3;
|
||||
bool use_soar = 4;
|
||||
}
|
||||
|
||||
message IndexParams {
|
||||
oneof params {
|
||||
InvertIndexParams invert = 1;
|
||||
HnswIndexParams hnsw = 2;
|
||||
FlatIndexParams flat = 3;
|
||||
IVFIndexParams ivf = 4;
|
||||
};
|
||||
};
|
||||
|
||||
message FieldSchema {
|
||||
string name = 1;
|
||||
DataType data_type = 2;
|
||||
uint32 dimension = 3;
|
||||
bool nullable = 4;
|
||||
IndexParams index_params = 5;
|
||||
};
|
||||
|
||||
message CollectionSchema {
|
||||
string name = 1;
|
||||
repeated FieldSchema fields = 2;
|
||||
uint64 max_doc_count_per_segment = 3;
|
||||
};
|
||||
|
||||
enum BlockType {
|
||||
BT_UNDEFINED = 0;
|
||||
BT_SCALAR = 1;
|
||||
BT_SCALAR_INDEX = 2;
|
||||
BT_VECTOR_INDEX = 3;
|
||||
BT_VECTOR_INDEX_QUANTIZE = 4;
|
||||
};
|
||||
|
||||
message BlockMeta {
|
||||
uint32 block_id = 1;
|
||||
BlockType block_type = 2; // for getting filename prefix
|
||||
uint64 min_doc_id = 3;
|
||||
uint64 max_doc_id = 4;
|
||||
uint64 doc_count = 5;
|
||||
repeated string columns = 6; // columns contained in this block
|
||||
};
|
||||
|
||||
// message AlterColumnMeta {
|
||||
// string old_column_name = 1;
|
||||
// FieldSchema new_schema = 2;
|
||||
// };
|
||||
|
||||
message SegmentMeta {
|
||||
uint32 segment_id = 1;
|
||||
// scalar data, vector data and vector index
|
||||
repeated BlockMeta persisted_blocks = 2;
|
||||
|
||||
BlockMeta writing_forward_block = 3;
|
||||
|
||||
// if indexed, index_params can be retrieved from schema
|
||||
// if not indexed, index_params is default index_params(flat)
|
||||
repeated string indexed_vector_fields = 4;
|
||||
// repeated AlterColumnMeta alter_columns = 10;
|
||||
};
|
||||
|
||||
message Manifest {
|
||||
uint32 version = 1;
|
||||
|
||||
CollectionSchema schema = 2;
|
||||
|
||||
bool enable_mmap = 3;
|
||||
|
||||
repeated SegmentMeta persisted_segment_metas = 4;
|
||||
|
||||
SegmentMeta writing_segment_meta = 5;
|
||||
|
||||
uint32 id_map_path_suffix = 6;
|
||||
uint32 delete_snapshot_path_suffix = 7;
|
||||
|
||||
uint32 next_segment_id = 8;
|
||||
};
|
||||
@@ -0,0 +1,25 @@
|
||||
include(${PROJECT_ROOT_DIR}/cmake/bazel.cmake)
|
||||
include(${PROJECT_ROOT_DIR}/cmake/option.cmake)
|
||||
|
||||
|
||||
cc_library(
|
||||
NAME zvec_parser STATIC STRICT
|
||||
SRCS common/*.cc antlr/gen/*.cc parser/*.cc
|
||||
LIBS zvec_common
|
||||
antlr4
|
||||
zvec_index
|
||||
INCS ${PROJECT_ROOT_DIR}/src
|
||||
VERSION "${PROXIMA_ZVEC_VERSION}"
|
||||
)
|
||||
|
||||
cc_library(
|
||||
NAME zvec_sqlengine STATIC STRICT
|
||||
SRCS *.cc analyzer/*.cc planner/*.cc planner/ops/*.cc planner/physical_rules/*.cc
|
||||
LIBS zvec_index
|
||||
zvec_common
|
||||
zvec_parser
|
||||
antlr4
|
||||
Arrow::arrow_acero
|
||||
INCS . ${PROJECT_ROOT_DIR}/src
|
||||
VERSION "${PROXIMA_ZVEC_VERSION}"
|
||||
)
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user