Skip to main content

Create Knowledge Base and Import

Create a Knowledge Base and import files in a single call (merges CreateIndex and SubmitIndexJob). On success, the response returns the Knowledge Base ID (data.pipelineId) and the import job ID (data.ingestionId).

Prerequisites

Get an API key and a workspace ID, and configure authentication first. See API overview and Authentication.

Endpoint

POST /api/v1/indices/rag/index/create_v2 Create a Knowledge Base and import files in a single call (merges CreateIndex and SubmitIndexJob).

Request body

The file ID parameter is docIds — not file_ids or fileIds. However, the validation error message uses the internal name file_ids.

Basic parameters

FieldRequiredTypeDescription
nameYesstringKnowledge Base name, 1-20 characters. Must be unique within the workspace.
descriptionNostringKnowledge Base description, 0-500 characters. Empty by default.
structureTypeYesstringStructure type: unstructured or structured. Use unstructured for document, image, and multimedia, and structured for table.
knowledgeTypeNostringKnowledge Base type: document (Document Search), table (Data Query), image (Image Q&A), or multimedia (Audio and Video Search). Supply together with knowledgeScene or omit both. When both are omitted, the system applies defaults based on structureType. See the scenario constraints below.
knowledgeSceneNostringUsage scenario. The value depends on knowledgeType and must be supplied together with it or omitted together. lite_document_qa requires sinkType=BUILT_IN. visual_perception_qa and image_qa require multimodalEmbeddingModelName. document also accepts visual_document_qa, but the console no longer exposes this option.
sinkTypeYesstringVector storage type. DEFAULT and BUILT_IN both use platform-managed vector storage. ADB means AnalyticDB for PostgreSQL and requires sinkInstanceId and sinkRegion. lite_document_qa supports only BUILT_IN.
sourceTypeYesstringImport mode. DATA_CENTER_FILE requires docIds; DATA_CENTER_CATEGORY requires categoryIds; DATA_CENTER_STRUCTURED_TABLE requires tableIds and columns. The top-level sourceType determines which parameters are validated; the identically named field in dataSources cannot replace it.
embeddingModelNameNostringEmbedding model, such as text-embedding-v3, text-embedding-v4, or qwen3.7-text-embedding. For basic document Q&A, the default is text-embedding-v3 when omitted.
multimodalEmbeddingModelNameConditionalstringMultimodal embedding model, such as qwen3-vl-embedding. Required when knowledgeScene is visual_perception_qa or image_qa. Missing or invalid values return invalid multi embedding model. Optional for audio and video search.
docIdsConditionalarray<string>Required when sourceType=DATA_CENTER_FILE. Providing only categoryIds is not a substitute. Values come from the fileId returned after registering a file with addFile, or query existing files through listFile. We recommend importing no more than 10,000. The parameter name is docIds — not file_ids or fileIds. However, validation error messages use the name file_ids.
categoryIdsConditionalarray<string>Required when sourceType=DATA_CENTER_CATEGORY. Providing only docIds is not a substitute. Specifying category IDs imports all files under the corresponding categories. We recommend importing no more than 10,000. Obtain category IDs through listCategory.
dataSourcesNoarray<object>Optional data source configuration. Its sourceType sub-field does not replace the top-level sourceType in determining the import mode. If provided, keep it consistent with the top-level sourceType.
pipelineCommercialTypeNostringEdition: standard (default) or enterprise.
pipelineCommercialCuConditionalintegerNumber of RCUs, 1-200. Required when pipelineCommercialType=enterprise; otherwise the request returns Required parameter(index_commercial_cu) missing or invalid.
pipelineRetrieveRateLimitStrategyNostringRate-limit strategy for dependent retrieval links, for enterprise only. Currently supports downgrade (use the lightweight retrieval link), which is also the default.

Chunking and parsing parameters

