搜尋
首頁後端開發Python教學適用於 SQL 思維的 ChromaDB

ChromaDB for the SQL Mind

您好,Chroma DB 是一個向量資料庫,對於使用 GenAI 應用程式非常有用。在本文中,我將探討如何透過查看 MySQL 中的類似關係來在 Chroma DB 上執行查詢。

模式

與 SQL 不同,您無法定義自己的架構。在 Chroma 中,您會得到固定的列,每個列都有自己的用途:

import chromadb

#setiing up the client
client = chromadb.Client() 
collection = client.create_collection(name="name")

collection.add(
    documents = ["str1","str2","str3",...]
    ids = [1,2,3,....]
    metadatas=[{"chapter": "3", "verse": "16"},{"chapter":"3", "verse":"5"}, ..]           
    embeddings = [[1,2,3], [3,4,5], [5,6,7]]
)

Ids:它們是唯一的 id。請注意,您需要自己提供它們,與 sql 不同,沒有自動增量
文件: 用於插入用於產生嵌入的文字資料。您可以提供文本,它會自動建立嵌入。或者您可以直接提供嵌入並將文字儲存在其他位置。
嵌入: 在我看來,它們是資料庫中最重要的部分,因為它們用於執行相似性搜尋。
元資料:這用於關聯您可能想要新增到資料庫中以獲得任何額外上下文的任何其他資料。

現在集合的基礎知識已經清楚了,讓我們繼續進行 CRUD 操作,我們將了解如何查詢資料庫。

增刪改查操作

注意:集合就像 Chroma 中的表格

要建立集合,我們可以使用 create_collection() 並根據需要執行我們的操作,但如果集合已經建立並且我們需要再次引用它,我們必須使用 get_collection() 否則我們會收到錯誤。

Create Table tablename 
#Create a collection
collection = client.create_collection(name="name")

#If a collection is already made and you need to use it again the use
collection = client.get_collection(name="name")
Insert into tablename
Values(... , ..., ...)
collection.add(
    ids = [1]
    documents = ["some text"]
    metadatas = [{"key":"value"}]
    embeddings = [[1,2,3]]
)

要更新插入的數據或刪除數據,我們可以使用以下命令

collection.update(
    ids = [2]
    documents = ["some text"]
    metadatas = [{"key":"value"}]
    embeddings = [[1,2,3]]            
)

# If the id does not exist update will do nothing. to add data if id does not exist use
collection.upsert(
    ids = [2]
    documents = ["some text"]
    metadatas = [{"key":"value"}]
    embeddings = [[1,2,3]]            
)

# To delete data use delete and refrence the document or id or the feild
collection.delete(
    documents = ["some text"]         
)

# Or you can delete from a bunch of ids using where that will apply filter on metadata
collection.delete(
    ids=["id1", "id2", "id3",...],
    where={"chapter": "20"}
)

查詢

現在我們將看看某些查詢的樣子

Select * from tablename

Select * from tablename limit value

Select Documents, Metadata from tablename
collection.get()

collection.get(limit = val)

collection.get(include = ["documents","metadata"])

雖然 get() 用於獲取大量表以進行更高級的查詢,但您需要使用查詢方法

Select A,B from table
limit val
collection.query(
    n_results = val #limit
    includes = [A,B] 
)

現在我們有3種可能的方法來過濾資料:相似性搜尋(向量資料庫主要用於什麼),元資料過濾器和文件過濾器

相似性搜尋

我們可以根據文字或嵌入進行搜尋並獲得最相似的輸出

collection.query(query_texts=["string"])

collection.query(query_embeddings=[[1,2,3]])

ChromaDB 中,where 和 where_document 參數用於在查詢期間過濾 結果。這些篩選器可讓您根據元資料或特定文件內容優化相似性搜尋。

按元資料過濾

where 參數可讓您根據關聯的元資料過濾文件。元資料通常是您在文件插入期間提供的鍵值對的字典。

按類別、作者或日期等元資料過濾文件。

import chromadb

#setiing up the client
client = chromadb.Client() 
collection = client.create_collection(name="name")

collection.add(
    documents = ["str1","str2","str3",...]
    ids = [1,2,3,....]
    metadatas=[{"chapter": "3", "verse": "16"},{"chapter":"3", "verse":"5"}, ..]           
    embeddings = [[1,2,3], [3,4,5], [5,6,7]]
)
Create Table tablename 

按文檔內容過濾

where_document 參數允許直接根據文件內容進行過濾。

僅檢索包含特定關鍵字的文件。

#Create a collection
collection = client.create_collection(name="name")

#If a collection is already made and you need to use it again the use
collection = client.get_collection(name="name")

重點:

  • 使用 $contains、$startsWith 或 $endsWith 等運算子。
    • $contains:符合包含子字串的文件。
    • $startsWith:符合以子字串開頭的文件。
    • $endsWith:符合以子字串結尾的文件。
  • 例如:

    Insert into tablename
    Values(... , ..., ...)
    

常見用例:

