@@ -47,12 +47,13 @@ class Vector extends Model
4747
4848 public static function isSupportedByMariaDb (): bool
4949 {
50- return \Illuminate \Support \Facades \Cache::remember (" is_vector_supported " , now ()->addDays (120 ), function () {
50+ return \Illuminate \Support \Facades \Cache::remember (' is_vector_supported ' , now ()->addDays (120 ), function () {
5151 try {
5252 $ version = DB ::select ('SELECT VERSION() as version ' )[0 ]->version ;
5353
54- if (!str_contains (strtolower ($ version ), 'mariadb ' )) {
54+ if (! str_contains (strtolower ($ version ), 'mariadb ' )) {
5555 Log::warning ('The current database is not MariaDB ' );
56+
5657 return false ;
5758 }
5859
@@ -63,33 +64,59 @@ public static function isSupportedByMariaDb(): bool
6364 return true ;
6465 }
6566
66- Log::warning ('MariaDB must be at least 11.7 to support vectors. Current version is ' . $ version );
67+ Log::warning ('MariaDB must be at least 11.7 to support vectors. Current version is ' .$ version );
68+
6769 return false ;
6870
6971 } catch (\Exception $ e ) {
7072 Log::warning ($ e ->getMessage ());
73+
7174 return false ;
7275 }
7376 });
7477 }
7578
7679 public static function insertVector (int $ collectionId , int $ fileId , int $ chunkId , string $ locale , string $ hypotheticalQuestion , array $ embedding ): bool
7780 {
78- if (!empty ($ embedding )) {
79- $ sql = "INSERT INTO cb_vectors (collection_id, file_id, locale, hypothetical_question, embedding, chunk_id, created_by, updated_at, created_at) VALUES (?, ?, ?, ?, VEC_FromText(?), ?, ?, NOW(), NOW()) " ;
81+ if (! empty ($ embedding )) {
82+ $ sql = 'INSERT INTO cb_vectors (collection_id, file_id, locale, hypothetical_question, embedding, chunk_id, created_by, updated_at, created_at) VALUES (?, ?, ?, ?, VEC_FromText(?), ?, ?, NOW(), NOW()) ' ;
83+
8084 return DB ::statement ($ sql , [
8185 $ collectionId ,
8286 $ fileId ,
8387 $ locale ,
8488 $ hypotheticalQuestion ,
85- ' [ ' . implode ( " , " , $ embedding ) . ' ] ' ,
89+ self :: formatEmbedding ( $ embedding ),
8690 $ chunkId ,
87- Auth::user ()?->id
91+ Auth::user ()?->id,
8892 ]);
8993 }
94+
9095 return false ;
9196 }
9297
98+ public function setEmbeddingAttribute ($ value ): void
99+ {
100+ if (! is_array ($ value )) {
101+ $ this ->attributes ['embedding ' ] = $ value ;
102+
103+ return ;
104+ }
105+
106+ if (self ::isSupportedByMariaDb ()) {
107+ $ this ->attributes ['embedding ' ] = DB ::raw ("VEC_FromText(' " .self ::formatEmbedding ($ value )."') " );
108+
109+ return ;
110+ }
111+
112+ $ this ->attributes ['embedding ' ] = json_encode ($ value );
113+ }
114+
115+ private static function formatEmbedding (array $ embedding ): string
116+ {
117+ return '[ ' .implode (', ' , array_map (static fn ($ value ) => (string ) $ value , $ embedding )).'] ' ;
118+ }
119+
93120 public function collection (): HasOne
94121 {
95122 return $ this ->hasOne (Collection::class, 'id ' , 'collection_id ' );
0 commit comments