FieldRequiredTypeDescription
chunkModeNostringChunking mode. Default: auto. Supported values: length, page, regex, and h1 through h5 for the corresponding heading levels.
chunkSizeNointegerChunk size in characters. Default for basic document Q&A: 500. Valid range: 1-6000. Recommended: 300-800. When set below 100, you must also set overlapSize to a smaller value.
overlapSizeNointegerOverlap between adjacent chunks in characters. Default: 100. Valid range: 0-1024. Must be smaller than chunkSize. The console field chunkOverlap is equivalent; either name can be used.
separatorConditionalstringSentence separator. Required and effective only when chunkMode=regex, for example (?<=。). Not needed for other modes.
enableHeadersNobooleanWhether to treat the first row of xlsx and xls files as a header and prepend it to each data chunk. Default: false. Enable only when the spreadsheet contains headers.
metaExtractColumnsNoarray<object>Metadata extraction configuration with up to five fields. It takes effect only when the knowledge base is created and cannot be added later through the update API. For element fields, see Metadata extraction configuration.

Retrieval and reranking parameters

FieldRequiredTypeDescription
enableRewriteNobooleanWhether to enable conversational query rewriting. Default for basic document Q&A: true.
rerankModelNameNostringReranking model. Default for basic document Q&A: qwen3-rerank. Also supports qwen3-rerank-hybrid, gte-rerank, and gte-rerank-hybrid. The latter two will no longer be updated and are not recommended.
rerankMinScoreNonumberSimilarity threshold. Default for basic document Q&A: 0.01. Valid range: 0.01-1.00.
rerankTopNNointegerDefault number of results after reranking. Default: 5. Valid range: 1-20. When set at creation, it becomes the default for subsequent Retrieve calls and can be overridden by RerankTopN in a Retrieve request.
sparseSimilarityTopKNointegerKeyword retrieval TopK. Default: 100. Valid range: 0-100. The sum of sparseSimilarityTopK and denseSimilarityTopK must not exceed 200.
denseSimilarityTopKNointegerVector retrieval TopK. Default: 100. Valid range: 0-100. The sum of sparseSimilarityTopK and denseSimilarityTopK must not exceed 200. For basic document Q&A, it must also be at least rerankTopN so that enough candidates are available.
rerankModeNostringInstruction mode of the reranking model: qa (default), similar, or custom.
rerankInstructNostringCustom reranking instruction. Effective only when rerankMode=custom.

Structured data and external storage parameters

FieldRequiredTypeDescription
tableIdsConditionalarray<string>Table IDs required for Data Query Knowledge Bases. If multiple IDs are provided, only the first is used. Obtain IDs from the table list in Data Connection.
columnsConditionalarray<object>Column configuration required for Data Query Knowledge Bases. Each element contains name (column name), type (string, double, long, datetime, or image_url), isSearch (whether the column participates in retrieval, default true), and isRecall (whether the column participates in model responses, default true).
connectIdNostringCustom database connector ID, which replaces the legacy datasourceCode field and is used with table. Not required when importing an existing data-center table through tableIds, and connectId + table cannot replace the tableIds required by this endpoint.
datasourceCodeNostringLegacy data source code. Use connectId instead. Required only for a custom database source and used with database and table.
databaseNostringCustom database name. Required only for a custom database source and used with datasourceCode or connectId and table.
tableNostringCustom table name. Required only for a custom database source and used with datasourceCode or connectId and database.
sinkInstanceIdConditionalstringAnalyticDB for PostgreSQL instance ID. Required when sinkType=ADB; otherwise the request returns Required parameter(db_instance_id) missing or invalid.
sinkRegionConditionalstringRegion of the AnalyticDB for PostgreSQL instance. Required when sinkType=ADB.
  • To create a Data Query Knowledge Base from an existing data-center table, the minimum parameter set is sourceType=DATA_CENTER_STRUCTURED_TABLE, tableIds, and columns. connectId, datasourceCode, database, and table are used only for custom database sources and are not required for this path.
  • createIndexType and channelType are not available. Do not pass them.
  • Browser network requests from the console use an internal console gateway and console-specific parameters. Their authentication, endpoints, and parameter contract differ from the public API. Use this page as the public API reference instead of copying console payloads.
  • This endpoint does not support enabling the console's Automatically sync knowledge index feature through dataSync; passing dataSync:true has no effect. After new files are added to a category, call Submit import job to append the category again. Re-uploading a file with the same name in the dataset may create a new file ID and does not automatically replace the old document in the Knowledge Base. Appending does not delete documents that were removed from the dataset; delete files from the dataset and the Knowledge Base separately.
  • In console payloads, dataType maps to structureType, and cornerstoneParam is a console-internal field; neither is an independent public parameter of this endpoint.

