为了后续小章节顺利进行,我们先准备一份测试数据,工欲利其事必先利其器。
测试数据集如下面代码:
import chromadb
from chromadb import GetResult
client = chromadb.EphemeralClient()
col = client.create_collection("notes", embedding_function=None)
# 准备测试数据
col.add(
ids=["r1", "r2", "r3", "r4"],
embeddings=[[1, 0, 0], [0, 1, 0], [0, 0, 1], [1, 1, 0]],
documents=["退款流程 refund", "发票 invoice", "物流 logistics", "退货政策"],
metadatas=[
{"cat": "售后", "year": 2020, "score": 0.9, "is_public":True, "tags": ["a", "b"]},
{"cat": "财务", "year": 2022, "score": 0.5, "is_public":False, "tags": ["c"]},
{"cat": "物流", "year": 2024, "score": 0.7, "is_public":False, "tags": ["a", "d"]},
{"cat": "售后", "year": 2024, "score": 0.3, "is_public":False, "tags": ["b", "d"]},
],
)
def get(res:GetResult, key:str):
if res is None or key is None:
return []
val = res[key]
return val if val is not None else []
def show(res:GetResult):
"""打印输出结果"""
for ids, document, metadata in zip(get(res, "ids"),
get(res, "documents"), get(res, "metadatas")):
print(f"id={ids}, document={document}, metadata={metadata}")
# 后续代码直接在这里进行编写即可
# 注意,后续示例仅给出查询部分代码,数据准备和打印查询结果参考这里的代码
show(col.get())运行示例代码,打印结果如下:
id=r1, document=退款流程 refund, metadata={'tags': ['a', 'b'], 'year': 2020, 'is_public': True, 'score': 0.9, 'cat': '售后'}
id=r2, document=发票 invoice, metadata={'year': 2022, 'score': 0.5, 'is_public': False, 'tags': ['c'], 'cat': '财务'}
id=r3, document=物流 logistics, metadata={'tags': ['a', 'd'], 'is_public': False, 'year': 2024, 'score': 0.7, 'cat': '物流'}
id=r4, document=退货政策, metadata={'score': 0.3, 'year': 2024, 'cat': '售后', 'is_public': False, 'tags': ['b', 'd']}