wpdb = $wpdb; $this->table = $wpdb->prefix . 'shoponix_product_vectors'; } public function add_vector($product_id, $content, $embedding) { $res = $this->wpdb->insert($this->table, [ 'product_id' => $product_id, 'content' => $content, 'embedding' => json_encode($embedding) ]); $this->clear_cache(); return $res; } public function delete_vector($product_id) { $res = $this->wpdb->delete($this->table, ['product_id' => $product_id]); $this->clear_cache(); return $res; } public function get_product_content($product_id) { global $wpdb; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared return $wpdb->get_var($wpdb->prepare("SELECT content FROM {$this->table} WHERE product_id = %d LIMIT 1", $product_id)); } public function clear_vectors() { global $wpdb; $res = $wpdb->query("TRUNCATE TABLE {$this->table}"); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared $this->clear_cache(); return $res; } public function clear_cache() { delete_transient('shoponix_cached_vectors'); } public function find_similar($query_embedding, $top_k = 5) { $cached_vectors = get_transient('shoponix_cached_vectors'); if (false === $cached_vectors) { global $wpdb; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared $rows = $wpdb->get_results("SELECT id, product_id, content, embedding FROM {$this->table} LIMIT 2000"); $cached_vectors = []; foreach ($rows as $row) { $vec = json_decode($row->embedding, true); if (!$vec) continue; $cached_vectors[] = [ 'product_id' => $row->product_id, 'content' => $row->content, 'embedding' => $vec ]; } set_transient('shoponix_cached_vectors', $cached_vectors, 12 * HOUR_IN_SECONDS); } $similarities = []; foreach ($cached_vectors as $item) { $similarity = $this->cosine_similarity($query_embedding, $item['embedding']); $similarities[] = [ 'similarity' => $similarity, 'product_id' => $item['product_id'], 'content' => $item['content'] ]; } usort($similarities, function ($a, $b) { return $b['similarity'] <=> $a['similarity']; }); return array_slice($similarities, 0, $top_k); } private function cosine_similarity($a, $b) { if (count($a) !== count($b)) return 0; $dot = 0; $normA = 0; $normB = 0; for ($i = 0; $i < count($a); $i++) { $dot += $a[$i] * $b[$i]; $normA += $a[$i] * $a[$i]; $normB += $b[$i] * $b[$i]; } if ($normA == 0 || $normB == 0) return 0; return $dot / (sqrt($normA) * sqrt($normB)); } }