Wiki configuration parameters

For a Flagship knowledge base (pipelineCommercialType=enterprise) with knowledge scene basic_document_qa, you can enable Wiki and the ontology knowledge graph while creating the knowledge base. For the feature and billing, see Wiki and Ontology Knowledge Graph.
FieldRequiredTypeDescription
wikiEnabledYesbooleanWhether to enable Wiki while creating the knowledge base. Omitted or null means not enabled; set true to enable
wikiAutoUpdateConditionalbooleanWiki auto-update switch. Required when wikiEnabled is true; only auto-update mode is supported, so it must be true. Existing documents are submitted for generation automatically, and newly imported documents are submitted after import completes
wikiConfig.extraction.synthesisModelIdConditionalstringWiki extraction model. Required, non-blank, and case-sensitive when enabling Wiki; one of qwen3.8-flash, qwen3.8-max, qwen3.7-plus
wikiConfig.extraction.extractionGranularityConditionalstringExtraction granularity. Required when enabling Wiki, no default; one of focused, standard, exhaustive
wikiConfig.extraction.contentInstructionsNostringWiki content generation requirements, controlling the emphasis of summaries, pages, and the home page. Length is counted in Unicode characters, up to 4000
wikiConfig.extraction.extractionInstructionsNostringWiki extraction focus, specifying the domain entities and concepts to prioritize. Length is counted in Unicode characters, up to 4000
When wikiEnabled is true, wikiConfig is required and must include the extraction group. If Wiki configuration validation fails, the create request fails outright and the knowledge base is not created; if validation passes, the knowledge base is created first and Wiki is enabled asynchronously afterwards — a success response only means the enable request was accepted. On configuration validation failure, field names in message are snake_case. Enabling and generation are asynchronous with no status-query endpoint; confirm the search_type=wiki service is published via List Agents before a trial retrieval.

Knowledge Base type and usage scenario

knowledgeType and knowledgeScene correspond to Knowledge Base Type and Usage Scenario in step 1 of the console creation wizard. They must be supplied together or omitted together — sending only one returns knowledgeType and knowledgeScene cannot be empty. When both are omitted, the system applies defaults based on structureType. The console only offers a Usage Scenario choice for Document Search. The other three types have a fixed scenario that the console fills in automatically. When creating through the API, you may omit both fields and let the system apply defaults based on structureType. They are required as a pair only when you need a non-default type or scenario.
knowledgeTypeConsole labelstructureTypeAvailable knowledgeScene
documentDocument Searchunstructuredbasic_document_qa (basic document Q&A)
visual_perception_qa (visual understanding, rich text documents)
lite_document_qa (express Q&A)
tableData Querystructuredbasic_table_qa (fixed)
imageImage Q&Aunstructuredimage_qa (fixed)
multimediaAudio and Video Searchunstructuredbasic_multimedia_qa (fixed)
  • An incompatible knowledgeType and structureType pair returns knowledgeType and structureType do not match. A knowledgeScene that does not belong to the selected type returns knowledgeType and knowledgeScene do not match.
  • lite_document_qa (express Q&A) requires sinkType to be BUILT_IN. Using the default DEFAULT returns Lite Rag only supports BUILT_IN sink type.
  • visual_perception_qa and image_qa must specify a multimodal embedding model through multimodalEmbeddingModelName (for example qwen3-vl-embedding), otherwise the request returns invalid multi embedding model.
  • The document type also has a visual_document_qa (rich media answers) scenario. The API still accepts this value, but the console no longer exposes it, so avoid it for new Knowledge Bases.
Example request body for Image Q&A:
{
  "name": "image-kb",
  "description": "Image Q&A Knowledge Base",
  "structureType": "unstructured",
  "knowledgeType": "image",
  "knowledgeScene": "image_qa",
  "sinkType": "BUILT_IN",
  "sourceType": "DATA_CENTER_FILE",
  "multimodalEmbeddingModelName": "qwen3-vl-embedding",
  "docIds": ["your-file-id"],
  "dataSources": [{ "sourceType": "DATA_CENTER_FILE" }]
}

