️ Предупреждение: этот SDK все еще находится в альфа -состоянии. Несмотря на то, что он в основном построен и функционален, он может претерпевать изменения, поскольку мы продолжаем улучшать UX. Пожалуйста, попробуйте это и дайте нам свои отзывы, но имейте в виду, что обновления могут внести нарушающие изменения.
Документацию можно найти здесь.
Версия ржавчины: протестирована с ржавой версией 1.78.0
Прежде чем вы сможете использовать SDK Pinecone, вы должны зарегистрироваться в учетной записи и найти свой клавиш API на панели панели консоли Pinecone по адресу https://app.pinecone.io.
Запустите cargo add pinecone-sdk , чтобы добавить ящик в качестве зависимости, или добавить линию pinecone-sdk = "0.1.2" в свой файл cargo.toml в [dependencies] . Подробнее о ящике можно найти здесь.
Класс PineconeClient является главной точкой входа в Rust SDK. Параметры могут либо быть непосредственно передаваться в Options , либо прочитать через переменные среды следующим образом. Более подробно:
PINECONE_API_KEY . Если он не будет принят, как None , клиент попытается прочитать в значении переменной среды.None принят, не будет попытаться прочитать в переменной среды под названием PINECONE_CONTROLLER_HOST . Если это не переменная среды, она по умолчанию будет по умолчанию на https://api.pinecone.io .Есть несколько способов создания экземпляра клиента, подробно описано ниже:
Инициализируйте структуру PineconeClientConfig с параметрами и вызовите config с помощью struct.
use pinecone_sdk :: pinecone :: { PineconeClient , PineconeClientConfig } ;
let config = PineconeClientConfig {
api_key : Some ( "INSERT_API_KEY" . to_string ( ) ) ,
control_plane_host : Some ( "INSERT_CONTROLLER_HOST" . to_string ( ) ) ,
.. Default :: default ( )
} ;
let pinecone : PineconeClient = config . client ( ) . expect ( "Failed to create Pinecone instance" ) ; Используйте функцию default_client() , которая является эквивалентом конструирования структуры PineconeClientConfig со всеми полями, установленными для None . Ключ API и хост плоскости управления (необязательно) будут считываться из переменных среды.
let pinecone : PineconeClient = pinecone_sdk :: pinecone :: default_client ( ) . expect ( "Failed to create Pinecone instance" ) ; Следующий пример создает без серверного индекса в области AWS us-east-1 . Для получения дополнительной информации о без серверной и региональной доступности см. Индексы понимания
use pinecone_sdk :: pinecone :: PineconeClientConfig ;
use pinecone_sdk :: models :: { Metric , Cloud , WaitPolicy , IndexModel } ;
let config = PineconeClientConfig {
api_key : Some ( ' << PINECONE_API_KEY >> ' ) ,
.. Default :: default ( )
} ;
let pinecone = config . client ( ) ? ;
let index_description : IndexModel = pinecone . create_serverless_index (
"index-name" , // Name of the index
10 , // Dimension of the vectors
Metric :: Cosine , // Distance metric
Cloud :: Aws , // Cloud provider
"us-east-1" , // Region
WaitPolicy :: NoWait // Timeout
) . await ? ; Следующий пример создает индекс POD в регионе AWS us-east-1 .
use pinecone_sdk :: pinecone :: PineconeClientConfig ;
use pinecone_sdk :: models :: { Metric , Cloud , WaitPolicy , IndexModel } ;
let config = PineconeClientConfig {
api_key : Some ( ' << PINECONE_API_KEY >> ' ) ,
.. Default :: default ( )
} ;
let pinecone = config . client ( ) ? ;
let index_description : IndexModel = pinecone . create_pod_index (
"index-name" , // Index name
10 , // Dimension
Metric :: Cosine , // Distance metric
"us-east-1" , // Region
"p1.x1" , // Pod type
1 , // Number of pods
None , // Number of replicas
None , // Number of shards
None , // Metadata to index
None , // Source collection
WaitPolicy :: NoWait // Wait policy
) . await ? ;Индексы POD поддерживают несколько дополнительных полей конфигурации. Следующий пример создает индекс POD с некоторыми спецификациями для этих полей.
use pinecone_sdk :: pinecone :: PineconeClientConfig ;
use pinecone_sdk :: models :: { Metric , Cloud , WaitPolicy , IndexModel } ;
let config = PineconeClientConfig {
api_key : Some ( ' << PINECONE_API_KEY >> ' ) ,
.. Default :: default ( )
} ;
let pinecone = config . client ( ) ? ;
let index_description : IndexModel = pinecone . create_pod_index (
"index-name" , // Index name
10 , // Dimension
Metric :: Cosine , // Distance metric
"us-east-1" , // Region
"p1.x1" , // Pod type
1 , // Number of pods
Some ( 1 ) , // Number of replicas
Some ( 1 ) , // Number of shards
Some ( // Metadata fields to index
& vec ! [ "genre" ,
"title" ,
"imdb_rating" ] ) ,
Some ( "collection" ) , // Source collection
WaitPolicy :: NoWait // Wait policy
) . await ? ; В следующем примере перечислены все индексы в вашем проекте.
use pinecone_sdk :: pinecone :: PineconeClientConfig ;
use pinecone_sdk :: models :: IndexList ;
let config = PineconeClientConfig {
api_key : Some ( ' << PINECONE_API_KEY >> ' ) ,
.. Default :: default ( )
} ;
let pinecone = config . client ( ) ? ;
let index_list : IndexList = pinecone . list_indexes ( ) . await ? ; В следующем примере возвращает информацию об index-name .
use pinecone_sdk :: pinecone :: PineconeClientConfig ;
use pinecone_sdk :: models :: IndexModel ;
let config = PineconeClientConfig {
api_key : Some ( ' << PINECONE_API_KEY >> ' ) ,
.. Default :: default ( )
} ;
let pinecone = config . client ( ) ? ;
let index_description : IndexModel = pinecone . describe_index ( "index-name" ) . await ? ; Настройка индекса принимает три дополнительных параметра - перечисление DelletionProtection, количество реплик и тип POD. Защита от удаления может быть обновлена для любого типа индекса, в то время как количество реплик и типа POD может быть обновлено только для индексов POD.
Следующий пример отключает защиту от удаления для index-name .
use pinecone_sdk :: pinecone :: PineconeClientConfig ;
use pinecone_sdk :: models :: IndexModel ;
let config = PineconeClientConfig {
api_key : Some ( ' << PINECONE_API_KEY >> ' ) ,
.. Default :: default ( )
} ;
let pinecone = config . client ( ) ? ;
let index_description : IndexModel = pinecone . configure_index ( "index-name" , Some ( DeletionProtection :: Disabled ) , None , None ) . await ? ; В следующем примере изменяется index-name индекса, чтобы иметь 6 реплик и типа POD s1 . Тип защиты от удаления не будет изменен в этом случае.
use pinecone_sdk :: pinecone :: PineconeClientConfig ;
use pinecone_sdk :: models :: IndexModel ;
let config = PineconeClientConfig {
api_key : Some ( ' << PINECONE_API_KEY >> ' ) ,
.. Default :: default ( )
} ;
let pinecone = config . client ( ) ? ;
let index_description : IndexModel = pinecone . configure_index ( "index-name" , None , Some ( 6 ) , Some ( "s1" ) ) . await ? ; Следующий пример удаляет index-name .
use pinecone_sdk :: pinecone :: PineconeClientConfig ;
let config = PineconeClientConfig {
api_key : Some ( ' << PINECONE_API_KEY >> ' ) ,
.. Default :: default ( )
} ;
let pinecone = config . client ( ) ? ;
pinecone . delete_index ( "index-name" ) . await ? ; В следующем примере возвращает статистику об индексе с хост index-host . Без фильтра
use std :: collections :: BTreeMap ;
use pinecone_sdk :: pinecone :: PineconeClientConfig ;
use pinecone_sdk :: models :: DescribeIndexStatsResponse ;
let config = PineconeClientConfig {
api_key : Some ( ' << PINECONE_API_KEY >> ' ) ,
.. Default :: default ( )
} ;
let pinecone = config . client ( ) ? ;
let mut index = pinecone . index ( "index-host" ) . await ? ;
let response : DescribeIndexStatsResponse = index . describe_index_stats ( None ) . await ? ;С фильтром
use std :: collections :: BTreeMap ;
use pinecone_sdk :: pinecone :: PineconeClientConfig ;
use pinecone_sdk :: models :: { Value , Kind , Metadata , DescribeIndexStatsResponse } ;
let config = PineconeClientConfig {
api_key : Some ( ' << PINECONE_API_KEY >> ' ) ,
.. Default :: default ( )
} ;
let pinecone = config . client ( ) ? ;
let mut index = pinecone . index ( "index-host" ) . await ? ;
let mut fields = BTreeMap :: new ( ) ;
let kind = Some ( Kind :: StringValue ( "value" . to_string ( ) ) ) ;
fields . insert ( "field" . to_string ( ) , Value { kind } ) ;
let response : DescribeIndexStatsResponse = index . describe_index_stats ( Some ( Metadata { fields } ) ) . await ? ; Следующий пример поднимает два вектора в индекс с index-host хоста.
use pinecone_sdk :: pinecone :: PineconeClientConfig ;
use pinecone_sdk :: models :: { Vector , UpsertResponse } ;
let config = PineconeClientConfig {
api_key : Some ( ' << PINECONE_API_KEY >> ' ) ,
.. Default :: default ( )
} ;
let pinecone = config . client ( ) ? ;
let mut index = pinecone . index ( "index-host" ) . await ? ;
let vectors = [ Vector {
id : "id1" . to_string ( ) ,
values : vec ! [ 1.0 , 2.0 , 3.0 , 4.0 ] ,
sparse_values : None ,
metadata : None ,
} , Vector {
id : "id2" . to_string ( ) ,
values : vec ! [ 2.0 , 3.0 , 4.0 , 5.0 ] ,
sparse_values : None ,
metadata : None ,
} ] ;
let response : UpsertResponse = index . upsert ( & vectors , & "namespace" . into ( ) ) . await ? ; Есть два поддерживаемых способа запроса индекса.
В следующем примере запрашивается индекс с index-host хоста для вектора с ID vector-id и возвращает 10 лучших совпадений.
use pinecone_sdk :: pinecone :: PineconeClientConfig ;
use pinecone_sdk :: models :: { Namespace , QueryResponse } ;
let config = PineconeClientConfig {
api_key : Some ( ' << PINECONE_API_KEY >> ' ) ,
.. Default :: default ( )
} ;
let pinecone = config . client ( ) ? ;
// Connect to index at host "index-host"
let mut index = pinecone . index ( "index-host" ) . await ? ;
// Query the vector with id "vector-id" in the namespace "namespace"
let response : QueryResponse = index . query_by_id (
"vector-id" . to_string ( ) ,
10 ,
& Namespace :: default ( ) ,
None ,
None ,
None
) . await ? ; В следующем примере задается индекс с index-host хоста для вектора со значениями [1.0, 2.0, 3.0, 4.0] и возвращает 10 лучших совпадений.
use pinecone_sdk :: pinecone :: PineconeClientConfig ;
use pinecone_sdk :: models :: { Namespace , QueryResponse } ;
let config = PineconeClientConfig {
api_key : Some ( ' << PINECONE_API_KEY >> ' ) ,
.. Default :: default ( )
} ;
let pinecone = config . client ( ) ? ;
let mut index = pinecone . index ( "index-host" ) . await ? ;
let vector = vec ! [ 1.0 , 2.0 , 3.0 , 4.0 ] ;
let response : QueryResponse = index . query_by_value (
vector ,
None ,
10 ,
& Namespace :: default ( ) ,
None ,
None ,
None
) . await ? ; Есть три поддерживаемых способа удаления векторов.
Следующий пример удаляет вектор с идентификатором vector-id в namespace имен имен.
use pinecone_sdk :: pinecone :: PineconeClientConfig ;
let config = PineconeClientConfig {
api_key : Some ( ' << PINECONE_API_KEY >> ' ) ,
.. Default :: default ( )
} ;
let pinecone = config . client ( ) ? ;
let mut index = pinecone . index ( "index-host" ) . await ? ;
let ids = [ "vector-id" ]
index . delete_by_id ( & ids , & "namespace" . into ( ) ) . await ? ; Следующий пример удаляет векторы, которые удовлетворяют фильтру в namespace имен имен.
use std :: collections :: BTreeMap ;
use pinecone_sdk :: pinecone :: PineconeClientConfig ;
use pinecone_sdk :: models :: { Metadata , Value , Kind , Namespace } ;
let config = PineconeClientConfig {
api_key : Some ( ' << PINECONE_API_KEY >> ' ) ,
.. Default :: default ( )
} ;
let pinecone = config . client ( ) ? ;
let mut fields = BTreeMap :: new ( ) ;
let kind = Some ( Kind :: StringValue ( "value" . to_string ( ) ) ) ;
fields . insert ( "field" . to_string ( ) , Value { kind } ) ;
index . delete_by_filter ( Metadata { fields } , & "namespace" . into ( ) ) . await ? ; Следующий пример удаляет все векторы в namespace имен имен.
use pinecone_sdk :: pinecone :: PineconeClientConfig ;
let config = PineconeClientConfig {
api_key : Some ( ' << PINECONE_API_KEY >> ' ) ,
.. Default :: default ( )
} ;
let pinecone = config . client ( ) ? ;
let mut index = pinecone . index ( "index-host" ) . await ? ;
index . delete_all ( & "namespace" . into ( ) ) . await ? ; В следующем примере избирает векторы с идентификаторами 1 и 2 из пространства имен по умолчанию.
use pinecone_sdk :: pinecone :: PineconeClientConfig ;
use pinecone_sdk :: models :: FetchResponse ;
let config = PineconeClientConfig {
api_key : Some ( ' << PINECONE_API_KEY >> ' ) ,
.. Default :: default ( )
} ;
let pinecone = config . client ( ) ? ;
let mut index = pinecone . index ( "index-host" ) . await ? ;
let vectors = & [ "1" , "2" ] ;
let response : FetchResponse = index . fetch ( vectors , & Default :: default ( ) ) . await ? ; В следующем примере обновляется вектор с идентификационным vector-id в namespace имен имен, чтобы иметь значения [1.0, 2.0, 3.0, 4.0] .
use pinecone_sdk :: pinecone :: PineconeClientConfig ;
use pinecone_sdk :: models :: UpdateResponse ;
let config = PineconeClientConfig {
api_key : Some ( ' << PINECONE_API_KEY >> ' ) ,
.. Default :: default ( )
} ;
let pinecone = config . client ( ) ? ;
let mut index = pinecone . index ( "index-host" ) . await ? ;
let response : UpdateResponse = index . update ( "vector-id" , vec ! [ 1.0 , 2.0 , 3.0 , 4.0 ] , None , None , & "namespace" . into ( ) ) . await ? ; В следующем примере перечислены векторы в namespace имен имен.
use pinecone_sdk :: pinecone :: PineconeClientConfig ;
use pinecone_sdk :: models :: { Namespace , ListResponse } ;
let config = PineconeClientConfig {
api_key : Some ( ' << PINECONE_API_KEY >> ' ) ,
.. Default :: default ( )
} ;
let pinecone = config . client ( ) ? ;
let mut index = pinecone . index ( "index-host" ) . await ? ;
let response : ListResponse = index . list ( & "namespace" . into ( ) , None , None , None ) . await ? ; Следующий пример создает collection-name коллекции в index-name .
use pinecone_sdk :: pinecone :: PineconeClientConfig ;
use pinecone_sdk :: models :: CollectionModel ;
let config = PineconeClientConfig {
api_key : Some ( ' << PINECONE_API_KEY >> ' ) ,
.. Default :: default ( )
} ;
let pinecone = config . client ( ) ? ;
let collection : CollectionModel = pinecone . create_collection ( "collection-name" , "index-name" ) . await ? ; В следующем примере перечислены все коллекции в проекте.
use pinecone_sdk :: pinecone :: PineconeClientConfig ;
use pinecone_sdk :: models :: CollectionList ;
let config = PineconeClientConfig {
api_key : Some ( ' << PINECONE_API_KEY >> ' ) ,
.. Default :: default ( )
} ;
let pinecone = config . client ( ) ? ;
let collection_list : CollectionList = pinecone . list_collections ( ) . await ? ; В следующем примере описывается collection-name коллекции.
use pinecone_sdk :: pinecone :: PineconeClientConfig ;
use pinecone_sdk :: models :: CollectionModel ;
let config = PineconeClientConfig {
api_key : Some ( ' << PINECONE_API_KEY >> ' ) ,
.. Default :: default ( )
} ;
let pinecone = config . client ( ) ? ;
let collection : CollectionModel = pinecone . describe_collection ( "collection-name" ) . await ? ; Следующий пример удаляет collection-name коллекции.
use pinecone_sdk :: pinecone :: PineconeClientConfig ;
let config = PineconeClientConfig {
api_key : Some ( ' << PINECONE_API_KEY >> ' ) ,
.. Default :: default ( )
} ;
let pinecone = config . client ( ) ? ;
pinecone . delete_collection ( "collection-name" ) . await ? ;Если вы хотите внести вклад или настройку локально для разработки клиента Pinecone Rust, см. Наше руководство по применению