qdrant-client Rust Documentation

repository·master·Indexed 19 days ago

https://github.com/qdrant/rust-client

A high-performance Rust client for Qdrant Vector Search Engine (v1.19.0). It enables developers to manage collections, upsert vectors with payloads, and perform complex similarity searches via gRPC. The library includes builders for HNSW index configuration, ACORN search parameters, Maximal Marginal Relevance (MMR), optimizer settings, and Reciprocal Rank Fusion (RRF), as well as tools for replicating points between shards.

Tokens
23.2K
Snippets
66
Records
113
Agent score
63%

What's inside qdrant-client

  1. Configure Qdrant gRPC interface

    master

    The client communicates via gRPC. Ensure your Qdrant server has the gRPC interface enabled. You can enable it using a Docker environment variable or by updating the configuration file.

    Using Docker environment variable:

    docker run -p 6333:6333 -p 6334:6334 \
        -e QDRANT__SERVICE__GRPC_PORT="6334" \
        qdrant/qdrant

    Using configuration file:

    service:
      grpc_port: 6334
  2. Connect to Qdrant Cloud

    master

    When using the managed Qdrant Cloud service, ensure you use the correct gRPC port (typically 6334) and provide your API KEY during client construction.

    use qdrant_client::Qdrant;
    
    let client = Qdrant::from_url("http://xxxxxxxxxx.eu-central.aws.cloud.qdrant.io:6334")
        .api_key(std::env::var("QDRANT_API_KEY"))
        .build()?;
    use qdrant_client::Qdrant;
    
    let client = Qdrant::from_url("http://xxxxxxxxxx.eu-central.aws.cloud.qdrant.io:6334")
        // Use an environment variable for the API KEY for example
        .api_key(std::env::var("QDRANT_API_KEY"))
        .build()?;
  3. Make requests to Qdrant

    master

    To use the client, you need to add qdrant-client along with anyhow, tonic, tokio, and serde-json. Ensure tokio is configured with the rt-multi-thread feature.

    Required dependencies:

    cargo add qdrant-client anyhow tonic tokio serde-json --features tokio/rt-multi-thread

    Basic Workflow Example:

    1. Initialize the client using Qdrant::from_url("...").build()?.
    2. Create collections using CreateCollectionBuilder.
    3. Upsert points using UpsertPointsBuilder and PointStruct.
    4. Query points using QueryPointsBuilder with filters and search parameters.

    Note: You can also use the tonic-generated client from src/qdrant.rs directly.

    use qdrant_client::qdrant::{
        Condition, CreateCollectionBuilder, Distance, Filter, PointStruct, QueryPointsBuilder,
        ScalarQuantizationBuilder, SearchParamsBuilder, UpsertPointsBuilder, VectorParamsBuilder,
    };
    use qdrant_client::{Payload, Qdrant, QdrantError};
    
    #[tokio::main]
    async fn main() -> Result<(), QdrantError> {
        // Initialize client
        let client = Qdrant::from_url("http://localhost:6334").build()?;
    
        let collection_name = "test";
    
        // Create a collection
        client
            .create_collection(
                CreateCollectionBuilder::new(collection_name)
                    .vectors_config(VectorParamsBuilder::new(10, Distance::Cosine))
                    .quantization_config(ScalarQuantizationBuilder::default()),
            )
            .await?;
    
        // Prepare payload and points
        let payload: Payload = serde_json::json!(
            {
                "foo": "Bar",
                "bar": 12,
                "baz": {
                    "qux": "quux"
                }
            }
        )
        .try_into()
        .unwrap();
    
        let points = vec![PointStruct::new(0, vec![12.; 10], payload)];
    
        // Upsert points
        client
            .upsert_points(UpsertPointsBuilder::new(collection_name, points))
            .await?;
    
        // Query points
        let query_result = client
            .query(
                QueryPointsBuilder::new(collection_name)
                    .query(vec![11.0; 10])
                    .limit(10)
                    .filter(Filter::all([Condition::matches("bar", 12)]))
                    .with_payload(true)
                    .params(SearchParamsBuilder::default().exact(true)),
            )
            .await?;
    
        Ok(())
    }
  4. Configure Read Consistency with ReadConsistencyType

    master

    You can control how many nodes must agree before a read is considered successful using ReadConsistencyType:

    • All (0): Request is sent to all nodes; points must be present on all of them.
    • Majority (1): Request is sent to all nodes; points must be present on a majority of them.
    • Quorum (2): Request is sent to half + 1 nodes; points must be present on all of them.
  5. Construct filters using the Filter and Condition types

    master

    Filters allow you to restrict search results based on payload criteria.

    Filter Structure

    A Filter consists of logical combinations of Condition objects:

    • should: At least one condition must match.
    • must: All conditions must match.
    • must_not: All conditions must NOT match.
    • min_should: A MinShould object specifying a minimum number of conditions that must match.

    Condition Types

    A Condition is a single requirement, which can be one of:

    • Field: A FieldCondition targeting a specific payload key.
    • IsEmpty: Checks if a key exists and is empty.
    • HasId: Checks if the point ID is within a provided list of PointIds.
    • Filter: A nested Filter for complex logic.
    • IsNull: Checks if a key is null.
    • Nested: A NestedCondition that applies a Filter to a nested object at a specific key path.
    • HasVector: Checks if a specific named vector exists.
    • Slice: A SliceCondition for deterministic ID space partitioning.
  6. Configure vector creation for Dense and Sparse vectors

    master

    When creating new vectors in a collection, you must specify the appropriate configuration:

    DenseVectorCreationConfig

    Used for dense vectors. Defines the immutable properties of the vector space:

    • size: The dimensionality of the vectors.
    • distance: The distance function used for comparison (e.g., Cosine, Euclidean).
    • multivector_config: Optional configuration for multi-vector search (e.g., ColBERT).
    • datatype: The data type of the vectors (e.g., Float32, Float16, Uint8, Turbo4).

    SparseVectorCreationConfig

    Used for sparse vectors:

    • modifier: Optional modifier to apply to vector values (e.g., IDF).
    • datatype: The data type used to store weights in the index.
  7. Apply Maximal Marginal Relevance (MMR) for diversity

    master

    The Mmr struct enables re-ranking search results using the Maximal Marginal Relevance algorithm to balance relevance and diversity.

    • diversity: A float in the range [0, 1]. A higher value favors diversity (dissimilarity to selected results), while a lower value favors relevance (similarity to the query vector). Default is 0.5.
    • candidates_limit: The maximum number of candidates to consider for re-ranking. If not specified, the query's limit is used.
  8. Use RecommendStrategy for recommendation queries

    master

    When performing recommendation searches, you can choose how to combine positive and negative vectors using RecommendStrategy:

    • AverageVector (0): Averages positive and negative vectors to create a single query: query = avg_pos + avg_pos - avg_neg.
    • BestScore (1): Compares candidates against all examples and chooses the score based on max(max_pos_score, max_neg_score). If max_neg_score is chosen, it is squared and negated.
    • SumScores (2): Sums all scores, adding scores from positive vectors and subtracting scores from negative vectors.
  9. Manage Write Consistency with WriteOrderingType

    master

    When performing batch updates, you can specify the WriteOrderingType to balance performance and consistency:

    • Weak (0): Default. Write operations may be reordered for higher performance.
    • Medium (1): Operations go through a dynamically selected leader. May be inconsistent during leader changes.
    • Strong (2): Operations go through the permanent leader. Provides high consistency but may be unavailable if the leader is down.
  10. Configure Read Consistency

    master

    When performing read operations, you can specify a ReadConsistency to control how many nodes must agree on the data before it is returned.

    ReadConsistency uses a oneof structure:

    • Type(ReadConsistencyType): Uses a predefined consistency level (e.g., via an enum).
    • Factor(u64): Specifies a exact number of nodes that must contain the points to ensure they are returned.
    // Example conceptual usage of ReadConsistency
    let consistency = ReadConsistency {
        value: Some(read_consistency::Value::Factor(3)), // Require 3 nodes
    };
  11. How the Qdrant client works

    master

    The client acts as a high-level wrapper around gRPC communication with a Qdrant server. It uses a builder pattern for most operations (creating collections, upserting points, querying) to provide a fluent API. The core interaction model follows:

    1. Connect: Establish a Qdrant client instance.
    2. Configure: Define collections with specific vector dimensions and distance metrics.
    3. Operate: Perform CRUD operations on points and manage payloads.
    4. Query: Execute similarity searches or filtered queries.