读写数据
更新时间:2024-03-12
概述
本章节介绍如何连接向量数据库,根据业务需求简单读写向量数据的操作。运行本章节所提供的示例代码,您将初步了解向量数据库的数据读写的能力。
前提条件
插入数据
插入记录,记录包含建表所包含的标量和向量信息
import pymochow
from pymochow.configuration import Configuration
from pymochow.auth.bce_credentials import BceCredentials
account = 'root'
api_key = 'your_api_key'
endpoint = 'you_endpoint' #example http://127.0.0.1:5287
config = Configuration(credentials=BceCredentials(account, api_key),
endpoint=endpoint)
client = pymochow.MochowClient(config)
db = client.database("db_test")
indexes = []
indexes.append(VectorIndex(index_name="vector_idx", index_type=IndexType.HNSW,
field="vector", metric_type=MetricType.L2,
params=HNSWParams(m=32, efconstruction=200)))
indexes.append(SecondaryIndex(index_name="book_name_idx", field="bookName"))
table = db.table("book_vector")
rows = [
Row(id='0001',
vector=[0.2123, 0.21, 0.213],
bookName='西游记'),
]
table.insert(rows)
client.close()
标量数据查询
根据刚刚插入的 id=0001 的记录返回数据
import pymochow
from pymochow.configuration import Configuration
from pymochow.auth.bce_credentials import BceCredentials
account = 'root'
api_key = 'your_api_key'
endpoint = 'you_endpoint' #example http://127.0.0.1:5287
config = Configuration(credentials=BceCredentials(account, api_key),
endpoint=endpoint)
client = pymochow.MochowClient(config)
db = client.database("db_test")
table = db.table("book_vector")
primary_key = {'id': '0001'}
projections = ["id", "bookName"]
res = table.query(primary_key=primary_key, projections=projections)
client.close()
恭喜你完成第一条数据的写入和读取,更详细的数据读写可参考:Row 操作