Dosu LogoDosu Logo
Ask
Join our Discord
Organization avatar
difyPublic
Dify
Documentsdify
Vector Store Integration
Vector Store Integration
Type
Topic
Status
Published
Created
Jul 30, 2026
Updated
Sep 15, 2026
Created by
Dosu Bot
Updated by
Dosu Bot

Vector Store Integration#

Dify's vector store layer is built around the BaseVector abstract class, which defines a common contract every backend must implement: search_by_vector, search_by_full_text, create, add_texts, delete_by_ids, and delete_by_metadata_field. Backends are registered as plugins under api/providers/vdb/ and resolved at dataset-open time.

The VectorType enum lists 38+ registered backends, including pgvector, Milvus, Qdrant, Weaviate, Chroma, OpenSearch, Elasticsearch (plus a Japanese variant), MatrixOne, Tencent, TiDB, OceanBase, AnalyticDB, and others.

Related articles: Retrieval Filtering and Scoring (pipeline above this layer) · Hybrid Search · Milvus Integration · Weaviate Vector Store


search_by_vector Contract#

All backends accept a consistent set of kwargs :

kwargDefaultPurpose
top_k4–5Maximum candidates to return
score_threshold0.0Minimum score gate
document_ids_filterNoneRestrict to specific parent documents

Returned Document objects carry metadata["score"] so the layer above can apply further threshold filtering without recomputing scores.

Hybrid search note: RetrievalService forces score_threshold=0.0 at vector retrieval time for hybrid queries, deferring threshold enforcement to post-fusion reranking. See Retrieval Filtering and Scoring .


Score Computation by Backend#

Backends fall into two camps — distance-to-score conversion and native score — so score_threshold values are not portable across backends .

Distance-to-Score (score = f(distance))#

BackendScore formulaSource
pgvector1 - distance (cosine <=>)pgvector.py L199–205
Weaviate1.0 - distance
Chroma1 - distance (Euclidean)
MatrixOne (search_by_vector)1.0 / (1.0 + distance) (L2)matrixone_vector.py L168–172
MatrixOne (search_by_full_text)1 - distancematrixone_vector.py L205–209

MatrixOne uses different formulas across its two search paths because L2 ANN distances and full-text distances have different numeric ranges: 1/(1+d) maps L2 distance from [0, ∞) into (0, 1], while 1 - d is appropriate for the normalized distance returned by full-text search .

Native Score (no conversion)#

BackendScore source
Milvusresult["distance"] stored as-is (inner-product / HNSW) — note threshold uses > not >=
Qdrantresult.score from the Qdrant client
OpenSearchhit["_score"] (BM25 or script_score)
Elasticsearchhit["_score"] (cosine similarity via KNN)

Score Threshold Filtering#

Post-query (most backends)#

pgvector, Weaviate, Chroma, MatrixOne, OpenSearch, and Elasticsearch all fetch top_k results first, then filter in Python: if score >= score_threshold . pgvector explicitly assigns metadata["score"] even before the threshold check, so the score is always available on returned docs .

In-query + post-query (Qdrant only)#

Qdrant passes score_threshold directly to _client.search(score_threshold=...), pruning at the index level, then applies a redundant Python check. As an edge case, score_threshold >= 1 short-circuits immediately to an empty list without a DB round-trip .

Milvus threshold semantics#

Milvus uses a strict > comparison (result["distance"] > score_threshold) rather than >=, so a score_threshold of exactly 0.0 still returns all results .


document_ids_filter Translation#

All backends translate document_ids_filter to backend-native filter syntax before the query :

BackendFilter mechanism
pgvectorSQL WHERE meta->>'document_id' IN (...) — pgvector.py L186–190
Milvusfilter='metadata["document_id"] in [...]' — milvus_vector.py L261–265
MatrixOnefilter={"document_id": {"$in": ids}} via MoVectorClient — matrixone_vector.py L161–163
Elasticsearchterms filter inside the KNN body —

