在 ChromaDB 中按一组查询文本进行查询 本教程将引导您通过一组查询文本作为输入,对 ChromaDB 中的集合进行查询,从而展示语义搜索功能。 创建集合 我们首先初始化 ChromaDB 客户端,并创建一个名为 . We set the distance function to 的集合。该集合适用于语义相似性搜索。 添加原始文档 我们使用 方法向集合中添加了三篇原始文档(来自《黑客帝国》的著名引言)。每篇文档都与一个唯一的 id 关联。 按一组查询文本进行查询 我们可以使用语义搜索对集合进行查询,具体代码请参阅 method.
本教程将引导您通过一组查询文本作为输入,对 ChromaDB 中的集合进行查询,从而展示语义搜索功能。
client = chromadb.Client() morpheus_collection = client.create_collection( name="morpheus", metadata={"hnsw:space": "cosine"} )
我们首先初始化 ChromaDB 客户端,并创建一个名为 morpheus. We set the distance function to "cosine" 的集合。该集合适用于语义相似性搜索。
morpheus_collection.add( documents=[ "This is your last chance. After this, there is no turning back.", "You take the blue pill, the story ends, you wake up in your bed and believe whatever you want to believe.", "You take the red pill, you stay in Wonderland, and I show you how deep the rabbit hole goes.", ], ids=["quote_1", "quote_2", "quote_3"], )
我们使用 add 方法向集合中添加了三篇原始文档(来自《黑客帝国》的著名引言)。每篇文档都与一个唯一的 id 关联。
results = morpheus_collection.query( query_texts=["Make a choice"], n_results=2, ) print(results)
我们可以使用语义搜索对集合进行查询,具体代码请参阅 query method. This will return the closest matches based on meaning, not just exact text matching. In this example, we query the collection with the text "Tell me about making a choice". We specify that we want to retrieve 2 results (n_results=2).
The results will include the ids, metadatas (if provided), and documents of the semantically closest matches. The order of the results is based on their semantic similarity to the query text, with the most relevant results appearing first.
Note: This example demonstrates semantic search. The query "Make a choice" doesn't appear verbatim in any of the documents, but ChromaDB will return the most semantically relevant results.
Please refer to the query_by_texts.py 文件,该文件包含了本教程所用的完整 Python 代码。
免责声明:
本文档采用基于机器的 AI 翻译服务进行翻译。尽管我们力求准确,但请注意,自动翻译可能存在错误或不准确之处。应以原文语言版本的文档作为权威依据。如需获取关键信息,建议使用专业的人工翻译。对于因使用本翻译而产生的任何误解或误读,我们概不负责。