定義用於分塊的函式
為了能以可重現的方式批次 upsert,你需要定義一個函式,把向量清單切成多個區塊。
內建的 itertools 模組已經幫你匯入。
本練習屬於課程
使用 Pinecone 構建 AI 應用
練習說明
- 將輸入的
iterable轉成疊代器。 - 使用
itertools模組,將it依batch_size的大小切成多個區塊。 - 產出(yield)目前的區塊。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
def chunks(iterable, batch_size=100):
"""A helper function to break an iterable into chunks of size batch_size."""
# Convert the iterable into an iterator
it = ____
# Slice the iterator into chunks of size batch_size
chunk = tuple(itertools.____(it, ____))
while chunk:
# Yield the chunk
____
chunk = tuple(itertools.islice(it, batch_size))