Pinecone使用demo示例(含:Python/NodeJS/PHP语言)

文 / @WordPress主题

Pinecone 是一款云原生的向量数据库,使用简单且功能强大。它可以帮助我们轻松构建针对大规模向量数据的搜索和推荐系统。今天我们就来看下如何使用 Pinecone 的 Python 和 Node.js SDK 进行向量操作。

c2df3ce07a2690df9e2424ed01a0525b

Pinecone 的优势主要有:

  • 简单的向量存储和索引接口,不需要自己搭建复杂系统
  • 提供了多语言的 SDK,包括 Python、Node.js、Go 等
  • 向量索引和搜索效率高,可以扩展到数十亿量级的向量
  • 还支持文本、图像、时间序列等数据的向量化存储
  • 完全托管的云服务,不需要自己部署和维护

下面我先给出 Python 和 Node.js 两个版本的 Pinecone 使用示例代码,示例实现了向量的插入、搜索这样的基本操作,可以作为使用 Pinecone 的入门Demo。后面我还会具体解释下代码中涉及的 Pinecone 的一些基础概念和接口。

使用 Pinecone 在 Python 中进行向量搜索的简单示例

这里是一个使用 Pinecone 在 Python 中进行向量搜索的简单示例:

python

Copy code

import pinecone

# 初始化 Pinecone client
index = pinecone.Index('my_index')

# 插入向量数据
vectors = [
pinecone.Vector(vector_id='1', values=[0.1, 0.2, 0.3]),
pinecone.Vector(vector_id='2', values=[0.2, 0.3, 0.4])]
index.upsert(vectors)

# 构建一个查询向量
query_vector = pinecone.Vector(values=[0.15, 0.25, 0.35])

# 查询相似的 5 个向量
response = index.query(query_vector, top_k=5)

print(response.vectors[0].id)
# '1'

主要步骤是:

  1. 初始化 Pinecone Index 对象,指定索引名。
  2. 插入向量数据,每个向量需要指定一个 id 和一个浮点向量。
  3. 构建查询向量。
  4. 使用 index.query 方法进行相似向量查询,指定返回最相似的 5 个向量。
  5. 从返回的结果中可以获取匹配的向量及其 id。

Pinecone 提供了非常易用的向量搜索接口,可以快速上手使用。相比自己搭建向量搜索系统,Pinecone 可以省去很多工作。

使用 Pinecone 在 Node.js中进行向量搜索的简单示例

这里是一个使用 Node.js 和 Pinecone 进行向量搜索的示例:

js

Copy code

const pinecone = require('@pinecone-database/pinecone');

// 初始化 Pinecone 客户端
const index = pinecone.Index('my_index');

// 插入向量数据
const vectors = [
pinecone.Vector.fromJSON({
id: '1',
values: [0.1, 0.2, 0.3]
}),
pinecone.Vector.fromJSON({
id: '2',
values: [0.2, 0.3, 0.4]
})
];

await index.upsert(vectors);

// 构建查询向量
const queryVector = pinecone.Vector.fromJSON({
values: [0.15, 0.25, 0.35]
});

// 相似向量查询
const response = await index.query(queryVector, {topK: 5});

console.log(response.matches[0].id);
// '1'

主要步骤:

  1. 导入 pinecone 模块
  2. 初始化 Index 对象
  3. 插入向量数据,需要先构造 Vector 对象
  4. 构造查询向量
  5. 调用 index.query 方法进行查询
  6. 从返回结果中获取匹配的向量

Pinecone 的 Node.js SDK 使用起来也很简单。与 Python SDK类似,可以轻松实现向量索引和搜索。

使用 PHP 和 Pinecone 进行向量搜索

这里是一个使用 PHP 和 Pinecone 进行向量搜索的简单示例:

php

Copy code

<?php

use Pinecone\PineconeClient;
use Pinecone\Vector;

$apiKey = 'your_api_key';

$client = new PineconeClient($apiKey);

$index = $client->initIndex('my_index');

// 插入向量
$vectors = [
new Vector('1', [0.1, 0.2, 0.3]),
new Vector('2', [0.2, 0.3, 0.4])
];

$index->upsert($vectors);

// 构建查询向量
$queryVector = new Vector([0.15, 0.25, 0.35]);

// 向量搜索
$response = $index->query($queryVector, ['topK' => 5]);

echo $response['matches'][0]['id'];
// 输出 '1'

主要步骤:

  1. 使用 PineconeClient 初始化连接,需要 API Key
  2. 获取一个索引对象 Index
  3. 构造 Vector 对象插入数据
  4. 创建查询向量
  5. 调用 index->query 进行向量相似搜索
  6. 从返回结果中解析出匹配的向量

Pinecone 的 PHP SDK 使用起来也很简单直观。与其他语言类似,可以通过简单的 API 调用实现向量搜索功能。

添加UTHEME为好友
扫码添加UTHEME微信为好友
· 分享WordPress相关技术文章,主题上新与优惠动态早知道。
· 微信端最大WordPress社群,限时免费入群。