Есть ли способ получить все векторы пространства имен в сосновой шишке?
Как я могу получить все векторы пространства имен в сосновой шишке, поскольку метод выборки ожидает идентификаторы векторов. Есть ли способ получить все идентификаторы векторов.
2 ответа
ОК, я много боролся с этим, но, наконец, я нашел решение, я просто пытался создать свой первый мир приветствия с помощью сосновой шишки, добавил некоторые данные и, чтобы убедиться, что они действительно добавлены, я хотел вернуть все векторы из пространства имен
Просто сделайте запрос к сосновой шишке и установите максимальное значение, и вы получите все векторы, независимо от вашего запроса.
например, у меня есть только 54 вектора в индексе сосновой шишки, поэтому, если я установлюtopK
к100
он возвращает мне все документы, независимо от того, что я даю в запросе или оставляю пустой текст в запросе,
вот мой код для справки, извините, он находится в модуле ES (javascript), но я уверен, что в Python он будет работать так же:
const queryPineconeIndex = async (queryText, numberOfResults) => {
const response = await openai.createEmbedding({
model: "text-embedding-ada-002",
input: queryText,
});
const vector = response?.data?.data[0]?.embedding
console.log("vector: ", vector);
// [ 0.0023063174, -0.009358601, 0.01578391, ... , 0.01678391, ]
const index = pinecone.Index(process.env.PINECONE_INDEX_NAME);
const queryResponse = await index.query({
queryRequest: {
vector: vector,
// id: "vec1",
topK: numberOfResults,
includeValues: true,
includeMetadata: true,
namespace: process.env.PINECONE_NAME_SPACE
}
});
queryResponse.matches.map(eachMatch => {
console.log(`score ${eachMatch.score.toFixed(1)} => ${JSON.stringify(eachMatch.metadata)}\n\n`);
})
console.log(`${queryResponse.matches.length} records found `);
}
queryPineconeIndex("any text or empty string", 100)
если вы не знаете, сколько векторов у вас в индексе, вы также можете получить его следующим образом:
const getIndexStats = async () => {
const indexesList = await pinecone.listIndexes();
console.log("indexesList: ", indexesList);
const index = pinecone.Index(process.env.PINECONE_INDEX_NAME);
const indexStats = await index.describeIndexStats({
describeIndexStatsRequest: {
filter: {},
},
});
console.log("indexStats: ", indexStats);
}
// getIndexStats()
полный код в моем репозитории GitHub: https://github.com/mInzamamMalik/vector-database-hello-world
Это все еще довольно смешно, что нам приходится это делать, но вот обходной путь, позволяющий получить все идентификаторы, чтобы вы могли загрузить все векторы:
def get_ids_from_query(index,input_vector):
print("searching pinecone...")
results = index.query(vector=input_vector, top_k=10000,include_values=False)
ids = set()
print(type(results))
for result in results['matches']:
ids.add(result['id'])
return ids
def get_all_ids_from_index(index, num_dimensions, namespace=""):
num_vectors = index.describe_index_stats()["namespaces"][namespace]['vector_count']
all_ids = set()
while len(all_ids) < num_vectors:
print("Length of ids list is shorter than the number of total vectors...")
input_vector = np.random.rand(num_dimensions).tolist()
print("creating random vector...")
ids = get_ids_from_query(index,input_vector)
print("getting ids from a vector query...")
all_ids.update(ids)
print("updating ids set...")
print(f"Collected {len(all_ids)} ids out of {num_vectors}.")
return all_ids
all_ids = get_all_ids_from_index(index, num_dimensions=1536, namespace="")
print(all_ids)