概述
该文档是对数据面 API 请求过程的概述,在使用 API 接口前,需先做好以下准备工作。
同时介绍响应体的公共参数,供用户在调用时参考。
调用流程
1. 账号注册与服务开通
通过 注册账号及开通服务 页面操作,完成注册账号及开通服务。
2. 构造鉴权
向量库支持使用 API Key 或 AK/SK 两种方式进行鉴权。
2.1 API Key 鉴权 (推荐)
我们推荐您使用创建 API Key 的方式,调用火山引擎向量数据库 VikingDB。
API Key 的获取
在向量库控制台进入 API Key 页面,点击 创建 API Key 即可生成新的 Key。


创建时需配置以下内容:
- API Key 名称:用于区分不同用途的 Key。
- 可访问的数据集范围:可选择当前项目下的一个或多个数据集授予访问权限。

API Key 只会在创建时显示一次,请务必妥善保存。若丢失需重新创建。

API Key 的权限管理 #
您可以随时在控制台调整 Key 的访问范围:
- 为现有 Key 新增更多数据库访问权限
- 移除指定数据库的访问权限
- 删除 Key
API Key 的鉴权代码 #
"""
pip3 install volcengine
"""
import os
from volcengine.base.Request import Request
import requests, json
class ClientForDataApi:
def __init__(self, api_key=None, host=None):
"""
初始化ClientForDataApi类
:param api_key: VikingDB的API Key
:param host: VikingDB的API Host
"""
if not api_key or not host:
raise ValueError("api_key and host are required")
self.api_key = api_key
self.host = host
def prepare_request(self, method, path, params=None, data=None):
r = Request()
r.set_shema("https")
r.set_method(method)
r.set_connection_timeout(10)
r.set_socket_timeout(10)
mheaders = {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Host': self.host,
'Authorization': f'Bearer {self.api_key}',
}
r.set_headers(mheaders)
if params:
r.set_query(params)
r.set_host(self.host)
r.set_path(path)
if data is not None:
r.set_body(json.dumps(data))
return r
def do_req(self, req_method, req_path, req_params, req_body):
req = self.prepare_request(method=req_method, path=req_path, params=req_params, data=req_body)
return requests.request(method=req.method, url="https://{}{}".format(self.host, req.path),
headers=req.headers, data=req.body, timeout=10000)
if __name__ == '__main__':
client = ClientForDataApi(
api_key=os.environ.get("API_KEY", "*"), # 替换为您的 api_key,或通过环境变量 API_KEY 传入
host="api-vikingdb.vikingdb.cn-beijing.volces.com", # 替换为您所在的域名
)
req_method = "POST"
req_params = None
req_path = "/api/vikingdb/data/fetch_in_collection" # 替换为当前操作url
req_body = {
"collection_name": "my_collection", # 替换为当前参数
'ids': [1, 2, -1]
}
result = client.do_req(req_method=req_method, req_path=req_path, req_params=req_params, req_body=req_body)
print("req http status code: ", result.status_code)
print("req result:
", result.text)
package org.example;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.net.URI;
public class DemoSignAndCallEmbeddingApiV2 {
private static String apiKey = System.getenv("API_KEY");
private static String host = "api-vikingdb.vikingdb.cn-beijing.volces.com";
public static void main(String[] args) throws Exception {
doEmbedding();
}
public static String doEmbedding() throws Exception {
String jsonString = "{" +
""dense_model": {" +
""name": "doubao-embedding-vision"," +
""version": "251215"," +
""dim": 1024" +
"}," +
""sparse_model": {" +
""name": "bge-m3"," +
""version": "default"" +
"}," +
""data": [" +
"{" +
""text": "天很蓝。"" +
"}," +
"{" +
""text": "海很深。"" +
"}" +
"]" +
"}";
System.out.println(jsonString);
String path = "/api/vikingdb/embedding";
//可自行处理做更加详细的错误处理
try {
HttpPost httpPost = prepareRequest(host, path, "POST", null, jsonString, apiKey);
HttpClient httpClient = HttpClients.createDefault();
HttpResponse response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
String responseBody = EntityUtils.toString(response.getEntity());
System.out.println("Status Code: " + statusCode);
System.out.println("Response Body: " + responseBody);
return responseBody;
} catch (Exception e) {
e.printStackTrace();
throw e;
}
}
public static HttpPost prepareRequest(String host, String path, String method, java.util.List<NameValuePair> params, String body, String apiKey) throws Exception {
URI uri = new URIBuilder().setScheme("https").setHost(host).setPath(path).build();
if (params != null) {
uri = new URIBuilder(uri).addParameters(params).build();
}
HttpPost httpPost = new HttpPost(uri);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-Type", "application/json");
httpPost.setHeader("Host", host);
httpPost.setHeader("Authorization", "Bearer " + apiKey);
httpPost.setEntity(new StringEntity(body, "utf-8"));
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(120000).setConnectTimeout(12000).build();
httpPost.setConfig(requestConfig);
return httpPost;
}
}
package main
import (
"bytes"
"fmt"
"io"
"net/http"
"net/url"
"os"
"strings"
)
func doRequest(host, method, path, apiKey string, query url.Values, body []byte) *http.Request {
u := url.URL{
Scheme: "https",
Host: host,
Path: path,
}
if query != nil {
u.RawQuery = query.Encode()
}
req, _ := http.NewRequest(strings.ToUpper(method), u.String(), bytes.NewReader(body))
req.Header.Add("Accept", "application/json")
req.Header.Add("Content-Type", "application/json")
req.Header.Add("Host", host)
req.Header.Add("Authorization", "Bearer "+apiKey)
return req
}
// v2数据面API调用示例。以写入数据(UpsertData)为例。
func main() {
var apiKey = os.Getenv("API_KEY")
if apiKey == "" {
apiKey = "**" // 您的 api_key,建议用环境变量 API_KEY
}
var host = "api-vikingdb.vikingdb.cn-beijing.volces.com" // 数据面api的域名
// UpsertData接口的path
path := "/api/vikingdb/data/upsert"
// 示例写入数据。实际的数据集名称、字段名称以您的数据集为准进行修改
body := []byte(`{
"collection_name": "test_coll_with_vectorize",
"data": [
{
"f_good_id": "000135",
"f_city": "北京",
"f_text": "这是一件历史悠久的文物,具有1300年的历史",
"f_image": "tos://my_bucket/good_000135.jpg"
}
]
}`)
req := doRequest(host, "POST", path, apiKey, nil, body)
response, err := http.DefaultClient.Do(req)
if err != nil {
panic(err)
}
defer response.Body.Close()
bodyBytes, err := io.ReadAll(response.Body)
if err != nil {
panic(err)
}
// 处理响应信息,可根据您的业务逻辑需要,进行调整
httpCode := response.StatusCode
fmt.Println(httpCode)
bodyString := string(bodyBytes)
fmt.Println(bodyString)
}
2.2 AK/SK 密钥获取
在调用火山引擎向量数据库 VikingDB 的各个能力之前,确保您已生成访问密钥 Access Key。
Access Key 包括 Access Key ID(简称为 AK) 和 Access Key Secret(简称为 SK)。其中,AK用于标识用户,SK用于验证用户的密钥,请您妥善保管。
AK/SK 密钥获取方式如下,更多详情请参考 Access Key(密钥)管理。
- 单击右上角账号名下拉框中的【密钥管理】进入对应页面。
- 单击【新建密钥】按钮,可获取 AK/SK,可以此为凭证调用上述已接入应用的接口。

安全起见,建议新建子账户,并使用子账户的 AK/SK。
签名生成
签名是什么?
签名是 API 请求中的一串经过计算得到的编码字符串,用于身份认证和防止数据被篡改。
签名获取后就能一直用吗?
签名不像 AK、SK,每个请求的签名都是独立且临时的,一个签名只能用于一次特定的请求,不能长期固定使用。
在下面调用示例中,prepare_request 即为鉴权函数。
调用示例(以 Python 为例)
以下为在数据集中点查的接口调用示例。
说明:运行该示例请填入 AK、SK、host、path 和 body,其中 path 和 body 见接口文档。
"""
pip3 install volcengine
"""
import os
from volcengine.auth.SignerV4 import SignerV4
from volcengine.Credentials import Credentials
from volcengine.base.Request import Request
import requests, json
class ClientForDataApi:
def __init__(self, ak, sk, host):
self.ak = ak
self.sk = sk
self.host = host
def prepare_request(self, method, path, params=None, data=None):
r = Request()
r.set_shema("https")
r.set_method(method)
r.set_connection_timeout(10)
r.set_socket_timeout(10)
mheaders = {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Host': self.host,
}
r.set_headers(mheaders)
if params:
r.set_query(params)
r.set_host(self.host)
r.set_path(path)
if data is not None:
r.set_body(json.dumps(data))
credentials = Credentials(self.ak, self.sk, 'vikingdb', 'cn-beijing')
SignerV4.sign(r, credentials)
return r
def do_req(self, req_method, req_path, req_params, req_body):
req = self.prepare_request(method=req_method, path=req_path, params=req_params, data=req_body)
return requests.request(method=req.method, url="https://{}{}".format(self.host, req.path),
headers=req.headers, data=req.body, timeout=10000)
if __name__ == '__main__':
client = ClientForDataApi(
ak = "*",#替换为您的ak
sk = "*",#替换为您的sk
host = "api-vikingdb.vikingdb.cn-beijing.volces.com",#替换为您所在的域名
)
req_method = "POST"
req_params = None
req_path = "/api/vikingdb/data/fetch_in_collection"#替换为当前操作url
req_body = {
"collection_name": "my_collection", #替换为当前参数
'ids': [1, 2, -1]
}
result = client.do_req(req_method=req_method, req_path=req_path, req_params=req_params, req_body=req_body)
print("req http status code: ", result.status_code)
print("req result:
", result.text)
package org.example;
import com.volcengine.auth.ISignerV4;
import com.volcengine.auth.impl.SignerV4Impl;
import com.volcengine.model.Credentials;
import com.volcengine.service.SignableRequest;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.net.URI;
import java.util.List;
public class DemoSignAndCallEmbeddingApiV2 {
private static String ak = System.getenv("AK");
private static String sk = System.getenv("SK");
private static String host = "api-vikingdb.vikingdb.cn-beijing.volces.com";
public static void main(String[] args) throws Exception {
doEmbedding();
}
public static String doEmbedding() throws Exception {
String jsonString = "{" +
""dense_model": {" +
""name": "doubao-embedding-vision"," +
""version": "251215"," +
""dim": 1024" +
"}," +
""sparse_model": {" +
""name": "bge-m3"," +
""version": "default"" +
"}," +
""data": [" +
"{" +
""text": "天很蓝。"" +
"}," +
"{" +
""text": "海很深。"" +
"}" +
"]" +
"}";
System.out.println(jsonString);
String path = "/api/vikingdb/embedding";
//可自行处理做更加详细的错误处理
try {
SignableRequest signableRequest = prepareRequest(host, path, "POST", null, jsonString, ak, sk);
URI uri = new URIBuilder().setScheme("https").setHost(host).setPath(path).build();
HttpPost httpPost = new HttpPost(uri);
httpPost.setConfig(signableRequest.getConfig());
httpPost.setEntity(signableRequest.getEntity());
for (Header header : signableRequest.getAllHeaders()) {
httpPost.setHeader(header.getName(), header.getValue());
}
HttpClient httpClient = HttpClients.createDefault();
HttpResponse response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
String responseBody = EntityUtils.toString(response.getEntity());
System.out.println("Status Code: " + statusCode);
System.out.println("Response Body: " + responseBody);
return responseBody;
} catch (Exception e) {
e.printStackTrace();
throw e;
}
}
public static SignableRequest prepareRequest(String host, String path, String method, List<NameValuePair> params, String body, String ak, String sk) throws Exception {
SignableRequest request = new SignableRequest();
request.setMethod(method);
request.setHeader("Accept", "application/json");
request.setHeader("Content-Type", "application/json");
request.setHeader("Host", host);
request.setEntity(new StringEntity(body, "utf-8"));
URIBuilder builder = request.getUriBuilder();
builder.setScheme("https");
builder.setHost(host);
builder.setPath(path);
if (params != null) {
builder.setParameters(params);
}
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(120000).setConnectTimeout(12000).build();
request.setConfig(requestConfig);
Credentials credentials = new Credentials("cn-beijing", "vikingdb");
credentials.setAccessKeyID(ak);
credentials.setSecretAccessKey(sk);
// 签名
ISignerV4 ISigner = new SignerV4Impl();
ISigner.sign(request, credentials);
return request;
}
}
package main
import (
"bytes"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"github.com/volcengine/volc-sdk-golang/base"
)
func doRequest(host, region, method, path, ak, sk string, query url.Values, body []byte) *http.Request {
u := url.URL{
Scheme: "https",
Host: host,
Path: path,
}
if query != nil {
u.RawQuery = query.Encode()
}
req, _ := http.NewRequest(strings.ToUpper(method), u.String(), bytes.NewReader(body))
req.Header.Add("Accept", "application/json")
req.Header.Add("Content-Type", "application/json")
req.Header.Add("Host", host)
credential := base.Credentials{
AccessKeyID: ak,
SecretAccessKey: sk,
Service: "vikingdb",
Region: region,
}
req = credential.Sign(req)
return req
}
// v2数据面API调用示例。以写入数据(UpsertData)为例。
func main() {
var ak = "**" // 您的ak
var sk = "**" // 您的sk
var host = "api-vikingdb.vikingdb.cn-beijing.volces.com" // 数据面 API 的域名。https://www.volcengine.com/docs/84313/1792715 这里以北京为例
var region = "cn-beijing"
// UpsertData接口的path
path := "/api/vikingdb/data/upsert"
// 示例写入数据。实际的数据集名称、字段名称以您的数据集为准进行修改
body := []byte(`{
"collection_name": "test_coll_with_vectorize",
"data": [
{
"f_good_id": "000135",
"f_city": "北京",
"f_text": "这是一件历史悠久的文物,具有1300年的历史",
"f_image": "tos://my_bucket/good_000135.jpg"
}
]
}`)
req := doRequest(host, region, "POST", path, ak, sk, nil, body)
response, err := http.DefaultClient.Do(req)
if err != nil {
panic(err)
}
defer response.Body.Close()
bodyBytes, err := io.ReadAll(response.Body)
if err != nil {
panic(err)
}
// 处理响应信息,可根据您的业务逻辑需要,进行调整
httpCode := response.StatusCode
fmt.Println(httpCode)
bodyString := string(bodyBytes)
fmt.Println(bodyString)
}
支持的域名和 Region
详见:地域和访问域名(Endpoint)
Region 名称 | 域名 |
|---|
cn-beijing | api-vikingdb.vikingdb.cn-beijing.volces.com |
cn-shanghai | api-vikingdb.vikingdb.cn-shanghai.volces.com |
cn-guangzhou | api-vikingdb.vikingdb.cn-guangzhou.volces.com |
ap-southeast-1 | api-vikingdb.vikingdb.ap-southeast-1.volces.com |
响应体公共参数介绍
参数名 | 类型 | 说明 |
|---|
request_id | string | 请求 ID |
code | string | 操作状态码。成功则为"Success",否则为错误码短语。遵循"Xxx"或"Xxx.Yyy"格式。 |
message | string | 操作执行信息。成功则为"The API call was executed successfully.",否则为错误信息。遵循完整的英文语句表达。 |
result | map | 如果操作没有结果或不需要结果,则返回的 result = null |