ナレッジベースからチャンクを取得 / テスト検索
ナレッジベースを検索し、クエリに最も関連性の高いチャンクを返します。本番環境の検索とテスト検索の両方に使用できます。
1 min read
post/datasets/{dataset_id}/retrieve
Request example
curl --request POST \
--url https://api.dify.ai/v1/datasets/{dataset_id}/retrieve \
--header 'Authorization: Bearer <token>' \
--header 'Content-Type: application/json' \
--data '{
"attachment_ids": [
"<string>"
],
"external_retrieval_model": {
"score_threshold": 1,
"score_threshold_enabled": true,
"top_k": 1
},
"query": "<string>",
"retrieval_model": {
"metadata_filtering_conditions": {
"conditions": [
{
"comparison_operator": "contains",
"name": "<string>",
"value": "<string>"
}
],
"logical_operator": "and"
},
"reranking_enable": true,
"reranking_mode": "reranking_model",
"reranking_model": {
"reranking_model_name": "<string>",
"reranking_provider_name": "<string>"
},
"score_threshold": 1,
"score_threshold_enabled": true,
"search_method": "keyword_search",
"top_k": 1,
"weights": {
"keyword_setting": {
"keyword_weight": 1
},
"vector_setting": {
"embedding_model_name": "<string>",
"embedding_provider_name": "<string>",
"vector_weight": 1
},
"weight_type": "semantic_first"
}
}
}'import requests
url = "https://api.dify.ai/v1/datasets/{dataset_id}/retrieve"
headers = {
"Authorization": "Bearer <token>",
"Content-Type": "application/json",
}
payload = {
"attachment_ids": [
"<string>"
],
"external_retrieval_model": {
"score_threshold": 1,
"score_threshold_enabled": True,
"top_k": 1
},
"query": "<string>",
"retrieval_model": {
"metadata_filtering_conditions": {
"conditions": [
{
"comparison_operator": "contains",
"name": "<string>",
"value": "<string>"
}
],
"logical_operator": "and"
},
"reranking_enable": True,
"reranking_mode": "reranking_model",
"reranking_model": {
"reranking_model_name": "<string>",
"reranking_provider_name": "<string>"
},
"score_threshold": 1,
"score_threshold_enabled": True,
"search_method": "keyword_search",
"top_k": 1,
"weights": {
"keyword_setting": {
"keyword_weight": 1
},
"vector_setting": {
"embedding_model_name": "<string>",
"embedding_provider_name": "<string>",
"vector_weight": 1
},
"weight_type": "semantic_first"
}
}
}
response = requests.request("POST", url, headers=headers, json=payload)
print(response.text)const response = await fetch('https://api.dify.ai/v1/datasets/{dataset_id}/retrieve', {
method: 'POST',
headers: {
'Authorization': 'Bearer <token>',
'Content-Type': 'application/json'
},
body: JSON.stringify({
"attachment_ids": [
"<string>"
],
"external_retrieval_model": {
"score_threshold": 1,
"score_threshold_enabled": true,
"top_k": 1
},
"query": "<string>",
"retrieval_model": {
"metadata_filtering_conditions": {
"conditions": [
{
"comparison_operator": "contains",
"name": "<string>",
"value": "<string>"
}
],
"logical_operator": "and"
},
"reranking_enable": true,
"reranking_mode": "reranking_model",
"reranking_model": {
"reranking_model_name": "<string>",
"reranking_provider_name": "<string>"
},
"score_threshold": 1,
"score_threshold_enabled": true,
"search_method": "keyword_search",
"top_k": 1,
"weights": {
"keyword_setting": {
"keyword_weight": 1
},
"vector_setting": {
"embedding_model_name": "<string>",
"embedding_provider_name": "<string>",
"vector_weight": 1
},
"weight_type": "semantic_first"
}
}
})
});
const data = await response.json();
console.log(data);<?php
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => 'https://api.dify.ai/v1/datasets/{dataset_id}/retrieve',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => '{
"attachment_ids": [
"<string>"
],
"external_retrieval_model": {
"score_threshold": 1,
"score_threshold_enabled": true,
"top_k": 1
},
"query": "<string>",
"retrieval_model": {
"metadata_filtering_conditions": {
"conditions": [
{
"comparison_operator": "contains",
"name": "<string>",
"value": "<string>"
}
],
"logical_operator": "and"
},
"reranking_enable": true,
"reranking_mode": "reranking_model",
"reranking_model": {
"reranking_model_name": "<string>",
"reranking_provider_name": "<string>"
},
"score_threshold": 1,
"score_threshold_enabled": true,
"search_method": "keyword_search",
"top_k": 1,
"weights": {
"keyword_setting": {
"keyword_weight": 1
},
"vector_setting": {
"embedding_model_name": "<string>",
"embedding_provider_name": "<string>",
"vector_weight": 1
},
"weight_type": "semantic_first"
}
}
}',
CURLOPT_HTTPHEADER => [
'Authorization: Bearer <token>',
'Content-Type: application/json',
],
]);
$response = curl_exec($curl);
curl_close($curl);
echo $response;package main
import (
"fmt"
"io"
"net/http"
"strings"
)
func main() {
url := "https://api.dify.ai/v1/datasets/{dataset_id}/retrieve"
payload := strings.NewReader("{\n \"attachment_ids\": [\n \"<string>\"\n ],\n \"external_retrieval_model\": {\n \"score_threshold\": 1,\n \"score_threshold_enabled\": true,\n \"top_k\": 1\n },\n \"query\": \"<string>\",\n \"retrieval_model\": {\n \"metadata_filtering_conditions\": {\n \"conditions\": [\n {\n \"comparison_operator\": \"contains\",\n \"name\": \"<string>\",\n \"value\": \"<string>\"\n }\n ],\n \"logical_operator\": \"and\"\n },\n \"reranking_enable\": true,\n \"reranking_mode\": \"reranking_model\",\n \"reranking_model\": {\n \"reranking_model_name\": \"<string>\",\n \"reranking_provider_name\": \"<string>\"\n },\n \"score_threshold\": 1,\n \"score_threshold_enabled\": true,\n \"search_method\": \"keyword_search\",\n \"top_k\": 1,\n \"weights\": {\n \"keyword_setting\": {\n \"keyword_weight\": 1\n },\n \"vector_setting\": {\n \"embedding_model_name\": \"<string>\",\n \"embedding_provider_name\": \"<string>\",\n \"vector_weight\": 1\n },\n \"weight_type\": \"semantic_first\"\n }\n }\n}")
req, _ := http.NewRequest("POST", url, payload)
req.Header.Add("Authorization", "Bearer <token>")
req.Header.Add("Content-Type", "application/json")
res, _ := http.DefaultClient.Do(req)
defer res.Body.Close()
body, _ := io.ReadAll(res.Body)
fmt.Println(string(body))
}HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://api.dify.ai/v1/datasets/{dataset_id}/retrieve"))
.header("Authorization", "Bearer <token>")
.header("Content-Type", "application/json")
.method("POST", HttpRequest.BodyPublishers.ofString("{\n \"attachment_ids\": [\n \"<string>\"\n ],\n \"external_retrieval_model\": {\n \"score_threshold\": 1,\n \"score_threshold_enabled\": true,\n \"top_k\": 1\n },\n \"query\": \"<string>\",\n \"retrieval_model\": {\n \"metadata_filtering_conditions\": {\n \"conditions\": [\n {\n \"comparison_operator\": \"contains\",\n \"name\": \"<string>\",\n \"value\": \"<string>\"\n }\n ],\n \"logical_operator\": \"and\"\n },\n \"reranking_enable\": true,\n \"reranking_mode\": \"reranking_model\",\n \"reranking_model\": {\n \"reranking_model_name\": \"<string>\",\n \"reranking_provider_name\": \"<string>\"\n },\n \"score_threshold\": 1,\n \"score_threshold_enabled\": true,\n \"search_method\": \"keyword_search\",\n \"top_k\": 1,\n \"weights\": {\n \"keyword_setting\": {\n \"keyword_weight\": 1\n },\n \"vector_setting\": {\n \"embedding_model_name\": \"<string>\",\n \"embedding_provider_name\": \"<string>\",\n \"vector_weight\": 1\n },\n \"weight_type\": \"semantic_first\"\n }\n }\n}"))
.build();
HttpResponse<String> response = HttpClient.newHttpClient()
.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.body());require 'uri'
require 'net/http'
url = URI('https://api.dify.ai/v1/datasets/{dataset_id}/retrieve')
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = url.scheme == 'https'
request = Net::HTTP::Post.new(url)
request['Authorization'] = 'Bearer <token>'
request['Content-Type'] = 'application/json'
request.body = '{
"attachment_ids": [
"<string>"
],
"external_retrieval_model": {
"score_threshold": 1,
"score_threshold_enabled": true,
"top_k": 1
},
"query": "<string>",
"retrieval_model": {
"metadata_filtering_conditions": {
"conditions": [
{
"comparison_operator": "contains",
"name": "<string>",
"value": "<string>"
}
],
"logical_operator": "and"
},
"reranking_enable": true,
"reranking_mode": "reranking_model",
"reranking_model": {
"reranking_model_name": "<string>",
"reranking_provider_name": "<string>"
},
"score_threshold": 1,
"score_threshold_enabled": true,
"search_method": "keyword_search",
"top_k": 1,
"weights": {
"keyword_setting": {
"keyword_weight": 1
},
"vector_setting": {
"embedding_model_name": "<string>",
"embedding_provider_name": "<string>",
"vector_weight": 1
},
"weight_type": "semantic_first"
}
}
}'
response = http.request(request)
puts response.read_bodyResponse
{
"query": {
"content": "What is Dify?"
},
"records": [
{
"child_chunks": [],
"files": [],
"score": 0.92,
"segment": {
"answer": "",
"completed_at": 1741267200,
"content": "Dify is an open-source LLM app development platform.",
"created_at": 1741267200,
"created_by": "ad313dd6-ef04-4dd1-a5b0-c0f0b9e2e7e4",
"disabled_at": null,
"disabled_by": null,
"document": {
"data_source_type": "upload_file",
"doc_metadata": null,
"doc_type": null,
"id": "a8e0e5b5-78c6-4130-a5ce-25feb0e0b4ac",
"name": "guide.txt"
},
"document_id": "a8e0e5b5-78c6-4130-a5ce-25feb0e0b4ac",
"enabled": true,
"error": null,
"hit_count": 1,
"id": "f3d1c7be-9f3a-40d8-8eb8-3a1ef9c3f2c1",
"index_node_hash": "abc123def456",
"index_node_id": "a1b2c3d4-e5f6-7890-abcd-000000000001",
"indexing_at": 1741267200,
"keywords": [
"dify",
"platform",
"llm"
],
"position": 1,
"sign_content": "",
"status": "completed",
"stopped_at": null,
"tokens": 12,
"word_count": 9
},
"summary": null,
"tsne_position": null
}
]
}{
"code": "completion_request_error",
"message": "Completion request failed.",
"status": 400
}{
"code": "dataset_not_initialized",
"message": "The dataset is still being initialized or indexing. Please wait a moment.",
"status": 400
}{
"code": "invalid_param",
"message": "Invalid parameter value.",
"status": 400
}{
"code": "model_currently_not_support",
"message": "Dify Hosted OpenAI trial currently not support the GPT-4 model.",
"status": 400
}{
"code": "provider_not_initialize",
"message": "No valid model provider credentials found. Please go to Settings -> Model Provider to complete your provider credentials.",
"status": 400
}{
"code": "provider_quota_exceeded",
"message": "Your quota for Dify Hosted Model Provider has been exhausted. Please go to Settings -> Model Provider to complete your own provider credentials.",
"status": 400
}{
"code": "forbidden",
"message": "Dataset api access is not enabled.",
"status": 403
}{
"code": "forbidden",
"message": "Sorry, you have reached the knowledge base request rate limit of your subscription.",
"status": 403
}{
"code": "forbidden",
"message": "The API key is not authorized to access this knowledge base.",
"status": 403
}{
"code": "not_found",
"message": "Dataset not found.",
"status": 404
}{
"code": "internal_server_error",
"message": "An internal error occurred.",
"status": 500
}post/datasets/{dataset_id}/retrieve
Authorization
すべてのリクエストは API キーで認証します:Authorization: Bearer {API_KEY}。アプリのエンドポイントにはアプリの API キーを、ナレッジのエンドポイントにはナレッジベースの API キーを使用します(Dify API クイックスタート)。
キーはサーバーサイドで保管し、クライアントコードには決して埋め込まないでください。キーが欠落または無効なリクエストは HTTP 401(unauthorized)で失敗します。
Path parameters
ナレッジベース ID。ナレッジベースリストを取得 で取得します。スコープを限定したキーでは、Dify の URL から ID をコピー してください。
Body
application/json検索コンテキストに含める添付ファイル ID のリストです。
外部ナレッジベースの検索設定です。
Show child attributesHide child attributes
ドキュメントのメタデータが指定した条件に一致するチャンクのみを取得対象に絞り込みます。条件はサーバーサイドで評価されます。
Show child attributesHide child attributes
評価するメタデータ条件のリストです。
Show child attributesHide child attributes
適用する比較方法です。メタデータのタイプ別:
- 文字列または配列のメタデータ:
contains、not contains、start with、end with、is、is not、empty、not empty、in、not in - 数値メタデータ:
=、≠、>、<、≥、≤ - 時刻メタデータ:
before、after
Options:
containsnot containsstart withend withisis notemptynot emptyinnot in=≠><≥≤beforeafter比較対象とするメタデータフィールド名です。
比較対象の値です。型は
comparison_operator によって異なります。ほとんどの文字列演算子では文字列、in および not in では文字列配列、数値演算子では数値、empty および not empty では省略します。リランキングが有効かどうかです。
リランキングモードです。
reranking_enable が true の場合は必須です。Options:
reranking_modelweighted_scoreリランキングモデルの設定です。
Show child attributesHide child attributes
リランキングモデル名です。
リランクモデルプロバイダーの識別子です。organization/plugin_name/provider_name の形式です(例:langgenius/cohere/cohere)。cohere のような短縮名は langgenius/<name>/<name> に展開され、langgenius が公開したプラグインでのみ機能します。
有効な値は 利用可能なモデルを取得 で model_type=rerank を指定した際の provider フィールドから取得します。
結果の最小関連性スコアです。
score_threshold_enabled が true の場合にのみ有効です。スコア閾値フィルタリングが有効かどうかです。
検索に使用される検索メソッドです。
Options:
keyword_searchsemantic_searchfull_text_searchhybrid_search返す結果の最大数です。
ハイブリッド検索の重み設定です。
Show child attributesHide child attributes
キーワード検索の重み設定です。
Show child attributesHide child attributes
キーワード検索結果に割り当てられた重みです。
セマンティック検索の重み設定です。
セマンティック検索とキーワード検索の重みを調整するための戦略です。
Options:
semantic_firstkeyword_firstcustomizedResponses
application/json
検索結果です。
一致した検索レコードのリスト。
Show child attributesHide child attributes
階層インデックスを使用している場合、チャンク内でマッチした子チャンクです。
このチャンクに添付されたファイルです。
関連性スコアです。
ナレッジベースから一致したチャンクです。
Show child attributesHide child attributes
回答コンテンツです。Q&A モードのドキュメントで使用されます。
インデックス作成が完了したタイムスタンプです。まだ完了していない場合は
null です。チャンクのテキスト内容です。
作成タイムスタンプ(Unix エポック、秒単位)です。
チャンクを作成したユーザーの ID です。
チャンクが無効化されたタイムスタンプです。有効な場合は
null です。チャンクを無効化したユーザーの ID です。有効な場合は
null です。マッチしたチャンクの親ドキュメント情報です。
このチャンクが属するドキュメントの ID です。
このチャンクが検索に対して有効かどうかです。
インデックス作成が失敗した場合のエラーメッセージです。エラーなしの場合は
null です。このチャンクが検索クエリでマッチした回数です。
チャンクの一意識別子です。
インデックスされたコンテンツのハッシュです。変更の検出に使用されます。
ベクトルストア内のインデックスノードの ID です。
インデックス作成が開始されたタイムスタンプです。まだ開始されていない場合は
null です。キーワードベースの検索のためにこのチャンクに関連付けられたキーワードです。
ドキュメント内のチャンクの位置。
整合性検証用の署名付きコンテンツハッシュです。
チャンクのインデックスステータスです。
インデックス作成が停止されたタイムスタンプです。停止されていない場合は
null です。チャンク内容のトークン数です。
チャンク内容の単語数です。
要約インデックス経由で取得された場合の要約コンテンツです。
t-SNE 可視化の位置です。