Sort clauses for collections (C#)

Many Data API commands use sort clauses to sort documents by field values, or to perform vector search or hybrid search.

You must use & to escape any . or & in field names in a sort clause. Dot notation, which is used to reference nested fields, should not be escaped. For more information, see Work with . and & in field names (C#).

Sort by field values

Use a sort clause to sort documents by field values in ascending or descending order.

When sorting by multiple fields, the order of the fields in the sort clause controls the order of the sorting.

Sort clauses can use only indexed fields. If you apply selective indexing when you create a collection, you cannot reference non-indexed fields in sort queries.

You can’t sort the $lexical field in ascending or descending order. Instead, you must sort by lexicographical match.

The following example uses untyped documents, but you can use strongly-typed classes for compile-time checks and IntelliSense. For more information and examples, see Custom typing for collections.

using System.Text.Json;
using DataStax.AstraDB.DataApi;
using DataStax.AstraDB.DataApi.Collections;
using DataStax.AstraDB.DataApi.Core;
using DataStax.AstraDB.DataApi.Core.Query;

namespace Examples;

public class Program
{
  static async Task Main()
  {
    // Get an existing collection
    var client = new DataAPIClient();
    var database = client.GetDatabase(
      "API_ENDPOINT",
      "APPLICATION_TOKEN"
    );
    var collection = database.GetCollection("COLLECTION_NAME");

    // Find documents
    var filterBuilder = Builders<Document>.CollectionFilter;
    var filter = filterBuilder.Eq("metadata.language", "English");
    var sort = Builders<Document>
      .CollectionSort.Ascending("rating")
      .Descending("title");
    var result = collection.Find(
      filter,
      new CollectionFindOptions<Document>() { Sort = sort }
    );

    await foreach (var document in result)
    {
      Console.WriteLine(JsonSerializer.Serialize(document));
    }
  }
}

To find the documents whose $vector value is most similar to a given vector, use a sort clause with the vector embeddings that you want to match. To find the documents whose $vector value is most similar to the $vector value generated from a given search string, use a sort with the search string that you want to vectorize and match. For more information, see Find data with vector search.

Vector search is only available for vector-enabled collections. For more information, see Create a collection that can store vector embeddings and $vector in collections (C#).

Vector search with vectorize is only available for collections that have vectorize enabled. For more information, see Create a collection that can automatically generate vector embeddings and $vectorize in collections (C#).

Example sorting against a search vector

The following example uses untyped documents, but you can use strongly-typed classes for compile-time checks and IntelliSense. For more information and examples, see Custom typing for collections.

using System.Text.Json;
using DataStax.AstraDB.DataApi;
using DataStax.AstraDB.DataApi.Collections;
using DataStax.AstraDB.DataApi.Core;
using DataStax.AstraDB.DataApi.Core.Query;

namespace Examples;

public class Program
{
  static async Task Main()
  {
    // Get an existing collection
    var client = new DataAPIClient();
    var database = client.GetDatabase(
      "API_ENDPOINT",
      "APPLICATION_TOKEN"
    );
    var collection = database.GetCollection("COLLECTION_NAME");

    // Find documents
    var embeddings = new float[] { 0.08f, -0.62f, 0.39f };
    var result = collection.Find(
      new CollectionFindOptions<Document>()
      {
        Sort = Builders<Document>.CollectionSort.Vector(embeddings),
      }
    );

    await foreach (var document in result)
    {
      Console.WriteLine(JsonSerializer.Serialize(document));
    }
  }
}

Example sorting against a search string

The following example uses untyped documents, but you can use strongly-typed classes for compile-time checks and IntelliSense. For more information and examples, see Custom typing for collections.

using System.Text.Json;
using DataStax.AstraDB.DataApi;
using DataStax.AstraDB.DataApi.Collections;
using DataStax.AstraDB.DataApi.Core;
using DataStax.AstraDB.DataApi.Core.Query;

namespace Examples;

public class Program
{
  static async Task Main()
  {
    // Get an existing collection
    var client = new DataAPIClient();
    var database = client.GetDatabase(
      "API_ENDPOINT",
      "APPLICATION_TOKEN"
    );
    var collection = database.GetCollection("COLLECTION_NAME");

    // Find documents
    var result = collection.Find(
      new CollectionFindOptions<Document>()
      {
        Sort = Builders<Document>.CollectionSort.Vectorize(
          "Text to vectorize"
        ),
      }
    );

    await foreach (var document in result)
    {
      Console.WriteLine(JsonSerializer.Serialize(document));
    }
  }
}

Sort by lexicographical matching (BM25-based ranking)

Sort on the $lexical field to the documents whose $lexical field value is most relevant to a given string of space-separated keywords or terms.

This is only available for collections with lexical enabled. For more information, see Create a collection that supports lexicographical matching.

When sorting on the $lexical field, you can’t include additional sort clauses.

The following example uses untyped documents, but you can use strongly-typed classes for compile-time checks and IntelliSense. For more information and examples, see Custom typing for collections.

using System.Text.Json;
using DataStax.AstraDB.DataApi;
using DataStax.AstraDB.DataApi.Collections;
using DataStax.AstraDB.DataApi.Core;
using DataStax.AstraDB.DataApi.Core.Query;

namespace Examples;

public class Program
{
  static async Task Main()
  {
    // Get an existing collection
    var client = new DataAPIClient();
    var database = client.GetDatabase(
      "API_ENDPOINT",
      "APPLICATION_TOKEN"
    );
    var collection = database.GetCollection("COLLECTION_NAME");

    // Find a document
    var result = collection.Find(
      new CollectionFindOptions<Document>()
      {
        Sort = Builders<Document>.CollectionSort.Lexical(
          "tree hill grassy"
        ),
      }
    );

    await foreach (var document in result)
    {
      Console.WriteLine(JsonSerializer.Serialize(document));
    }
  }
}

A hybrid search uses a reranker model to combine results from a vector search and a lexical search. When you find documents via hybrid search, you use a sort clause to specify the queries for the underlying vector search and hybrid search.

using System.Text.Json;
using DataStax.AstraDB.DataApi;
using DataStax.AstraDB.DataApi.Collections;
using DataStax.AstraDB.DataApi.Core;
using DataStax.AstraDB.DataApi.Core.Query;

namespace Examples;

public class Program
{
  static async Task Main()
  {
    // Get an existing collection
    var client = new DataAPIClient();
    var database = client.GetDatabase(
      "API_ENDPOINT",
      "APPLICATION_TOKEN"
    );
    var collection = database.GetCollection("COLLECTION_NAME");

    // Find documents
    var result = collection.FindAndRerank(
      new CollectionFindAndRerankOptions<Document>
      {
        Sort = Builders<Document>.CollectionFindAndRerankSort.Hybrid(
          "A tree in the woods",
          "house hill grassy"
        ),
      }
    );

    await foreach (var document in result)
    {
      Console.WriteLine(JsonSerializer.Serialize(document.Document));
    }
  }
}

Was this helpful?

Give Feedback

How can we improve the documentation?

© Copyright IBM Corporation 2026 | Privacy policy | Terms of use Manage Privacy Choices

Apache, Apache Cassandra, Cassandra, Apache Tomcat, Tomcat, Apache Lucene, Apache Solr, Apache Hadoop, Hadoop, Apache Pulsar, Pulsar, Apache Spark, Spark, Apache TinkerPop, TinkerPop, Apache Kafka and Kafka are either registered trademarks or trademarks of the Apache Software Foundation or its subsidiaries in Canada, the United States and/or other countries. Kubernetes is the registered trademark of the Linux Foundation.

General Inquiries: Contact IBM