import { existsSync, readFileSync, writeFileSync } from "fs"; import { ICollection } from "../../../interfaces/vectorDB/ICollection"; import { VectorResponseCommon } from "../../../types/vector"; import { CollectionCreateParams, CollectionCreateParamsIndex, CollectionDescribeParams, CollectionDescribeResponse, CollectionDropParams, CollectionListItem, CollectionListParams, CollectionListResponse, CollectionTruncateParams } from "../../../types/vector/collection"; import * as lancedb from "@lancedb/lancedb"; import * as arrow from "apache-arrow"; import { Connection } from '@lancedb/lancedb' import { LanceDBEmbeddingConfig } from "../../../types/lanceDB"; import { embedding } from "@lancedb/lancedb"; import { join } from "path"; import { Logger } from "../../../utils/Logger"; import { EmbeddingAPIType } from "../../../types/embedding"; export class LanceDBCollection implements ICollection { rootPath: string embeddingConfig?: LanceDBEmbeddingConfig // db?: Connection constructor(options?: { rootPath: string, embedding?: LanceDBEmbeddingConfig }) { this.rootPath = options?.rootPath || ""; this.embeddingConfig = options?.embedding } private async getDB(database: string): Promise { const dbPath = `${this.rootPath}/${database}` if (!existsSync(dbPath)) { return Promise.reject(`Database ${database} does not exist`) } const db = await lancedb.connect(dbPath) // this.db = db return db } private async getTable(database: string, collection: string): Promise { try { const db = await this.getDB(database) const tbl = await db.openTable(collection) return tbl } catch (err) { return Promise.reject(err) } } private checkCreateIndexParams(indexes: CollectionCreateParamsIndex[], type: "id" | "vector"): boolean { if (indexes.length === 0) { return false } if (type === "id") { return indexes.filter(item => item.fieldName === "id").length > 0 } else { return indexes.filter(item => item.fieldName === "vector").length > 0 } } async create(params: CollectionCreateParams, isAIPackage?: boolean): Promise { const db = await this.getDB(params.database) const fields: any = {} const embeddingField = params.embedding?.field || "text" const embeddingVectorField = params.embedding?.vectorField || "vector" params.indexes = params.indexes || [] as CollectionCreateParamsIndex[] if (!this.checkCreateIndexParams(params.indexes, "id")) { params.indexes.push({ fieldName: "id", fieldType: "string", indexType: "primaryKey" }) } params.indexes?.forEach(item => { if (item.fieldName !== embeddingField && item.fieldName !== embeddingVectorField) { fields[item.fieldName] = this.getFieldType(item.fieldType) } }) // fields[params.embedding?.field || "text"] = new arrow.Utf8() // const func = getRegistry().get("openai")?.create({ // model: "text-embedding-ada-002" // }) as EmbeddingFunction const func = embedding.getRegistry().get("reai_embedding")?.create({ model: this.embeddingConfig?.model, baseUrl: this.embeddingConfig?.baseUrl, type: this.embeddingConfig?.type, apiKey: this.embeddingConfig?.apiKey, topNum: this.embeddingConfig?.topNum }) if (!func) { return Promise.reject("Embedding function not found") } fields[embeddingField] = func.sourceField(new arrow.Utf8()) fields[embeddingVectorField] = func?.vectorField() // fields[params.embedding?.vectorField || "vector"] = func.vectorField() Logger.debug("create fields" , fields) const schema = embedding.LanceSchema(fields) await db.createEmptyTable(params.collection, schema, { // embeddingFunction: { // function: func, // sourceColumn: params.embedding?.field || "text", // vectorColumn: params.embedding?.vectorField || "vector" // }, mode: "overwrite" }) this.saveInfo(params.database, params.collection, params) return { code: 0, msg: "success", affectedCount: 0 } } private saveInfo(database: string, collection: string, info: CollectionCreateParams) { const embedding = { field: info.embedding?.field || "text", vectorField: info.embedding?.vectorField || "vector", model: info.embedding?.model } info.embedding = embedding info.indexes?.push({ fieldName: embedding.field, fieldType: "string", indexType: "filter" }) info.indexes?.push({ fieldName: embedding.vectorField, fieldType: "vector", indexType: "lanceDB" }) writeFileSync(join(this.rootPath, database, collection + ".lance", "_info.json"), JSON.stringify(info)) } private getInfo(database: string, collection: string) { return JSON.parse(readFileSync(join(this.rootPath, database, collection + ".lance", "_info.json"), "utf-8")) } private getFieldType(fieldType: string): any { switch (fieldType) { case "string": return new arrow.Utf8() case "uint64": return new arrow.Uint64() case "boolean": return new arrow.Bool() default: return new arrow.Utf8() } } async list(params: CollectionListParams, isAIPackage?: boolean): Promise { const db = await this.getDB(params.database) const tables = await db.tableNames() const collections = tables.map(item => this.getTableInfo(params.database, item)) return { code: 0, msg: "success", collections: collections } } private getTableInfo(database: string, tableName: string) { const info = this.getInfo(database, tableName) const item: CollectionListItem = { database, collection: tableName, } return Object.assign(item, info) } async describe(params: CollectionDescribeParams, isAIPackage?: boolean): Promise { const db = await this.getDB(params.database) try { await db.openTable(params.collection) return { code: 0, msg: "success", collection: this.getTableInfo(params.database, params.collection), } } catch (err) { return Promise.reject(err) } } async drop(params: CollectionDropParams, isAIPackage?: boolean): Promise { try { const db = await this.getDB(params.database) await db.dropTable(params.collection) return { code: 0, msg: "success", affectedCount: 0 } } catch (err) { return Promise.reject(err) } } async truncate(params: CollectionTruncateParams, isAIPackage?: boolean): Promise { try { const db = await this.getDB(params.database) const table = await db.openTable(params.collection) const count = await table.countRows() table.delete("id != ''") return { code: 0, msg: "success", affectedCount: count } } catch (err) { return Promise.reject(err) } } }