### Install qdrant-client Source: https://github.com/qdrant/qdrant-client/blob/master/README.md Install the Qdrant client library using pip. For local inference with FastEmbed, include the `[fastembed]` extra. ```bash pip install qdrant-client ``` ```bash pip install qdrant-client[fastembed] ``` -------------------------------- ### Install Python and Dependencies Source: https://github.com/qdrant/qdrant-client/blob/master/tools/DEVELOPMENT.md Set up a Python virtual environment using pyenv and pip. Ensure specific versions of Python and grpcio are installed, along with virtualenv and poetry for dependency management. ```bash pyenv install 3.10.10 ``` ```bash pyenv local 3.10.10 ``` ```bash pip install grpcio==1.59.3 ``` ```bash pip install grpcio-tools==1.59.3 ``` ```bash pip install virtualenv ``` ```bash virtualenv venv ``` ```bash source venv/bin/activate ``` ```bash pip install poetry ``` ```bash poetry install ``` -------------------------------- ### Install FastEmbed with GPU Support Source: https://github.com/qdrant/qdrant-client/blob/master/README.md Install the qdrant-client with fastembed-gpu to enable GPU acceleration for embeddings. Note that 'fastembed-gpu' and 'fastembed' are mutually exclusive. ```bash pip install 'qdrant-client[fastembed-gpu]' ``` -------------------------------- ### Configure gnu-sed Alias on MacOS Source: https://github.com/qdrant/qdrant-client/blob/master/tools/DEVELOPMENT.md On macOS, ensure 'gnu-sed' is installed and aliased to 'sed' for compatibility. Refer to 'brew info gnu-sed' for alias setup instructions. ```bash brew install gnu-sed ``` -------------------------------- ### Get All Aliases Source: https://context7.com/qdrant/qdrant-client/llms.txt Retrieves a list of all aliases across all collections in the Qdrant instance. ```python # List all aliases all_aliases = client.get_aliases() ``` -------------------------------- ### Get Server Info and Optimizations Source: https://context7.com/qdrant/qdrant-client/llms.txt Retrieves server version information and monitors optimization tasks for a specified collection. Use `client.info()` for version details and `client.get_optimizations()` for task status. ```python # Server version and commit version_info = client.info() print(version_info.version) # e.g. "1.12.0" print(version_info.title) # "qdrant - vector search engine" # Monitor ongoing/completed optimization tasks for a collection opts = client.get_optimizations( collection_name="articles", completed_limit=10, # how many completed ops to include in response ) for opt in opts.optimizations: print(opt.status, opt.optimizations_report) ``` -------------------------------- ### Migrate Local In-Memory to Remote Source: https://context7.com/qdrant/qdrant-client/llms.txt Migrates collections from a local in-memory Qdrant client to a remote Qdrant instance. Useful for persisting a prototype or testing setup. ```python from qdrant_client import QdrantClient local = QdrantClient(":memory:") # ... populate local ... local.migrate(dest_client=dest, collection_names=["prototype"]) ``` -------------------------------- ### Get Collection Shard Distribution Source: https://context7.com/qdrant/qdrant-client/llms.txt Fetches and displays the distribution of shards for a given collection across local and remote nodes. Helps in understanding data placement in a distributed setup. ```python cluster_info = client.collection_cluster_info("articles") for shard in cluster_info.local_shards: print(shard.shard_id, shard.state) for shard in cluster_info.remote_shards: print(shard.shard_id, shard.peer_id) ``` -------------------------------- ### Collection Operations Source: https://context7.com/qdrant/qdrant-client/llms.txt Demonstrates basic collection management operations like checking existence, creating, getting detailed info, listing, and deleting collections. ```APIDOC ## Collection Operations ### Check existence before creating ```python if not client.collection_exists("articles"): client.create_collection( "articles", vectors_config=models.VectorParams(size=384, distance=models.Distance.COSINE), ) ``` ### Detailed info ```python info = client.get_collection("articles") print(info.status) # CollectionStatus.GREEN print(info.vectors_count) # number of vectors print(info.config.params.vectors) ``` ### List all collections ```python resp = client.get_collections() for col in resp.collections: print(col.name) ``` ### Delete ```python client.delete_collection("articles") # Returns: True ``` ``` -------------------------------- ### Get Collection Information Source: https://context7.com/qdrant/qdrant-client/llms.txt Retrieve detailed information about a collection, including its status, vector count, and configuration parameters. ```python # Detailed info info = client.get_collection("articles") print(info.status) # CollectionStatus.GREEN print(info.vectors_count) # number of vectors print(info.config.params.vectors) ``` -------------------------------- ### Initialize Qdrant Client in Local Mode Source: https://github.com/qdrant/qdrant-client/blob/master/README.md Instantiate the Qdrant client for local use. Use ':memory:' for in-memory storage or a path for persistent storage. ```python client = QdrantClient(":memory:") # or QdrantClient(path="path/to/db") for local mode and persistent storage ``` -------------------------------- ### Async Qdrant Client Usage Source: https://github.com/qdrant/qdrant-client/blob/master/README.md Demonstrates how to initialize and use the AsyncQdrantClient for common operations like creating collections, upserting data, and querying points. Ensure you have the necessary imports and an event loop to run async functions. ```python import asyncio import numpy as np from qdrant_client import AsyncQdrantClient, models async def main(): # Your async code using QdrantClient might be put here client = AsyncQdrantClient(url="http://localhost:6333") await client.create_collection( collection_name="my_collection", vectors_config=models.VectorParams(size=10, distance=models.Distance.COSINE), ) await client.upsert( collection_name="my_collection", points=[ models.PointStruct( id=i, vector=np.random.rand(10).tolist(), ) for i in range(100) ], ) res = await client.query_points( collection_name="my_collection", query=np.random.rand(10).tolist(), # type: ignore limit=10, ) print(res) asyncio.run(main()) ``` -------------------------------- ### Run Qdrant Server with Docker Source: https://github.com/qdrant/qdrant-client/blob/master/README.md Launch a Qdrant server locally using Docker, exposing the default port. ```bash docker run -p 6333:6333 qdrant/qdrant:latest ``` -------------------------------- ### Initialize Qdrant Client (Python) Source: https://context7.com/qdrant/qdrant-client/llms.txt Instantiate the Qdrant client for various connection types: in-memory, persistent local storage, remote server (REST/gRPC), and Qdrant Cloud with API key authentication. Supports both synchronous and asynchronous clients. ```python from qdrant_client import QdrantClient, AsyncQdrantClient, models # In-memory (local dev / CI — no server required) client = QdrantClient(":memory:") # Persistent local storage client = QdrantClient(path="./my_qdrant_db") # Remote server (REST) client = QdrantClient(host="localhost", port=6333) # or client = QdrantClient(url="http://localhost:6333") # Remote server (gRPC — faster for bulk uploads) client = QdrantClient(host="localhost", grpc_port=6334, prefer_grpc=True) # Qdrant Cloud with API key client = QdrantClient( url="https://xyz.us-east.aws.cloud.qdrant.io:6333", api_key="", ) # Qdrant Cloud with remote inference (paid plans) client = QdrantClient( url="https://xyz.us-east.aws.cloud.qdrant.io:6333", api_key="", cloud_inference=True, ) # Async client — identical API surface import asyncio async def main(): async_client = AsyncQdrantClient(url="http://localhost:6333") info = await async_client.info() print(info) asyncio.run(main()) # Access low-level clients when needed grpc_points = client.grpc_points # raw gRPC PointsStub grpc_collections = client.grpc_collections # raw gRPC CollectionsStub rest_api = client.http # generated REST ApiClient ``` -------------------------------- ### Client Initialization Source: https://context7.com/qdrant/qdrant-client/llms.txt Instantiate the synchronous or asynchronous Qdrant client for various connection modes including in-memory, persistent local storage, remote server (REST/gRPC), and Qdrant Cloud. ```APIDOC ## Client Initialization **`QdrantClient` / `AsyncQdrantClient` — instantiate the client** The entry point for all operations. Supports in-memory mode for local development, file-system persistence, remote server connection, and Qdrant Cloud with API key authentication. Accepts both REST and gRPC transports. ```python from qdrant_client import QdrantClient, AsyncQdrantClient, models # In-memory (local dev / CI — no server required) client = QdrantClient(":memory:") # Persistent local storage client = QdrantClient(path="./my_qdrant_db") # Remote server (REST) client = QdrantClient(host="localhost", port=6333) # or client = QdrantClient(url="http://localhost:6333") # Remote server (gRPC — faster for bulk uploads) client = QdrantClient(host="localhost", grpc_port=6334, prefer_grpc=True) # Qdrant Cloud with API key client = QdrantClient( url="https://xyz.us-east.aws.cloud.qdrant.io:6333", api_key="", ) # Qdrant Cloud with remote inference (paid plans) client = QdrantClient( url="https://xyz.us-east.aws.cloud.qdrant.io:6333", api_key="", cloud_inference=True, ) # Async client — identical API surface import asyncio async def main(): async_client = AsyncQdrantClient(url="http://localhost:6333") info = await async_client.info() print(info) asyncio.run(main()) # Access low-level clients when needed grpc_points = client.grpc_points # raw gRPC PointsStub grpc_collections = client.grpc_collections # raw gRPC CollectionsStub rest_api = client.http # generated REST ApiClient ``` ``` -------------------------------- ### Get Collection Aliases Source: https://context7.com/qdrant/qdrant-client/llms.txt Retrieves a list of aliases associated with a specific collection. ```python # List aliases for a collection aliases = client.get_collection_aliases("articles_v3") print([a.alias_name for a in aliases.aliases]) ``` -------------------------------- ### Initialize Qdrant Client for Cloud Inference Source: https://github.com/qdrant/qdrant-client/blob/master/README.md Instantiate the Qdrant client for remote inference on Qdrant Cloud. Requires URL and API key. Ensure you are on a paid plan for this feature. ```python from qdrant_client import QdrantClient client = QdrantClient( url="https://xxxxxx-xxxxx-xxxxx-xxxx-xxxxxxxxx.us-east.aws.cloud.qdrant.io:6333", api_key="", cloud_inference=True, # Enable remote inference ) ``` -------------------------------- ### Connect to Qdrant Server Source: https://github.com/qdrant/qdrant-client/blob/master/README.md Connect to a running Qdrant server by specifying the host and port, or a full URL. ```python from qdrant_client import QdrantClient client = QdrantClient(host="localhost", port=6333) ``` ```python from qdrant_client import QdrantClient client = QdrantClient(url="http://localhost:6333") ``` -------------------------------- ### Get Embedding Size Source: https://context7.com/qdrant/qdrant-client/llms.txt Retrieves the expected embedding vector size for a given model name. This is useful for correctly configuring collections before uploading data. ```python from qdrant_client import QdrantClient, models client = QdrantClient(":memory:") model_name = "sentence-transformers/all-MiniLM-L6-v2" size = client.get_embedding_size(model_name) # e.g. 384 ``` -------------------------------- ### Initialize QdrantClient in Local Mode Source: https://github.com/qdrant/qdrant-client/blob/master/README.md Initialize the Qdrant client for local mode, either in-memory or by specifying a persistent storage path. ```python from qdrant_client import QdrantClient client = QdrantClient(":memory:") ``` ```python from qdrant_client import QdrantClient client = QdrantClient(path="path/to/db") # Persists changes to disk ``` -------------------------------- ### Async Qdrant Client Operations Source: https://context7.com/qdrant/qdrant-client/llms.txt Demonstrates asynchronous operations including collection creation, upserting points, querying, scrolling, and batch querying using AsyncQdrantClient. Ensure an asyncio event loop is running. ```python import asyncio import numpy as np from qdrant_client import AsyncQdrantClient, models async def main(): client = AsyncQdrantClient(url="http://localhost:6333") await client.create_collection( collection_name="async_demo", vectors_config=models.VectorParams(size=10, distance=models.Distance.COSINE), ) await client.upsert( collection_name="async_demo", points=[ models.PointStruct(id=i, vector=np.random.rand(10).tolist(), payload={"i": i}) for i in range(200) ], ) result = await client.query_points( collection_name="async_demo", query=np.random.rand(10).tolist(), limit=5, query_filter=models.Filter( must=[models.FieldCondition(key="i", range=models.Range(gte=100))] ), ) for hit in result.points: print(hit.id, hit.score) # Scroll asynchronously records, offset = await client.scroll("async_demo", limit=50) # Batch query batch = await client.query_batch_points( "async_demo", requests=[ models.QueryRequest(query=np.random.rand(10).tolist(), limit=3), models.QueryRequest(query=np.random.rand(10).tolist(), limit=3), ], ) await client.close() asyncio.run(main()) ``` -------------------------------- ### Create Full Storage Snapshot Source: https://context7.com/qdrant/qdrant-client/llms.txt Creates a snapshot of the entire Qdrant storage. The `wait=True` parameter ensures the operation completes before returning. ```python # Full storage snapshot full_snap = client.create_full_snapshot(wait=True) ``` -------------------------------- ### upsert — insert or update points Source: https://context7.com/qdrant/qdrant-client/llms.txt Inserts or overwrites points identified by their IDs. Supports batch inserts, named vectors, sparse vectors, and automatic inference when FastEmbed is installed. ```APIDOC ## Point Operations ### `upsert` — insert or update points Inserts or overwrites points identified by their IDs. Supports batch inserts, named vectors, sparse vectors, and automatic inference when FastEmbed is installed. ```python import numpy as np from qdrant_client import QdrantClient, models client = QdrantClient(":memory:") client.create_collection( "articles", vectors_config=models.VectorParams(size=4, distance=models.Distance.COSINE), ) # Insert with dense vectors and payload result = client.upsert( collection_name="articles", points=[ models.PointStruct( id=1, vector=[0.1, 0.9, 0.3, 0.7], payload={"title": "Intro to Qdrant", "category": "tutorial", "year": 2024}, ), models.PointStruct( id=2, vector=[0.8, 0.2, 0.6, 0.1], payload={"title": "Vector Search Deep Dive", "category": "research", "year": 2023}, ), models.PointStruct( id="550e8400-e29b-41d4-a716-446655440000", # UUID string also valid vector=[0.5, 0.5, 0.5, 0.5], payload={"title": "Hybrid Search", "category": "tutorial", "year": 2024}, ), ], wait=True, ) print(result.status) # UpdateStatus.COMPLETED # Upsert with named vectors client.upsert( collection_name="hybrid_articles", points=[ models.PointStruct( id=10, vector={ "dense": [0.1, 0.9, 0.3, 0.7], "sparse": models.SparseVector( indices=[1, 45, 200], values=[0.3, 0.7, 0.5], ), }, payload={"text": "example document"}, ) ], ) ``` ``` -------------------------------- ### Facet for Aggregated Value Counts Source: https://context7.com/qdrant/qdrant-client/llms.txt Use the `facet` method to get aggregated counts for unique values of a payload field. This is useful for understanding data distribution within a collection, especially when combined with filters. ```python facet_result = client.facet( collection_name="articles", key="category", facet_filter=models.Filter( must=[models.FieldCondition(key="year", range=models.Range(gte=2023))] ), limit=20, exact=False, ) for hit in facet_result.hits: print(hit.value, hit.count) # tutorial 87 # research 43 # guide 29 ``` -------------------------------- ### Initialize Qdrant Client with gRPC Enabled Source: https://github.com/qdrant/qdrant-client/blob/master/README.md Initializes the Qdrant client to prefer gRPC for communication, typically resulting in faster collection uploading. Ensure gRPC port is correctly specified. ```python from qdrant_client import QdrantClient client = QdrantClient(host="localhost", grpc_port=6334, prefer_grpc=True) ``` -------------------------------- ### Create Qdrant Collection (Python) Source: https://context7.com/qdrant/qdrant-client/llms.txt Create a new vector collection with specified configurations for dense and sparse vectors, HNSW indexing, quantization, sharding, and replication. Supports single anonymous dense vectors or multiple named vectors for hybrid search. ```python from qdrant_client import QdrantClient, models client = QdrantClient(":memory:") # Single anonymous dense vector client.create_collection( collection_name="articles", vectors_config=models.VectorParams(size=384, distance=models.Distance.COSINE), ) # Multiple named vectors (dense + sparse for hybrid search) client.create_collection( collection_name="hybrid_articles", vectors_config={ "dense": models.VectorParams(size=384, distance=models.Distance.COSINE), "colbert": models.VectorParams( size=128, distance=models.Distance.COSINE, multivector_config=models.MultiVectorConfig( comparator=models.MultiVectorComparator.MAX_SIM ), ), }, sparse_vectors_config={ "sparse": models.SparseVectorParams(), }, hnsw_config=models.HnswConfigDiff(m=16, ef_construct=100), optimizers_config=models.OptimizersConfigDiff(memmap_threshold=20000), quantization_config=models.ScalarQuantization( scalar=models.ScalarQuantizationConfig( type=models.ScalarType.INT8, always_ram=True, ) ), on_disk_payload=False, shard_number=2, replication_factor=1, ) # Returns: True ``` -------------------------------- ### Configure Document for GPU Computation Source: https://github.com/qdrant/qdrant-client/blob/master/README.md Extend document creation to specify GPU computation using the 'options' parameter. ```python models.Document(text="To be computed on GPU", model=model_name, options={"cuda": True}) ``` -------------------------------- ### Connect to Qdrant Cloud Source: https://github.com/qdrant/qdrant-client/blob/master/README.md Connect to your Qdrant Cloud instance using the provided URL and API key. ```python from qdrant_client import QdrantClient qdrant_client = QdrantClient( url="https://xxxxxx-xxxxx-xxxxx-xxxx-xxxxxxxxx.us-east.aws.cloud.qdrant.io:6333", api_key="", ) ``` -------------------------------- ### Create Collection and Upload Data Source: https://github.com/qdrant/qdrant-client/blob/master/README.md Demonstrates creating a collection with specified vector parameters and uploading documents with associated payloads and IDs. ```python model_name = "sentence-transformers/all-MiniLM-L6-v2" payload = [ {"document": "Qdrant has Langchain integrations", "source": "Langchain-docs", }, {"document": "Qdrant also has Llama Index integrations", "source": "LlamaIndex-docs"}, ] docs = [models.Document(text=data["document"], model=model_name) for data in payload] olds = [42, 2] client.create_collection( "demo_collection", vectors_config=models.VectorParams( size=client.get_embedding_size(model_name), distance=models.Distance.COSINE) ) client.upload_collection( collection_name="demo_collection", vectors=docs, ids=ids, payload=payload, ) ``` -------------------------------- ### List Full Storage Snapshots Source: https://context7.com/qdrant/qdrant-client/llms.txt Lists all available full storage snapshots. ```python client.list_full_snapshots() ``` -------------------------------- ### Generate REST Client Code Source: https://github.com/qdrant/qdrant-client/blob/master/tools/DEVELOPMENT.md Execute the script to generate REST client code. This script fetches the OpenAPI specification from 'qdrant:dev' to create the necessary client files. ```bash bash -x tools/generate_rest_client.sh ``` -------------------------------- ### Run Integration Tests Source: https://github.com/qdrant/qdrant-client/blob/master/tools/DEVELOPMENT.md Execute the integration tests to ensure the client is functioning correctly. Refer to the provided script for detailed testing procedures. ```bash tests/integration-tests.sh ``` -------------------------------- ### Generate gRPC Client Code Source: https://github.com/qdrant/qdrant-client/blob/master/tools/DEVELOPMENT.md Run the script to generate gRPC client code. It retrieves the proto definitions from 'qdrant:dev' to produce the gRPC client artifacts. ```bash bash -x tools/generate_grpc_client.sh ``` -------------------------------- ### List Available Text, Sparse, and Image Models Source: https://context7.com/qdrant/qdrant-client/llms.txt Shows how to retrieve lists of available text, sparse, and image embedding models supported by the Qdrant client. The output is limited to the first 5 text models. ```python text_models = QdrantClient.list_text_models() sparse_models = QdrantClient.list_sparse_models() image_models = QdrantClient.list_image_models() print(list(text_models.keys())[:5]) ``` -------------------------------- ### AsyncQdrantClient Operations Source: https://context7.com/qdrant/qdrant-client/llms.txt Demonstrates the usage of AsyncQdrantClient for asynchronous operations including collection creation, upserting points, querying, scrolling, and batch querying. ```APIDOC ## AsyncQdrantClient ### Description Provides asynchronous versions of all methods available on `QdrantClient`. The initialization signature is identical. ### Usage Example ```python import asyncio import numpy as np from qdrant_client import AsyncQdrantClient, models async def main(): client = AsyncQdrantClient(url="http://localhost:6333") # Create a collection asynchronously await client.create_collection( collection_name="async_demo", vectors_config=models.VectorParams(size=10, distance=models.Distance.COSINE), ) # Upsert points asynchronously await client.upsert( collection_name="async_demo", points=[ models.PointStruct(id=i, vector=np.random.rand(10).tolist(), payload={"i": i}) for i in range(200) ], ) # Query points asynchronously result = await client.query_points( collection_name="async_demo", query=np.random.rand(10).tolist(), limit=5, query_filter=models.Filter( must=[ models.FieldCondition(key="i", range=models.Range(gte=100)) ] ), ) for hit in result.points: print(hit.id, hit.score) # Scroll asynchronously records, offset = await client.scroll("async_demo", limit=50) # Batch query asynchronously batch = await client.query_batch_points( "async_demo", requests=[ models.QueryRequest(query=np.random.rand(10).tolist(), limit=3), models.QueryRequest(query=np.random.rand(10).tolist(), limit=3), ], ) await client.close() asyncio.run(main()) ``` ``` -------------------------------- ### Create a New Qdrant Collection Source: https://github.com/qdrant/qdrant-client/blob/master/README.md Creates a new collection named 'my_collection' with specified vector size and distance metric. ```python from qdrant_client.models import Distance, VectorParams client.create_collection( collection_name="my_collection", vectors_config=VectorParams(size=100, distance=Distance.COSINE), ) ``` -------------------------------- ### Upserting and Querying Documents Source: https://context7.com/qdrant/qdrant-client/llms.txt Demonstrates how to upload documents with automatic embedding computation and perform queries using text. ```APIDOC ## Upsert using Document — embedding is computed automatically This operation allows you to upload documents to a collection where embeddings are generated automatically by the specified model. ### Method `client.upload_collection` ### Parameters - `collection_name` (string) - The name of the collection to upload to. - `vectors` (list[models.Document]) - A list of Document objects, each containing text and the model name for embedding. - `payload` (list[dict]) - A list of dictionaries, where each dictionary is the payload for a document. - `ids` (list[int]) - A list of unique identifiers for the documents. ### Request Example ```python payload = [ {"text": "Qdrant is a vector database", "source": "docs"}, {"text": "FastEmbed runs locally via ONNX", "source": "readme"}, ] docs = [models.Document(text=p["text"], model=model_name) for p in payload] client.upload_collection( collection_name="docs", vectors=docs, payload=payload, ids=[1, 2], ) ``` ## Query with automatic text embedding This operation allows you to query for points in a collection using a text query, where the embedding is computed automatically. ### Method `client.query_points` ### Parameters - `collection_name` (string) - The name of the collection to query. - `query` (models.Document) - A Document object containing the text to embed and the model name. - `limit` (int) - The maximum number of results to return. ### Request Example ```python result = client.query_points( collection_name="docs", query=models.Document(text="how to run inference locally", model=model_name), limit=3, ) for hit in result.points: print(hit.id, hit.score, hit.payload) ``` ``` -------------------------------- ### Populate Inspection Cache Source: https://github.com/qdrant/qdrant-client/blob/master/tools/DEVELOPMENT.md Use this script to populate the inspection cache. This is a necessary step in the client update process. ```bash bash -x tools/populate_inspection_cache.sh ``` -------------------------------- ### Create Collection Snapshot Source: https://context7.com/qdrant/qdrant-client/llms.txt Creates a snapshot of a specified collection. The `wait=True` parameter ensures the operation completes before returning. ```python # Create a collection snapshot snap = client.create_snapshot(collection_name="articles", wait=True) print(snap.name) # e.g. articles-1234567890-2024-01-15-12-00-00.snapshot print(snap.creation_time) ``` -------------------------------- ### List All Collections Source: https://context7.com/qdrant/qdrant-client/llms.txt Iterate through all available collections and print their names. ```python # List all collections resp = client.get_collections() for col in resp.collections: print(col.name) ``` -------------------------------- ### Service Information Source: https://context7.com/qdrant/qdrant-client/llms.txt Retrieve server version and optimization status for collections. ```APIDOC ## Service Information ### `info` / `get_optimizations` — server and optimization status #### `info` ##### Description Retrieves the server version and title. ##### Usage Example ```python # Server version and commit version_info = client.info() print(version_info.version) # e.g. "1.12.0" print(version_info.title) # "qdrant - vector search engine" ``` #### `get_optimizations` ##### Description Monitors ongoing and completed optimization tasks for a specified collection. ##### Parameters - **collection_name** (str) - Required - The name of the collection to check optimizations for. - **completed_limit** (int) - Optional - How many completed optimization tasks to include in the response. ##### Usage Example ```python # Monitor ongoing/completed optimization tasks for a collection opts = client.get_optimizations( collection_name="articles", completed_limit=10, # how many completed ops to include in response ) for opt in opts.optimizations: print(opt.status, opt.optimizations_report) ``` ``` -------------------------------- ### Upsert Documents and Query with Automatic Embedding Source: https://context7.com/qdrant/qdrant-client/llms.txt Demonstrates how to upload documents with automatic embedding computation and then query the collection using text. Ensure the model_name is correctly set. ```python payload = [ {"text": "Qdrant is a vector database", "source": "docs"}, {"text": "FastEmbed runs locally via ONNX", "source": "readme"}, ] docs = [models.Document(text=p["text"], model=model_name) for p in payload] client.upload_collection( collection_name="docs", vectors=docs, payload=payload, ids=[1, 2], ) result = client.query_points( collection_name="docs", query=models.Document(text="how to run inference locally", model=model_name), limit=3, ) for hit in result.points: print(hit.id, hit.score, hit.payload) ``` -------------------------------- ### List Collection Snapshots Source: https://context7.com/qdrant/qdrant-client/llms.txt Lists all available snapshots for a specified collection. ```python # List available snapshots snapshots = client.list_snapshots(collection_name="articles") for s in snapshots: print(s.name, s.size) ``` -------------------------------- ### Migrate All Collections Source: https://context7.com/qdrant/qdrant-client/llms.txt Migrates all collections from a source Qdrant client to a destination client. `recreate_on_collision=True` will overwrite existing collections on the destination. ```python from qdrant_client import QdrantClient source = QdrantClient(url="http://old-server:6333") dest = QdrantClient(url="http://new-server:6333", api_key="new-key") # Migrate all collections source.migrate( dest_client=dest, batch_size=200, recreate_on_collision=True, # overwrite if collection already exists on dest ) ``` -------------------------------- ### Hybrid Search Fusion with Reciprocal Rank Fusion Source: https://context7.com/qdrant/qdrant-client/llms.txt Demonstrates client-side fusion of search results from dense and sparse vectors using Reciprocal Rank Fusion (RRF). Requires importing fusion utilities and running separate searches first. ```python from qdrant_client.hybrid.fusion import reciprocal_rank_fusion, distribution_based_score_fusion from qdrant_client import QdrantClient, models client = QdrantClient(":memory:") dense_hits = client.query_points("articles", query=[0.1, 0.9, 0.3, 0.7], limit=20, using="dense").points sparse_hits = client.query_points( "articles", query=models.SparseVector(indices=[1, 45, 200], values=[0.3, 0.7, 0.5]), limit=20, using="sparse", ).points fused = reciprocal_rank_fusion( responses=[dense_hits, sparse_hits], limit=10, ranking_constant_k=2, weights=[0.7, 0.3], # weight dense results higher ) for point in fused: print(point.id, point.score) ``` -------------------------------- ### Create Custom Shard Key Source: https://context7.com/qdrant/qdrant-client/llms.txt Creates a custom shard key for a collection, specifying the number of shards and replication factor. This allows for more granular control over data distribution. ```python client.create_shard_key( collection_name="articles", shard_key="region_us", shards_number=2, replication_factor=1, ) ``` -------------------------------- ### GPU Inference Options Source: https://context7.com/qdrant/qdrant-client/llms.txt Illustrates how to specify GPU acceleration for embedding computation when creating a document. Requires the 'fastembed-gpu' package. ```python gpu_doc = models.Document( text="accelerated embedding", model=model_name, options={"cuda": True}, ) ``` -------------------------------- ### Snapshots Source: https://context7.com/qdrant/qdrant-client/llms.txt Manage collection and full storage snapshots for backup and recovery purposes. ```APIDOC ## Snapshots ### `create_snapshot` Creates a snapshot for a specific collection. #### Parameters - **collection_name** (str) - The name of the collection. - **wait** (bool, optional) - Whether to wait for the snapshot creation to complete. ### `list_snapshots` Lists available snapshots for a specific collection. #### Parameters - **collection_name** (str) - The name of the collection. ### `recover_snapshot` Recovers a collection from a snapshot located at a given URL. #### Parameters - **collection_name** (str) - The name of the collection to recover. - **location** (str) - The URL or path to the snapshot. - **priority** (models.SnapshotPriority, optional) - Priority for the recovery process. - **wait** (bool, optional) - Whether to wait for the recovery to complete. ### `create_full_snapshot` Creates a snapshot of the entire Qdrant storage. #### Parameters - **wait** (bool, optional) - Whether to wait for the snapshot creation to complete. ### `list_full_snapshots` Lists all available full storage snapshots. ### `delete_full_snapshot` Deletes a specified full storage snapshot. #### Parameters - **snapshot_name** (str) - The name of the snapshot to delete. ### `create_shard_snapshot` Creates a snapshot for a specific shard within a collection. #### Parameters - **collection_name** (str) - The name of the collection. - **shard_id** (int) - The ID of the shard. ### `list_shard_snapshots` Lists available snapshots for a specific shard within a collection. #### Parameters - **collection_name** (str) - The name of the collection. - **shard_id** (int) - The ID of the shard. ### `recover_shard_snapshot` Recovers a specific shard within a collection from a snapshot. #### Parameters - **collection_name** (str) - The name of the collection. - **shard_id** (int) - The ID of the shard. - **location** (str) - The URL or path to the snapshot. ``` -------------------------------- ### Listing Available Models Source: https://context7.com/qdrant/qdrant-client/llms.txt Retrieves lists of available text, sparse, and image embedding models supported by the client. ```APIDOC ## List available models This operation allows you to list the available text, sparse, and image embedding models. ### Method `QdrantClient.list_text_models()` `QdrantClient.list_sparse_models()` `QdrantClient.list_image_models()` ### Response Example ```python text_models = QdrantClient.list_text_models() sparse_models = QdrantClient.list_sparse_models() image_models = QdrantClient.list_image_models() print(list(text_models.keys())[:5]) # ['BAAI/bge-small-en', 'BAAI/bge-small-en-v1.5', 'sentence-transformers/all-MiniLM-L6-v2', ...] ``` ``` -------------------------------- ### Create Shard Snapshot Source: https://context7.com/qdrant/qdrant-client/llms.txt Creates a snapshot for a specific shard within a collection. ```python # Shard-level snapshots shard_snap = client.create_shard_snapshot(collection_name="articles", shard_id=0) ``` -------------------------------- ### Create Collection Source: https://context7.com/qdrant/qdrant-client/llms.txt Creates a new vector collection with specified configurations for dense vectors, sparse vectors, HNSW indexing, quantization, sharding, and replication. ```APIDOC ## Collection Management ### `create_collection` — create a new vector collection Creates an empty collection with specified vector configuration. Supports dense vectors, sparse vectors (for hybrid search), HNSW index tuning, quantization, sharding, and replication. ```python from qdrant_client import QdrantClient, models client = QdrantClient(":memory:") # Single anonymous dense vector client.create_collection( collection_name="articles", vectors_config=models.VectorParams(size=384, distance=models.Distance.COSINE), ) # Multiple named vectors (dense + sparse for hybrid search) client.create_collection( collection_name="hybrid_articles", vectors_config={ "dense": models.VectorParams(size=384, distance=models.Distance.COSINE), "colbert": models.VectorParams( size=128, distance=models.Distance.COSINE, multivector_config=models.MultiVectorConfig( comparator=models.MultiVectorComparator.MAX_SIM ), ), }, sparse_vectors_config={ "sparse": models.SparseVectorParams(), }, hnsw_config=models.HnswConfigDiff(m=16, ef_construct=100), optimizers_config=models.OptimizersConfigDiff(memmap_threshold=20000), quantization_config=models.ScalarQuantization( scalar=models.ScalarQuantizationConfig( type=models.ScalarType.INT8, always_ram=True, ) ), on_disk_payload=False, shard_number=2, replication_factor=1, ) # Returns: True ``` ``` -------------------------------- ### upload_collection — bulk upload with automatic batching Source: https://context7.com/qdrant/qdrant-client/llms.txt Optimized method for initial data loading. Accepts numpy arrays or iterables, handles batching and parallelism automatically. ```APIDOC ### `upload_collection` — bulk upload with automatic batching Optimized method for initial data loading. Accepts numpy arrays or iterables, handles batching and parallelism automatically. ```python import numpy as np from qdrant_client import QdrantClient, models client = QdrantClient(url="http://localhost:6333") client.create_collection( "embeddings", vectors_config=models.VectorParams(size=128, distance=models.Distance.EUCLIDEAN), ) # Upload from numpy array vectors = np.random.rand(10000, 128).astype(np.float32) payload = [{"item_id": i, "score": float(np.random.rand())} for i in range(10000)] client.upload_collection( collection_name="embeddings", vectors=vectors, payload=payload, ids=list(range(10000)), # optional custom IDs batch_size=256, parallel=4, max_retries=3, ) ``` ``` -------------------------------- ### Create or Check Collection Source: https://context7.com/qdrant/qdrant-client/llms.txt Check if a collection exists before creating it to avoid errors. Ensure the collection is configured with appropriate vector parameters. ```python if not client.collection_exists("articles"): client.create_collection( "articles", vectors_config=models.VectorParams(size=384, distance=models.Distance.COSINE), ) ``` -------------------------------- ### Hybrid Search Fusion with Distribution-Based Score Fusion Source: https://context7.com/qdrant/qdrant-client/llms.txt Shows how to fuse search results from dense and sparse vectors using the Distribution-Based Score Fusion (DBSF) method on the client side. This requires prior execution of separate dense and sparse searches. ```python fused_dbsf = distribution_based_score_fusion( responses=[dense_hits, sparse_hits], limit=10, ) ``` -------------------------------- ### List Shard Snapshots Source: https://context7.com/qdrant/qdrant-client/llms.txt Lists all available snapshots for a specific shard within a collection. ```python client.list_shard_snapshots(collection_name="articles", shard_id=0) ``` -------------------------------- ### List Custom Shard Keys Source: https://context7.com/qdrant/qdrant-client/llms.txt Retrieves a list of all custom shard keys defined for a given collection. ```python client.list_shard_keys("articles") ``` -------------------------------- ### Universal Query Endpoint for Search Source: https://context7.com/qdrant/qdrant-client/llms.txt The `query_points` method is a versatile endpoint for various search types including dense vector search, filtered search, recommend-by-example, multi-stage queries with prefetch and fusion, and auto-embedding text queries. ```python import numpy as np from qdrant_client import QdrantClient, models client = QdrantClient(":memory:") client.create_collection("articles", vectors_config=models.VectorParams(size=4, distance=models.Distance.COSINE)) # Dense vector nearest-neighbor search result = client.query_points( collection_name="articles", query=[0.1, 0.9, 0.3, 0.7], limit=5, with_payload=True, score_threshold=0.7, ) for hit in result.points: print(hit.id, hit.score, hit.payload) # Filtered search result = client.query_points( collection_name="articles", query=[0.1, 0.9, 0.3, 0.7], query_filter=models.Filter( must=[ models.FieldCondition(key="category", match=models.MatchValue(value="tutorial")), models.FieldCondition(key="year", range=models.Range(gte=2023)), ] ), limit=10, ) # Recommend-by-example using an existing point's ID result = client.query_points( collection_name="articles", query=models.RecommendQuery( recommend=models.RecommendInput( positive=[1, 2], # point IDs to use as positive examples negative=[3], ) ), limit=5, ) # Multi-stage query with prefetch and fusion reranking result = client.query_points( collection_name="hybrid_articles", prefetch=[ models.Prefetch(query=[0.1, 0.9, 0.3, 0.7], using="dense", limit=50), models.Prefetch( query=models.SparseVector(indices=[1, 45], values=[0.3, 0.7]), using="sparse", limit=50, ), ], query=models.FusionQuery(fusion=models.Fusion.RRF), # Reciprocal Rank Fusion limit=10, ) # Auto-embed query text using FastEmbed (requires qdrant-client[fastembed]) result = client.query_points( collection_name="articles", query=models.Document( text="vector similarity search tutorial", model="sentence-transformers/all-MiniLM-L6-v2", ), limit=5, ) ``` -------------------------------- ### Update Qdrant Collection Parameters (Python) Source: https://context7.com/qdrant/qdrant-client/llms.txt Modify optimizer, HNSW, quantization, or sparse-vector configurations on an existing Qdrant collection without data loss. Use `strict_mode_config` to enforce query limits. ```python client.update_collection( collection_name="articles", optimizers_config=models.OptimizersConfigDiff(indexing_threshold=10000), hnsw_config=models.HnswConfigDiff(ef_construct=200), strict_mode_config=models.StrictModeConfig(enabled=True, max_query_limit=1000), ) # Returns: True ``` -------------------------------- ### Collection Migration Source: https://context7.com/qdrant/qdrant-client/llms.txt Migrate data between Qdrant instances for upgrades, moves, or cross-cloud transfers. ```APIDOC ## Collection Migration ### `migrate` Copies one or all collections from a source Qdrant client to a destination client. #### Parameters - **dest_client** (QdrantClient) - The destination Qdrant client instance. - **collection_names** (list[str], optional) - A list of specific collection names to migrate. If not provided, all collections are migrated. - **batch_size** (int, optional) - The number of records to process in each batch during migration. - **recreate_on_collision** (bool, optional) - If True, existing collections on the destination will be recreated. If False, a ValueError is raised on collision. ``` -------------------------------- ### Collection Aliases Source: https://context7.com/qdrant/qdrant-client/llms.txt Manage collection aliases atomically for zero-downtime index swaps and alias management. ```APIDOC ## Collection Aliases ### `update_collection_aliases` Performs atomic operations to create, delete, or rename collection aliases. #### Parameters - **change_aliases_operations** (list[models.AliasOperations]) - A list of alias operations to perform. ### `get_collection_aliases` Retrieves all aliases associated with a specific collection. #### Parameters - **collection_name** (str) - The name of the collection. ### `get_aliases` Retrieves all aliases across all collections in the Qdrant instance. ``` -------------------------------- ### Collection Utilities Source: https://context7.com/qdrant/qdrant-client/llms.txt Provides utility functions to check for collection existence, retrieve collection information, list all collections, and delete collections. ```APIDOC ### `collection_exists` / `get_collection` / `get_collections` / `delete_collection` Utilities to inspect and manage the collection registry. ```python ``` -------------------------------- ### FastEmbed Inference Integration Source: https://context7.com/qdrant/qdrant-client/llms.txt Integrate text and image embedding using fastembed models directly within Qdrant. ```APIDOC ## FastEmbed Inference Integration ### `get_embedding_size` Retrieves the embedding vector size for a given fastembed model name. #### Parameters - **model_name** (str) - The name of the fastembed model (e.g., 'sentence-transformers/all-MiniLM-L6-v2'). ### `QdrantFastembedMixin` When `qdrant-client[fastembed]` is installed, this mixin provides helpers for automatic embedding of `models.Document` and `models.Image` objects during upload or query operations. ``` -------------------------------- ### Perform a Vector Search Source: https://github.com/qdrant/qdrant-client/blob/master/README.md Executes a search query against a collection using a document and prints the results. ```python search_result = client.query_points( collection_name="demo_collection", query=models.Document(text="This is a query document", model=model_name) ).points print(search_result) ``` -------------------------------- ### Move Collection Shard Replica Source: https://context7.com/qdrant/qdrant-client/llms.txt Initiates an operation to move a specific shard replica of a collection from one peer to another. Requires specifying the collection name, shard ID, and source/destination peer IDs. ```python client.cluster_collection_update( collection_name="articles", cluster_operation=models.MoveShardOperation( move_shard=models.MoveShard( shard_id=0, to_peer_id=2, from_peer_id=1, ) ), ) ```