Python, векторы фильтров из векторного хранилища Pinecone на основе поля, сохраненного в метаданных этих векторовPython

Программы на Python
Ответить Пред. темаСлед. тема
Anonymous
 Python, векторы фильтров из векторного хранилища Pinecone на основе поля, сохраненного в метаданных этих векторов

Сообщение Anonymous »

У меня есть векторы, хранящиеся в хранилище векторов Pinecone, каждый вектор представляет собой содержимое PDF-файла:

Метаданные::
hash_code: "d53d7ec8b0e66e9a83a97acda09edd3fe9867cadb42833f9bf5525cc3b89fe2d"
id: "cc54ffbe-9cba-4de9-9f30-a114e4c3c3fb"

Я сохранил новое поле в метаданных, которое представляет собой хеш-код PDF-файла. содержимое, чтобы избежать повторного добавления одного и того же файла в векторное хранилище.
Для этого я получаю новые хэш-коды новых документов, которые мне нужны. чтобы добавить, я хочу просканировать существующие, чтобы найти, существует ли какой-либо из них, а затем отфильтровать его.
Я использую Python и пробовал такой код, но не получилось мне пока не удалось достичь цели:
Первый способ:
def filter_existing_docs(index_name, docs):
# Initialize the Pinecone index
index = pinecone_client.Index(index_name)

# Extract hash_codes from the docs list using the appropriate method for your Document objects
hash_codes = [doc.metadata['hash_code'] for doc in docs] # Accessing 'metadata' if it's an attribute
print("Hash Codes:", hash_codes)

# Fetch by list of hash_codes (ensure hash_codes are valid ids)
fetch_response = index.fetch(ids=hash_codes)
print("Fetch Response:", fetch_response)

# Get the existing hash_codes that are already in the Pinecone index
existing_hash_codes = set(fetch_response.get('vectors', {}).keys()) # Extract existing IDs from the response
print("1 -----------> Existing Hash Codes:", len(existing_hash_codes))

# Filter out the docs that have already been added to Pinecone
filtered_docs = [doc for doc in docs if doc.metadata['hash_code'] not in existing_hash_codes]
print("2 -----------> Filtered Docs:", len(filtered_docs))

return filtered_docs

Затем попробовал другой подход:
def filter_existing_docs(index_name, docs):
# Initialize the Pinecone index
index = pinecone_client.Index(index_name)

# Extract hash_codes from the docs list using the appropriate method for your Document objects
hash_codes = [doc.metadata['hash_code'] for doc in docs] # Accessing 'metadata' if it's an attribute
print("Hash Codes:", hash_codes)

# We need to query Pinecone using `top_k` and search through the index
query_response = index.query(
top_k=100, # Set a suitable `top_k` to return a reasonable number of documents
include_metadata=True,
#namespace=namespace
)

# Debug: Print the query response to see its structure
print("Query Response:", query_response)

# Extract the hash_codes of the existing documents in Pinecone
existing_hash_codes = {item['metadata']['hash_code'] for item in query_response['matches']}
print("1 -----------> Existing Hash Codes:", len(existing_hash_codes))

# Filter out the docs that have already been added to Pinecone based on hash_code
filtered_docs = [doc for doc in docs if str(doc.metadata['hash_code']) not in existing_hash_codes]
print("2 -----------> Filtered Docs:", len(filtered_docs))

return filtered_docs


Подробнее здесь: https://stackoverflow.com/questions/793 ... ved-in-the
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «Python»