我們可以像這樣組合所有三個過濾器:

  1. 在特定類別中搜尋

    collection.add(
        ids = [1]
        documents = ["some text"]
        metadatas = [{"key":"value"}]
        embeddings = [[1,2,3]]
    )
    
  2. 搜尋包含特定術語的文件:

    collection.update(
        ids = [2]
        documents = ["some text"]
        metadatas = [{"key":"value"}]
        embeddings = [[1,2,3]]            
    )
    
    # If the id does not exist update will do nothing. to add data if id does not exist use
    collection.upsert(
        ids = [2]
        documents = ["some text"]
        metadatas = [{"key":"value"}]
        embeddings = [[1,2,3]]            
    )
    
    # To delete data use delete and refrence the document or id or the feild
    collection.delete(
        documents = ["some text"]         
    )
    
    # Or you can delete from a bunch of ids using where that will apply filter on metadata
    collection.delete(
        ids=["id1", "id2", "id3",...],
        where={"chapter": "20"}
    )
    
  3. 組合元資料與文件內容過濾器:

    Select * from tablename
    
    Select * from tablename limit value
    
    Select Documents, Metadata from tablename
    

這些過濾器提高了相似性搜尋的精確度,使 ChromaDB 成為目標文件檢索的強大工具。

結論

我寫這篇文章是因為我覺得該文件在嘗試製作自己的程式時還有很多不足之處,我希望這會有所幫助!

感謝您的閱讀,如果您喜歡這篇文章,請按讚和分享。另外,如果您是軟體架構新手並且想了解更多信息,我將開始一個基於小組的隊列,我將親自與您和一個小組一起工作,教您有關軟體架構和設計原理的所有知識。如果您有興趣,可以填寫下面的表格。 https://forms.gle/SUAxrzRyvbnV8uCGA

以上是適用於 SQL 思維的 ChromaDB的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
python中兩個列表的串聯替代方案是什麼?python中兩個列表的串聯替代方案是什麼?May 09, 2025 am 12:16 AM

可以使用多種方法在Python中連接兩個列表:1.使用 操作符,簡單但在大列表中效率低;2.使用extend方法,效率高但會修改原列表;3.使用 =操作符,兼具效率和可讀性;4.使用itertools.chain函數,內存效率高但需額外導入;5.使用列表解析,優雅但可能過於復雜。選擇方法應根據代碼上下文和需求。

Python:合併兩個列表的有效方法Python:合併兩個列表的有效方法May 09, 2025 am 12:15 AM

有多種方法可以合併Python列表:1.使用 操作符,簡單但對大列表不內存高效;2.使用extend方法,內存高效但會修改原列表;3.使用itertools.chain,適用於大數據集;4.使用*操作符,一行代碼合併小到中型列表;5.使用numpy.concatenate,適用於大數據集和性能要求高的場景;6.使用append方法,適用於小列表但效率低。選擇方法時需考慮列表大小和應用場景。

編譯的與解釋的語言:優點和缺點編譯的與解釋的語言:優點和缺點May 09, 2025 am 12:06 AM

CompiledLanguagesOffersPeedAndSecurity,而interneterpretledlanguages provideeaseafuseanDoctability.1)commiledlanguageslikec arefasterandSecureButhOnderDevevelmendeclementCyclesclesclesclesclesclesclesclesclesclesclesclesclesclesclesclesclesclesandentency.2)cransportedeplatectentysenty

Python:對於循環,最完整的指南Python:對於循環,最完整的指南May 09, 2025 am 12:05 AM

Python中,for循環用於遍歷可迭代對象,while循環用於條件滿足時重複執行操作。 1)for循環示例:遍歷列表並打印元素。 2)while循環示例:猜數字遊戲,直到猜對為止。掌握循環原理和優化技巧可提高代碼效率和可靠性。

python concatenate列表到一個字符串中python concatenate列表到一個字符串中May 09, 2025 am 12:02 AM

要將列表連接成字符串,Python中使用join()方法是最佳選擇。 1)使用join()方法將列表元素連接成字符串,如''.join(my_list)。 2)對於包含數字的列表,先用map(str,numbers)轉換為字符串再連接。 3)可以使用生成器表達式進行複雜格式化,如','.join(f'({fruit})'forfruitinfruits)。 4)處理混合數據類型時,使用map(str,mixed_list)確保所有元素可轉換為字符串。 5)對於大型列表,使用''.join(large_li

Python的混合方法:編譯和解釋合併Python的混合方法:編譯和解釋合併May 08, 2025 am 12:16 AM

pythonuseshybridapprace,ComminingCompilationTobyTecoDeAndInterpretation.1)codeiscompiledtoplatform-Indepententbybytecode.2)bytecodeisisterpretedbybythepbybythepythonvirtualmachine,增強效率和通用性。

了解python的' for”和' then”循環之間的差異了解python的' for”和' then”循環之間的差異May 08, 2025 am 12:11 AM

theKeyDifferencesBetnewpython's“ for”和“ for”和“ loopsare:1)” for“ loopsareIdealForiteringSequenceSquencesSorkNowniterations,而2)”,而“ loopsareBetterforConterContinuingUntilacTientInditionIntionismetismetistismetistwithOutpredefinedInedIterations.un

Python串聯列表與重複Python串聯列表與重複May 08, 2025 am 12:09 AM

在Python中,可以通過多種方法連接列表並管理重複元素:1)使用 運算符或extend()方法可以保留所有重複元素;2)轉換為集合再轉回列表可以去除所有重複元素,但會丟失原有順序;3)使用循環或列表推導式結合集合可以去除重複元素並保持原有順序。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

VSCode Windows 64位元 下載

VSCode Windows 64位元 下載

微軟推出的免費、功能強大的一款IDE編輯器

SublimeText3 英文版

SublimeText3 英文版

推薦:為Win版本,支援程式碼提示!

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具