Skip to content

Conversation

kashifsoofi
Copy link
Contributor

@kashifsoofi kashifsoofi commented Aug 14, 2025

Pull Request

Related issue

Fixes #665

What does this PR do?

  • Add Sort to DocumentsQuery

PR checklist

Please check if your PR fulfills the following requirements:

  • Does this PR fix an existing issue, or have you listed the changes applied in the PR description (and why they are needed)?
  • Have you read the contributing guidelines?
  • Have you made sure that the title is accurate and descriptive of the changes?

Thank you so much for contributing to Meilisearch!

Summary by CodeRabbit

  • New Features

    • Added support for sorting document query results, including multi-field ordering and ID-based sorts; works with filters and limits.
  • Documentation

    • Added "Search with sort" guidance and a C# example showing how to specify sort options.
  • Tests

    • Added tests validating ascending/descending, multi-field sort with filters, and that sort parameters appear in query strings.
  • Chores

    • Bumped Meilisearch version used in CI from v1.10.0 to v1.16.

Copy link

coderabbitai bot commented Aug 14, 2025

Walkthrough

Adds support for specifying sort on document queries by introducing a Sort property on DocumentsQuery, updates README with a "Search with sort" example, adds tests covering id and multi-field sorting plus query-string serialization, and bumps MEILISEARCH_VERSION in .env.

Changes

Cohort / File(s) Summary
Documentation
README.md
Adds “Search with sort” section and C# example demonstrating multi-field sort (genre:asc, name:desc).
Query parameter model
src/Meilisearch/QueryParameters/DocumentsQuery.cs
Adds public List<string> Sort { get; set; } annotated with [JsonPropertyName("sort")] and XML doc "An optional sort to apply."
Document sorting tests
tests/Meilisearch.Tests/DocumentTests.cs
Adds two tests validating sorting for integer-id documents: id-based asc/desc test and a multi-field sort with genre filter.
Query string serialization tests
tests/Meilisearch.Tests/ObjectExtensionsTests.cs
Adds QueryStringsWithSortAreEqualForDocumentsQuery test and using System.Linq; to verify DocumentsQuery.ToQueryString includes sort.
Env/version
.env
Updates MEILISEARCH_VERSION from v1.10.0 to v1.16.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant Client
  participant SDK
  participant Meilisearch
  rect rgb(220, 240, 255)
    Note left of Client: Build DocumentsQuery\nwith Sort (e.g. ["genre:asc","name:desc"])
  end
  Client->>SDK: Call Documents API (Search/Query) with DocumentsQuery
  SDK->>Meilisearch: HTTP request with JSON body/query including "sort"
  Meilisearch-->>SDK: Sorted results response
  SDK-->>Client: Return typed results
  note right of SDK #e8f5e9: New DocumentsQuery.Sort\nis serialized into request
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Assessment against linked issues