Metadata extraction configuration

metaExtractColumns generates metadata for documents when the knowledge base is created and its index is built. Each array element supports the following fields:
FieldRequiredTypeDescription
keyYesstringMetadata field name. It must be 1-50 characters long and contain only letters and underscores.
descNostringChinese description of the metadata field, 0-1000 characters. The default value is empty. Chinese characters, letters, digits, underscores (_), hyphens (-), periods (.), and colons (:) are supported.
typeYesstringExtraction method: constant, variable, custom_prompt (LLM), regular (regular expression), or keywords (keyword search).
valueYesstringExtraction rule corresponding to type, as described in the following table.
enableSearchNobooleanWhether the metadata field and its values participate in knowledge retrieval with the text chunk. Default: false.
enableLlmNobooleanWhether the metadata field and its values are passed to the LLM as input for response generation. Default: false.
typevalue descriptionExample
constantA fixed value assigned to all files in the knowledge base.meta_test
variableA file variable. file_name uses the file name, and cat_name uses the name of the category containing the file.file_name
custom_promptAn entity description that guides the LLM to extract relevant information from each file.The main product name in the document. Extract only one complete product name.
regularA regular expression used to match and extract document content.StarHub X1
keywordsPreset keywords separated by commas. Only keywords that actually appear in the document are returned.smartphone,battery life,water resistance
Place the following fragment at the same level as creation parameters such as name and docIds:
{
  "metaExtractColumns": [
    {
      "key": "source_file_name",
      "desc": "Source file name",
      "type": "variable",
      "value": "file_name",
      "enableSearch": true,
      "enableLlm": true
    },
    {
      "key": "product_name",
      "desc": "Product name",
      "type": "custom_prompt",
      "value": "The main product name in the document. Extract only one complete product name.",
      "enableSearch": true,
      "enableLlm": true
    }
  ]
}
enableSearch and enableLlm serve different purposes from metadata_filter at query time. To filter documents by metadata when calling an application through the API, specify both pipeline_ids and metadata_filter in rag_options. For more information, see Application call parameters. After the index is built, inspect the actual extraction results in meta_extract_info through the List file details API.

Request example

curl -X POST "$BASE_URL/api/v1/indices/rag/index/create_v2" \
  -H "Authorization: Bearer $BAILIAN_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "your-kb-name",
    "description": "your-kb-description",
    "structureType": "unstructured",
    "sinkType": "DEFAULT",
    "sourceType": "DATA_CENTER_FILE",
    "embeddingModelName": "text-embedding-v4",
    "chunkSize": 600,
    "docIds": ["your-file-id-1", "your-file-id-2"],
    "dataSources": [{"sourceType": "DATA_CENTER_FILE"}]
  }'
To import by category, set the top-level sourceType to DATA_CENTER_CATEGORY and pass categoryIds. You do not need docIds or dataSources:
curl -X POST "$BASE_URL/api/v1/indices/rag/index/create_v2" \
  -H "Authorization: Bearer $BAILIAN_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "your-kb-name",
    "description": "your-kb-description",
    "structureType": "unstructured",
    "sinkType": "DEFAULT",
    "sourceType": "DATA_CENTER_CATEGORY",
    "embeddingModelName": "text-embedding-v4",
    "chunkSize": 600,
    "categoryIds": ["your-category-id"]
  }'
To create an enterprise Knowledge Base, also include the following fields at the top level of the request body. When pipelineCommercialType is omitted, the default is standard:
{
  "pipelineCommercialType": "enterprise",
  "pipelineCommercialCu": 1
}
Image Q&A knowledge base (knowledgeType=image, knowledgeScene=image_qa, requires sinkType=BUILT_IN and a multimodal embedding model):
curl -X POST "$BASE_URL/api/v1/indices/rag/index/create_v2" \
  -H "Authorization: Bearer $BAILIAN_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "image-kb",
    "description": "Image Q&A knowledge base",
    "structureType": "unstructured",
    "knowledgeType": "image",
    "knowledgeScene": "image_qa",
    "sinkType": "BUILT_IN",
    "sourceType": "DATA_CENTER_FILE",
    "multimodalEmbeddingModelName": "qwen3-vl-embedding",
    "docIds": ["your-file-id"],
    "dataSources": [{"sourceType": "DATA_CENTER_FILE"}]
  }'