Tencent VectorDB bug (fixed 2025-08-07, PR #23564): In full-text search mode, document_ids_filter was previously silently dropped. The fix builds Filter.In("metadata.document_id", document_ids_filter) and passes it into hybrid_search(filter=...).


MatrixOne-Specific Notes#

matrixone_vector.py was added 2026-07-29:

  • Backed by mo_vector.MoVectorClient over a MySQL-protocol connection (mysql+pymysql://). Default metric is l2, configurable via MATRIXONE_METRIC env var .
  • Client initialization is lazy (via @ensure_client decorator) and guarded by a Redis lock (vector_indexing_lock_{collection_name}). Full-text index creation is cached for 1 hour (redis_client.set(..., ex=3600)) to avoid recreation on every call .
  • Unit coverage: test_matrixone_vector.py.

Metadata Type Constraints: Tencent VectorDB Deadlock#

Tencent VectorDB rejects boolean values in JSON metadata. Summary index vectors include is_summary: True, which caused upserts to fail. The failure path opened a second DB session to record the error while the caller-owned session still held a row lock — resulting in a deadlock .

Fix (PR #41916):

  1. In tencent_vector.py add_texts(), convert metadata["is_summary"] = True → 1 before upsert.
  2. In summary_index_service.py vectorize_summary(), when a caller-owned session is provided, write error status back on that session and re-raise — do not open a new error_session that competes for the same row lock.

This session ownership discipline in error paths applies to any backend where vectorization can fail after the caller has already flushed a row.


Key Files#

FileRole
vdb/vector_base.pyBaseVector abstract class
vdb/vector_type.pyVectorType enum — all registered backends
vdb-pgvector/…/pgvector.pypgvector: cosine distance, 1-distance score, post-query threshold
vdb-milvus/…/milvus_vector.pyMilvus: native distance score, > threshold, HNSW/IP
vdb-matrixone/…/matrixone_vector.pyMatrixOne: L2/MySQL, 1/(1+d) score formula
retrieval_service.pyCalls search_by_vector; hybrid score deferral
summary_index_service.pySummary vectorization pipeline, session ownership fix
Documents
Account Activity Tracking
Agent API Routes
Agent App Architecture
Dify Agent Server 模块分析 (Commit 55f95dbc)
Agent App Event Architecture
Agent App Input Variables
Agent App MCP Integration
Agent Context Compaction
Agent Cost and Usage Tracking
Agent File Handling
Agent File Upload Configuration
Agent Icon Data Model
Agent Log Event Pipeline
Agent Message History
Dify Agent Server 模块分析 (Commit 55f95dbc)
Agent Model Settings
Agent Node Data Models
Agent Response Schema
Agent Runtime
Dify Agent Server 模块分析 (Commit 55f95dbc)
Agent Runtime Backend Initialization
Agent Runtime Layer Provider Registration
Dify Agent Server 模块分析 (Commit 55f95dbc)
Agent Sandbox SSRF Allowlisting
Agent Shell Layer
Dify Agent Server 模块分析 (Commit 55f95dbc)
Agent Soul Config Management
Agent Strategy Plugin Architecture
Agent V2 Architecture
Dify Agent Server 模块分析 (Commit 55f95dbc)
Agent V2 Configure Interface
Agent V2 Feature Flags
Agent V2 File and Vision Handling
Agent V2 Publish Validation
Agent V2 Variable System
Agent Workflow Node Variable References
Amplitude Analytics Integration
Annotation Reply and Moderation Short-Circuit
API Documentation Pipeline
App Mode Configuration
App Publishing and Embedding
Auth Route Architecture
Avatar Management
Branding Customization
Browser Tab and State Management
Builtin Tool Provider Credentials
Celery Task Resilience
Chat Action Bar Mobile Visibility
Chat Avatar Rendering
Chatbot Conversation State Recovery
Chatbot Widget Embedding
Collaborative Workflow Editing
Console API DELETE Request Handling
Console Authentication
Conversation Deep-Linking
Credential Encryption and Secret Management
CSV Data Ingestion
Custom Tool Authentication
Custom Tool HTTP Timeout Configuration
Custom Tool OpenAPI Integration
Data Export
Database Migration System
Database Session Management
Database Transaction Isolation
Dataset Batch Import
Dataset Deletion
Dataset Permission Model
Dataset Segmentation Configuration
Dependency Injection and Testability
Dify Agent Server 模块分析 (Commit 55f95dbc)
Dify Agent Monorepo Structure
Dify Agent Server 模块分析 (Commit 55f95dbc)
Dify Cloud Billing
Dify OpenAPI
difyctl CLI
Docker Container Security
Docker Deployment and Upgrades
Docker Frontend Configuration
Docker Networking
Docker Storage and Permissions
Document Indexing Operations
DocumentSegment Position Assignment
Draft Variable Storage Cleanup
E2B Sandbox Integration
Edition-Based Feature Gating
Elasticsearch Integration
Embedding Cache Integrity
Excel Extractor
External Knowledge Integration
Extractor Encoding Fallback
File Access Control
File Array Handling
File Download Architecture
File Download Security
File Storage Synchronization
File Upload and Download Integrity
File Upload Configuration
File Upload Processing
File URL Resolution
Flask Application Architecture
Flask Blueprint and Route Registration
Graph Streaming Infrastructure
Home Directory Management
HTTP Request Node
HTTP Request Node Key-Value Editor
httpx and Gevent Compatibility
Human Input Node
Human-in-the-Loop Authorization
Hybrid Search
Icon URL Resolution
Iframe Embedding Security
Internationalization and Locale Management
JSON-in-Markdown Parsing
JWT Authentication
Keyboard Shortcut Management
Keyword Moderation
Knowledge Base API
Knowledge Base Document Processing
Knowledge Base Metadata Filtering
Knowledge Base Summarization Pipeline
Langfuse Integration
LDAP Authentication and Workspace Provisioning
Lexical Editor Integration
LiteLLM Dependency Management
LLM Provider Message Validation
LLM Structured Output
MCP Protocol Integration for Dify Workflows
Local Development Configuration
Local Embedding Model Deployment
Log Filtering
Markdown Extractor Heading Parsing
Markdown Rendering
Marketplace Plugin Filtering
MCP Client Session Management
MCP Client Transport and Connectivity
MCP OAuth Integration
MCP Protocol Integration
MCP Protocol Integration for Dify Workflows
MCP Provider Architecture
MCP Protocol Integration for Dify Workflows
MCP Server Code Lifecycle
MCP Server URL Generation
MCP Streaming Mode
MCP Tool Content Processing
MCP Tool Integration
MCP Protocol Integration for Dify Workflows
MCP Tool Parameter Binding
MCP Tool Provider Management
Milvus Integration
Model Plugin Boolean Parameter Handling
Model Provider Error Handling
Monaco Editor Integration
Multi-Tenant Context Propagation
Multimodal Knowledge Base Support
Multimodal Prompt Delivery
N+1 Query Optimization
Next.js Routing and Redirects
Next.js SSR Authentication
Nginx Reverse Proxy Configuration
Notion Extractor Table Parsing
NumPy CPU Compatibility
OAuth Login Flow
Observability and Tracing
OpenAI-Compatible Server Integration
OpenAPI Spec Accuracy
OpenDAL Storage Backend
Ops Trace Data Models
Oracle Database Connectivity
Parallel Workflow Execution
Parent-Child Retrieval Architecture
Plugin API Key Configuration
Plugin Architecture
Plugin Credential Management
Plugin Daemon Architecture
Plugin Daemon Communication
Plugin Daemon Model Parameter Handling
Plugin Database Integrity
Plugin Dependency Management
Plugin Error Handling
Plugin File Handling
Plugin Lifecycle Management
Plugin Marketplace Connectivity
Plugin Model Caching
Plugin Model Invocation
Plugin Permissions
Plugin Storage Configuration
Plugin System Timeouts
Plugin Taxonomy and Validation
Plugin Trigger OAuth Refresh
Private Address Detection
Provider Model & Credential Management
RAG Document Extraction
RAG Web Crawling Providers
RBAC Initialization
RBAC Permission Key Lookup
Reasoning Model Integration
Reasoning Tag Filtering
Redis Connection Management
Redis Streaming Resilience
Release Breaking Changes
Remote File Fetching
Remote File Handling and Validation
Retrieval Config Management
Retrieval Filtering and Scoring
RTL Locale Support
Sandbox Code Execution
Sandbox Network Isolation
Score Threshold Sentinel Semantics
Segment Update and Attachment Lifecycle
Server Deployment Configuration
Service API Error Handling
Service API Pagination
Session Refresh Token Race Conditions
Shell Provider Lifecycle
Snippet Variable Handling
SQLite Test Infrastructure
SSE Stream Lifecycle
SSE Stream Terminal Event Delivery
SSR Data Fetching
SSRF Proxy
Suggested Questions After Answer
Summary Index
Tenant-Isolated Document Indexing Queue
Test Doubles and In-Memory Repositories
TiDB Vector Full-Text Search
Time Tools
Timestamp Management
Tool File URL Signing
Tool Node Input Validation
Tool OAuth Authorization
Tool Parameter Type Conversion
Tool Provider Authorization
Trace Task Pipeline
URL Content Extraction
User and Tenant Context Propagation
Dify Agent Server 模块分析 (Commit 55f95dbc)
User Roles and Permissions
Variable Pool Falsy Value Handling
Variable Resolution and Template Substitution
Vector Database Plugin Architecture
Vector Store Integration
Vinext Build Pipeline
Weaviate Vector Store
Web Container Docker Configuration
Webhook Trigger Publish Sync
Webhook Trigger System
WebSocket Service Architecture
Word Document Extraction
Workflow Agent Node Configuration
Workflow and Agent Composition
Workflow Conditional Branching
Workflow Conversation State Management
Workflow Copy and Export
Workflow Draft Synchronization
Workflow Execution Dispatch
Dify Agent Server 模块分析 (Commit 55f95dbc)
Workflow Execution Persistence
Workflow Fail Branch Architecture
Workflow File Handling
Workflow Generator Node Reference Rewriting
Workflow Graph Validation
Workflow Iteration Node Execution
Workflow LLM Node Configuration
Workflow Memory Management
Workflow Node Versioning
Workflow Pause-Resume State Management
Workflow Resume Architecture
Workflow Run State Management
Workflow Schedule Triggers
Workflow Test Run Execution
Workflow Timeout and Execution Limits
Workflow Tool Visibility and Access Control
Workflow Trigger Log Lifecycle
Workflow Variable Size Management