Objective Addressed Explanation
Update documents methods to accept the sort parameter (#665)
Add new test case (#665)

"I nibble lines of ordered code,
Carrots stacked in tidy mode;
Ascend then fall, a neat parade,
Filters paired, the queries made.
Hop, tests pass — the sort’s bestowed. 🥕🐇"

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.


📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between a4a2f2a and 1be21f6.

📒 Files selected for processing (1)
  • tests/Meilisearch.Tests/DocumentTests.cs (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • tests/Meilisearch.Tests/DocumentTests.cs
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@kashifsoofi kashifsoofi force-pushed the #665-add-support-for-sorting-on-documents-api branch 6 times, most recently from a06db50 to c95e43a Compare August 14, 2025 14:46
@kashifsoofi kashifsoofi force-pushed the #665-add-support-for-sorting-on-documents-api branch from c95e43a to a4a2f2a Compare August 23, 2025 18:03
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (3)
tests/Meilisearch.Tests/DocumentTests.cs (3)

646-662: Pluralize test name, use a unique index UID, and avoid multiple enumerations.

  • Naming: other tests use “Documents” (plural). Align for consistency.
  • Index UID: reusing "GetOneExistingDocumentWithIntegerIdTest" can make failures harder to triage; give each test its own UID.
  • Results: materialize once to a list to avoid repeated enumeration of Results.

Apply:

-        public async Task GetMultipleExistingDocumentWithAscSort()
+        public async Task GetMultipleExistingDocumentsWithAscSort()
         {
-            var index = await _fixture.SetUpBasicIndexWithIntId("GetOneExistingDocumentWithIntegerIdTest");
+            var index = await _fixture.SetUpBasicIndexWithIntId("GetMultipleExistingDocumentsWithAscSortTest");
             var updateSortable = await index.UpdateSortableAttributesAsync(new[] { "id" });
             updateSortable.TaskUid.Should().BeGreaterOrEqualTo(0);
             await index.WaitForTaskAsync(updateSortable.TaskUid);

-            var documents =
-                await index.GetDocumentsAsync<MovieWithIntId>(new DocumentsQuery()
-                {
-                    Sort = new List<string> { "id:asc" }
-                });
+            var results = (await index.GetDocumentsAsync<MovieWithIntId>(
+                new DocumentsQuery { Sort = new List<string> { "id:asc" } }
+            )).Results.ToList();

-            Assert.Equal(7, documents.Results.Count());
-            documents.Results.Should().BeInAscendingOrder(x => x.Id);
+            Assert.Equal(7, results.Count);
+            results.Should().BeInAscendingOrder(x => x.Id);
         }

664-680: Same refinements for the DESC test; consider consolidating ASC/DESC with a Theory.

  • Consistency and isolation: pluralize the method name and use a unique index UID.
  • Minor style: materialize results once.
  • Optional: reduce duplication by converting ASC/DESC into a single [Theory] with InlineData.

Apply:

-        public async Task GetMultipleExistingDocumentWithDescSort()
+        public async Task GetMultipleExistingDocumentsWithDescSort()
         {
-            var index = await _fixture.SetUpBasicIndexWithIntId("GetOneExistingDocumentWithIntegerIdTest");
+            var index = await _fixture.SetUpBasicIndexWithIntId("GetMultipleExistingDocumentsWithDescSortTest");
             var updateSortable = await index.UpdateSortableAttributesAsync(new[] { "id" });
             updateSortable.TaskUid.Should().BeGreaterOrEqualTo(0);
             await index.WaitForTaskAsync(updateSortable.TaskUid);

-            var documents =
-                await index.GetDocumentsAsync<MovieWithIntId>(new DocumentsQuery()
-                {
-                    Sort = new List<string> { "id:desc" }
-                });
+            var results = (await index.GetDocumentsAsync<MovieWithIntId>(
+                new DocumentsQuery { Sort = new List<string> { "id:desc" } }
+            )).Results.ToList();

-            Assert.Equal(7, documents.Results.Count());
-            documents.Results.Should().BeInDescendingOrder(x => x.Id);
+            Assert.Equal(7, results.Count);
+            results.Should().BeInDescendingOrder(x => x.Id);
         }

Optional consolidation sketch:

[Theory]
[InlineData("id:asc", true)]
[InlineData("id:desc", false)]
public async Task GetMultipleExistingDocumentsWithIdSort(string sort, bool ascending)
{
    var index = await _fixture.SetUpBasicIndexWithIntId($"GetMultipleExistingDocumentsWithIdSort_{(ascending ? "Asc" : "Desc")}Test");
    var updateSortable = await index.UpdateSortableAttributesAsync(new[] { "id" });
    updateSortable.TaskUid.Should().BeGreaterOrEqualTo(0);
    await index.WaitForTaskAsync(updateSortable.TaskUid);

    var results = (await index.GetDocumentsAsync<MovieWithIntId>(new DocumentsQuery { Sort = new() { sort } }))
        .Results.ToList();

    Assert.Equal(7, results.Count);
    if (ascending)
        results.Should().BeInAscendingOrder(x => x.Id);
    else
        results.Should().BeInDescendingOrder(x => x.Id);
}

682-708: Multi-sort test: unique index UID, pluralized name, and optionally strengthen the ordering assertions.

  • Consistency/isolation: pluralize the method name and use a unique index UID.
  • Optional: in addition to checking first/last, verify group boundaries and within-group descending order on name to more directly exercise multi-key sort.

Apply:

-        public async Task GetMultipleExistingDocumentWithMultiSort()
+        public async Task GetMultipleExistingDocumentsWithMultiSort()
         {
-            var index = await _fixture.SetUpBasicIndexWithIntId("GetOneExistingDocumentWithIntegerIdTest");
+            var index = await _fixture.SetUpBasicIndexWithIntId("GetMultipleExistingDocumentsWithMultiSortTest");
             var updateFilterable = await index.UpdateFilterableAttributesAsync(new[] { "genre" });
             updateFilterable.TaskUid.Should().BeGreaterOrEqualTo(0);
             await index.WaitForTaskAsync(updateFilterable.TaskUid);

             var updateSortable = await index.UpdateSortableAttributesAsync(new[] { "genre", "name" });
             updateSortable.TaskUid.Should().BeGreaterOrEqualTo(0);
             await index.WaitForTaskAsync(updateSortable.TaskUid);

-            var documents =
-                await index.GetDocumentsAsync<MovieWithIntId>(new DocumentsQuery()
-                {
-                    Filter = "genre IN ['SF','Action']",
-                    Sort = new List<string> { "genre:asc", "name:desc" }
-                });
+            var results = (await index.GetDocumentsAsync<MovieWithIntId>(
+                new DocumentsQuery
+                {
+                    Filter = "genre IN ['SF','Action']",
+                    Sort = new List<string> { "genre:asc", "name:desc" }
+                }
+            )).Results.ToList();

-            Assert.Equal(4, documents.Results.Count());
-            var first = documents.Results.First();
+            Assert.Equal(4, results.Count);
+            var first = results.First();
             first.Genre.Should().Be("Action");
             first.Name.Should().Be("Spider-Man");
-            var last = documents.Results.Last();
+            var last = results.Last();
             last.Genre.Should().Be("SF");
             last.Name.Should().Be("Harry Potter");
         }

Optional additional checks to more explicitly validate multi-key ordering:

+            // Optional: validate grouping and within-group sort
+            var split = results.FindIndex(x => x.Genre == "SF");
+            split.Should().BeGreaterThan(0); // at least one Action before SF
+            results.Take(split).Should().OnlyContain(x => x.Genre == "Action");
+            results.Skip(split).Should().OnlyContain(x => x.Genre == "SF");
+            results.Take(split).Should().BeInDescendingOrder(x => x.Name);
+            results.Skip(split).Should().BeInDescendingOrder(x => x.Name);
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 025cf5e and a4a2f2a.

📒 Files selected for processing (5)
  • .env (1 hunks)
  • README.md (1 hunks)
  • src/Meilisearch/QueryParameters/DocumentsQuery.cs (1 hunks)
  • tests/Meilisearch.Tests/DocumentTests.cs (1 hunks)
  • tests/Meilisearch.Tests/ObjectExtensionsTests.cs (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (4)
  • tests/Meilisearch.Tests/ObjectExtensionsTests.cs
  • .env
  • README.md
  • src/Meilisearch/QueryParameters/DocumentsQuery.cs
🧰 Additional context used
🧬 Code graph analysis (1)
tests/Meilisearch.Tests/DocumentTests.cs (2)
tests/Meilisearch.Tests/Movie.cs (1)
  • MovieWithIntId (40-47)
src/Meilisearch/QueryParameters/DocumentsQuery.cs (1)
  • DocumentsQuery (9-40)

@curquiza curquiza changed the title #665: Add support for sort in documents api Add support for sort in documents api Aug 26, 2025
Copy link
Member

@curquiza curquiza left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

thank you

bors merge

@curquiza curquiza changed the title Add support for sort in documents api Add support to sort in /documents endpoint Aug 26, 2025
Copy link
Contributor

meili-bors bot commented Aug 26, 2025

Build succeeded:

@meili-bors meili-bors bot merged commit 1592132 into meilisearch:main Aug 26, 2025
5 checks passed
@kashifsoofi kashifsoofi deleted the #665-add-support-for-sorting-on-documents-api branch August 26, 2025 10:44
@curquiza curquiza added the enhancement New feature or request label Sep 18, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

Successfully merging this pull request may close these issues.

[v1.16.0] Add support for sorting on the documents API
2 participants