Create a Flagship document Q&A knowledge base and enable Wiki at the same time (wikiEnabled=true; see Wiki configuration parameters):
curl -X POST "$BASE_URL/api/v1/indices/rag/index/create_v2" \
  -H "Authorization: Bearer $BAILIAN_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "wiki-kb",
    "description": "Product help documentation",
    "structureType": "unstructured",
    "knowledgeType": "document",
    "knowledgeScene": "basic_document_qa",
    "sourceType": "DATA_CENTER_FILE",
    "docIds": ["your-file-id"],
    "dataSources": [{"sourceType": "DATA_CENTER_FILE"}],
    "pipelineCommercialType": "enterprise",
    "pipelineCommercialCu": 1,
    "wikiEnabled": true,
    "wikiAutoUpdate": true,
    "wikiConfig": {
      "extraction": {
        "synthesisModelId": "qwen3.8-flash",
        "extractionGranularity": "standard"
      }
    }
  }'
BASE_URL is https://{workspace_id}.cn-beijing.maas.aliyuncs.com ({workspace_id} is the workspace ID), and BAILIAN_API_KEY is your Alibaba Cloud Model Studio API key.

Response example

Returns 200 on success.
{
  "code": "Success",
  "status_code": 200,
  "success": true,
  "message": "success",
  "data": {
    "pipelineId": "h6a85zj8oc",
    "ingestionId": "7f90991a5ec24ad28c8d309ac37e6dd3",
    "status": "PENDING",
    "created_at": 1783657930436,
    "updated_at": 1783657930436
  },
  "request_id": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
  "status": "SUCCESS"
}

Response fields

FieldTypeDescription
codestringResponse code. Success when successful.
status_codeintegerHTTP status code.
successbooleanWhether the request succeeded. true when successful.
messagestringResponse message. success when successful.
request_idstringUnique request identifier. Provide this ID when troubleshooting.
statusstringRequest status. SUCCESS when successful.
dataobjectResponse data. Sub-fields: pipelineId (string, Knowledge Base ID; used as the knowledge base identifier in subsequent APIs), ingestionId (string, the import job ID for this request; track import progress through the Get Import Job Status endpoint), status (string, import job status; PENDING on successful creation), created_at (integer, Knowledge Base creation time as a Unix timestamp in milliseconds), updated_at (integer, last update time as a Unix timestamp in milliseconds).

Error codes

HTTP status codeError code (code)Description
400Index.InvalidParameterdescription exceeds 500 characters: Required parameter(description length range[1-500]) missing or invalid, please check the request parameters.
400Index.InvalidParameterdocIds is missing or empty when sourceType=DATA_CENTER_FILE. This error occurs even if categoryIds is provided: Required parameter(file_ids) missing or invalid, please check the request parameters.
400Index.InvalidParametercategoryIds is missing when sourceType=DATA_CENTER_CATEGORY. This error occurs if only docIds is provided or the category parameter is incorrectly named source_ids: Required parameter(source_ids) missing or invalid, please check the request parameters.
400Index.InvalidParameterThe top-level sourceType is missing. This error occurs even if dataSources is provided: Required parameter(data_sources) missing or invalid, please check the request parameters.
400Index.FileEmptyErrorA file ID in docIds does not exist: fetch empty file list from data center.
401InvalidApiKeyInvalid or missing API key: Invalid API-key provided.
400Index.WikiEditionNotSupportedThe knowledge base is not Flagship when enabling Wiki (unspecified specification is treated as Standard)
400Index.WikiSceneNotSupportedknowledgeScene is not basic_document_qa when enabling Wiki
400Index.WikiConfigInvalidInvalid Wiki configuration key, e.g. missing extraction group, missing or non-whitelisted synthesisModelId, invalid extractionGranularity, or over-length instructions; locate by the field name in message
400Index.InvalidParameterwikiAutoUpdate missing or not true when enabling Wiki
A 400 response caused by a missing top-level sourceType may also leave an empty Knowledge Base with the requested name. Before retrying, check for and delete such empty Knowledge Bases through List Knowledge Bases.