欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python使用Oracle向量數(shù)據(jù)庫實現(xiàn)文本檢索系統(tǒng)

 更新時間:2024年07月04日 10:39:21   作者:engchina  
在本文中,我們將深入分析一個使用Oracle向量數(shù)據(jù)庫實現(xiàn)文本檢索系統(tǒng)的Python代碼,并基于相同的技術生成一個新的示例,這個系統(tǒng)允許我們存儲文檔及其嵌入向量,并執(zhí)行相似性搜索,感興趣的朋友可以參考下

代碼分析

讓我們逐步分析原始代碼的主要組件和功能:

  1. 導入必要的庫:

    • 使用oracledb連接Oracle數(shù)據(jù)庫
    • 使用numpy處理向量
    • 使用pydantic進行配置驗證
    • 使用flaskredis進行Web應用程序集成
  2. 定義OracleVectorConfig類:

    • 使用Pydantic模型驗證Oracle連接配置
  3. 創(chuàng)建OracleVector類:

    • 實現(xiàn)向量數(shù)據(jù)庫的核心功能
    • 使用contextmanager管理數(shù)據(jù)庫連接
    • 實現(xiàn)CRUD操作和向量搜索
  4. 實現(xiàn)OracleVectorFactory類:

    • 用于初始化向量數(shù)據(jù)庫實例

現(xiàn)在,讓我們基于相同的技術創(chuàng)建一個新的示例代碼:

import array
import json
import uuid
from contextlib import contextmanager
from typing import List, Dict, Any

import numpy as np
import oracledb
from pydantic import BaseModel, validator

class OracleConfig(BaseModel):
    host: str
    port: int
    user: str
    password: str
    database: str

    @validator('host', 'user', 'password', 'database')
    def check_not_empty(cls, v):
        if not v:
            raise ValueError("Field cannot be empty")
        return v

class TextEmbeddingStore:
    def __init__(self, config: OracleConfig):
        self.pool = self._create_connection_pool(config)
        self.table_name = "text_embeddings"
        self._create_table()

    def _create_connection_pool(self, config: OracleConfig):
        return oracledb.create_pool(
            user=config.user,
            password=config.password,
            dsn=f"{config.host}:{config.port}/{config.database}",
            min=1,
            max=5,
            increment=1
        )

    @contextmanager
    def _get_cursor(self):
        conn = self.pool.acquire()
        conn.inputtypehandler = self._input_type_handler
        conn.outputtypehandler = self._output_type_handler
        cur = conn.cursor()
        try:
            yield cur
        finally:
            cur.close()
            conn.commit()
            conn.close()

    def _input_type_handler(self, cursor, value, arraysize):
        if isinstance(value, np.ndarray):
            return cursor.var(
                oracledb.DB_TYPE_VECTOR,
                arraysize=arraysize,
                inconverter=self._numpy_to_array
            )

    def _output_type_handler(self, cursor, metadata):
        if metadata.type_code is oracledb.DB_TYPE_VECTOR:
            return cursor.var(
                metadata.type_code,
                arraysize=cursor.arraysize,
                outconverter=self._array_to_numpy
            )

    def _numpy_to_array(self, value):
        return array.array('f', value)

    def _array_to_numpy(self, value):
        return np.array(value, dtype=np.float32)

    def _create_table(self):
        with self._get_cursor() as cur:
            cur.execute(f"""
                CREATE TABLE IF NOT EXISTS {self.table_name} (
                    id VARCHAR2(100) PRIMARY KEY,
                    text CLOB NOT NULL,
                    metadata JSON,
                    embedding VECTOR NOT NULL
                )
            """)

    def add_texts(self, texts: List[str], embeddings: List[List[float]], metadata: List[Dict] = None):
        if metadata is None:
            metadata = [{} for _ in texts]
        
        values = [
            (str(uuid.uuid4()), text, json.dumps(meta), np.array(emb, dtype=np.float32))
            for text, emb, meta in zip(texts, embeddings, metadata)
        ]

        with self._get_cursor() as cur:
            cur.executemany(
                f"INSERT INTO {self.table_name} (id, text, metadata, embedding) VALUES (:1, :2, :3, :4)",
                values
            )

    def search_similar(self, query_vector: List[float], top_k: int = 5) -> List[Dict[str, Any]]:
        query_vector = np.array(query_vector, dtype=np.float32)
        with self._get_cursor() as cur:
            cur.execute(
                f"""
                SELECT id, text, metadata, vector_distance(embedding, :1) AS distance
                FROM {self.table_name}
                ORDER BY distance
                FETCH FIRST :2 ROWS ONLY
                """,
                [query_vector, top_k]
            )
            results = []
            for id, text, metadata, distance in cur:
                results.append({
                    "id": id,
                    "text": text,
                    "metadata": json.loads(metadata),
                    "distance": distance,
                    "similarity": 1 - distance
                })
        return results

# 使用示例
if __name__ == "__main__":
    config = OracleConfig(
        host="localhost",
        port=1521,
        user="your_username",
        password="your_password",
        database="your_database"
    )
    
    store = TextEmbeddingStore(config)
    
    # 添加文本和嵌入
    texts = ["Hello world", "Python programming", "Vector database"]
    embeddings = [[0.1, 0.2, 0.3], [0.4, 0.5, 0.6], [0.7, 0.8, 0.9]]
    store.add_texts(texts, embeddings)
    
    # 搜索相似文本
    query_vector = [0.2, 0.3, 0.4]
    results = store.search_similar(query_vector, top_k=2)
    
    for result in results:
        print(f"Text: {result['text']}")
        print(f"Similarity: {result['similarity']:.4f}")
        print("---")

這個新的示例代碼實現(xiàn)了一個簡化版的文本嵌入存儲系統(tǒng),使用Oracle向量數(shù)據(jù)庫。它包含以下主要功能:

  1. 使用Pydantic進行配置驗證
  2. 創(chuàng)建和管理Oracle連接池
  3. 使用上下文管理器處理數(shù)據(jù)庫連接
  4. 處理numpy數(shù)組和Oracle向量類型之間的轉換
  5. 實現(xiàn)添加文本和嵌入的方法
  6. 實現(xiàn)基于向量相似度的搜索方法

這個示例展示了如何使用Oracle向量數(shù)據(jù)庫來存儲和檢索文本嵌入,可以作為構建更復雜的文本檢索或推薦系統(tǒng)的基礎。

在實際應用中,你可能需要添加錯誤處理、日志記錄、性能優(yōu)化等功能。

到此這篇關于Python使用Oracle向量數(shù)據(jù)庫實現(xiàn)文本檢索系統(tǒng)的文章就介紹到這了,更多相關Python Oracle文本檢索系統(tǒng)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

最新評論