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