Skip to content

Update search and rawSearch methods to use SearchQuery#833

Open
tw2066 wants to merge 11 commits intomeilisearch:mainfrom
tw2066:search
Open

Update search and rawSearch methods to use SearchQuery#833
tw2066 wants to merge 11 commits intomeilisearch:mainfrom
tw2066:search

Conversation

@tw2066
Copy link
Copy Markdown

@tw2066 tw2066 commented Dec 5, 2025

Pull Request

Update search and rawSearch methods to use SearchQuery

Summary by CodeRabbit

  • New Features

    • Search and raw search now accept SearchQuery objects in addition to arrays for more flexible parameter input while remaining backward compatible.
  • Tests

    • Added extensive end-to-end tests covering pagination, options, highlighting/cropping, matching strategies, filters, facets, sorting, vector (embedding) search, ranking score details, distinct attributes, locales, and consistency between raw and formatted results.

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Dec 5, 2025

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Search methods in src/Endpoints/Indexes.php now accept array|SearchQuery for search parameters; rawSearch() converts SearchQuery to an array before merging. A new comprehensive test suite tests/Endpoints/SearchQueryTest.php was added covering many search scenarios.

Changes

Cohort / File(s) Summary
Endpoint signature & handling
src/Endpoints/Indexes.php
Updated search() and rawSearch() parameter types to `array
SearchQuery tests (new)
tests/Endpoints/SearchQueryTest.php
Added extensive end-to-end tests (~+685 lines) covering pagination, raw vs formatted responses, cropping/highlighting, matching strategies, filters, facets, vector search, ranking scores, transform facet options, locales, distinct attribute behavior, and related scenarios.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

I nibble on queries both small and grand,
Array or SearchQuery held in my hand,
I hop, I convert, then tests start to sing,
Results neat as carrots in spring,
A joyful index — happy hops! 🐰✨

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 2.94% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately reflects the main changes: updating the search and rawSearch method signatures to accept SearchQuery objects in addition to arrays.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
📝 Coding Plan
  • Generate coding plan for human review comments

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

Comment @coderabbitai help to get the list of available commands and usage tips.

Tip

You can validate your CodeRabbit configuration file in your editor.

If your editor has YAML language server, you can enable auto-completion and validation by adding # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json at the top of your CodeRabbit configuration file.

Copy link
Copy Markdown

@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 (2)
src/Endpoints/Indexes.php (2)

191-203: Widened search() parameter type is BC‑safe and consistent

Accepting SearchQuery|array for $searchParams while delegating normalization to rawSearch() cleanly extends the API without breaking existing array callers. Consider adding a brief phpdoc @param SearchQuery|array $searchParams for tools that still lean on annotations, but that’s optional.


205-212: Confirm intended precedence between $query and SearchQuery::q

Normalizing $searchParams with instanceof SearchQuery is correct and keeps rawSearch() working for both arrays and objects. Note that with:

$parameters = array_merge(['q' => $query], $searchParams);

a q key coming from SearchQuery::toArray() will override the $query argument when both are set. If you instead want the explicit $query parameter to always win, you could swap the merge order:

-        $parameters = array_merge(
-
-            ['q' => $query],
-            $searchParams
-        );
+        $parameters = array_merge(
+            $searchParams,
+            ['q' => $query],
+        );

Please confirm which behavior you intend.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 565bca2 and 884bf61.

📒 Files selected for processing (1)
  • src/Endpoints/Indexes.php (3 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
src/Endpoints/Indexes.php (1)
src/Contracts/SearchQuery.php (2)
  • SearchQuery (7-495)
  • toArray (463-494)
🔇 Additional comments (1)
src/Endpoints/Indexes.php (1)

13-13: Importing SearchQuery matches the new method signatures

The added use Meilisearch\Contracts\SearchQuery; cleanly supports the new union-typed parameters without redundancy.

@Strift Strift added the enhancement New feature or request label Feb 10, 2026
@codecov
Copy link
Copy Markdown

codecov bot commented Feb 10, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 87.06%. Comparing base (0078a8c) to head (4c71b74).
⚠️ Report is 137 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main     #833      +/-   ##
==========================================
- Coverage   89.78%   87.06%   -2.73%     
==========================================
  Files          59       82      +23     
  Lines        1449     1809     +360     
==========================================
+ Hits         1301     1575     +274     
- Misses        148      234      +86     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@Strift Strift enabled auto-merge February 10, 2026 03:49
Copy link
Copy Markdown
Collaborator

@Strift Strift left a comment

Choose a reason for hiding this comment

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

Hey @tw2066, thanks for your PR.

Can you add tests?

@Strift Strift disabled auto-merge February 10, 2026 03:50
Copy link
Copy Markdown

@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: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@tests/Endpoints/SearchQueryTest.php`:
- Line 483: In testShowRankingScoreDetails there's an unused local variable
$http created by "new Client(...)" — remove the unused declaration to clean up
the test; locate the instantiation in testShowRankingScoreDetails and delete the
"$http = new Client($this->host, getenv('MEILISEARCH_API_KEY'));" line so the
test no longer defines an unused variable.

ℹ️ Review info

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 385f71b and df296b0.

📒 Files selected for processing (2)
  • src/Endpoints/Indexes.php
  • tests/Endpoints/SearchQueryTest.php

Comment thread tests/Endpoints/SearchQueryTest.php Outdated
Copy link
Copy Markdown

@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: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@tests/Endpoints/SearchQueryTest.php`:
- Line 631: The async index operations (updateFilterableAttributes and
updateDocuments called on $this->index) return Task objects and must be awaited
to avoid racing with subsequent assertions; update each call to append ->wait()
so the test waits for the index mutation to complete (e.g., ensure calls to
$this->index->updateFilterableAttributes(...) and
$this->index->updateDocuments(...) use ->wait() before performing
searches/assertions).

ℹ️ Review info

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between df296b0 and 4ce5b00.

📒 Files selected for processing (1)
  • tests/Endpoints/SearchQueryTest.php

Comment thread tests/Endpoints/SearchQueryTest.php Outdated
public function testSearchAndRetrieveFacetStats(): void
{
$this->index = $this->createEmptyIndex($this->safeIndexName());
$this->index->updateFilterableAttributes(['info.reviewNb']);
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

FILE="tests/Endpoints/SearchQueryTest.php"

# Check if file exists and get its line count
if [ ! -f "$FILE" ]; then
    echo "File not found: $FILE"
    exit 1
fi

echo "=== Examining lines around 631 ==="
sed -n '625,640p' "$FILE"

echo
echo "=== Examining lines around 647 ==="
sed -n '641,655p' "$FILE"

echo
echo "=== Examining lines around 676 ==="
sed -n '670,680p' "$FILE"

echo
echo "=== All updateFilterableAttributes and updateDocuments calls ==="
rg -n 'updateFilterableAttributes|updateDocuments' "$FILE" | head -20

Repository: meilisearch/meilisearch-php

Length of output: 3287


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Find where the index property is defined to understand its type
echo "=== Looking for index property definition ==="
rg -n '\$this->index' tests/Endpoints/SearchQueryTest.php | head -5

echo
echo "=== Looking for test class setup/initialization ==="
rg -n 'function setUp|function setUpBeforeClass|class SearchQueryTest' tests/Endpoints/SearchQueryTest.php | head -10

echo
echo "=== Check what type of index is being used ==="
rg -B5 -A5 'protected.*index|private.*index' tests/Endpoints/SearchQueryTest.php | head -30

Repository: meilisearch/meilisearch-php

Length of output: 835


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Look for the Index class and check if updateFilterableAttributes returns something awaitable
echo "=== Searching for Index class ==="
find . -name "*.php" -path "*/src/*" | xargs grep -l "class Index" | head -5

echo
echo "=== Looking for method signatures of updateFilterableAttributes and updateDocuments ==="
rg -A10 'public.*function updateFilterableAttributes|public.*function updateDocuments' --type php | grep -E '(function|return|Task|Index|->)' | head -20

Repository: meilisearch/meilisearch-php

Length of output: 3512


Add ->wait() to async index operations to prevent test flakiness.

Lines 631, 647, and 676 call async index operations without ->wait(). Since updateFilterableAttributes() and updateDocuments() return Task objects, they execute asynchronously and can race with subsequent search assertions, causing intermittent test failures.

🔧 Proposed fix
-        $this->index->updateFilterableAttributes(['info.reviewNb']);
+        $this->index->updateFilterableAttributes(['info.reviewNb'])->wait();
@@
-        $this->index->updateFilterableAttributes(['genre']);
+        $this->index->updateFilterableAttributes(['genre'])->wait();
@@
-        $this->index->updateDocuments(self::DOCUMENTS);
+        $this->index->updateDocuments(self::DOCUMENTS)->wait();

Also applies to: 647-647, 676-676

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tests/Endpoints/SearchQueryTest.php` at line 631, The async index operations
(updateFilterableAttributes and updateDocuments called on $this->index) return
Task objects and must be awaited to avoid racing with subsequent assertions;
update each call to append ->wait() so the test waits for the index mutation to
complete (e.g., ensure calls to $this->index->updateFilterableAttributes(...)
and $this->index->updateDocuments(...) use ->wait() before performing
searches/assertions).

@curquiza
Copy link
Copy Markdown
Member

I love your pic @tw2066 👌 🍊

@Strift Strift self-requested a review March 3, 2026 06:03
Copy link
Copy Markdown
Collaborator

@Strift Strift left a comment

Choose a reason for hiding this comment

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

Hey @tw2066, the CI is not passing.

I suggest you run the tests and linter checks locally and ensure it works before submitting for review 🙏

Please look into the CodeRabbitAI review comments and address them; you can resolve the irrelevant ones.

Copy link
Copy Markdown

@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: 1

🧹 Nitpick comments (1)
tests/Endpoints/SearchQueryTest.php (1)

29-684: Add a direct rawSearch(SearchQuery) test to ensure the SearchQuery parameter type path is covered.

The test suite validates raw responses through search(..., ['raw' => true]) but does not call rawSearch() with a SearchQuery instance directly. Since the rawSearch() method signature accepts array|SearchQuery as its second parameter, a focused test explicitly passing a SearchQuery to rawSearch() would verify this type acceptance path is functional.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tests/Endpoints/SearchQueryTest.php` around lines 29 - 684, Add a new unit
test method (e.g. testRawSearchWithSearchQuery) that constructs a SearchQuery
instance, sets a couple of options (like setLimit(1) or setFacets(['genre'])),
and calls rawSearch on the index with that SearchQuery (e.g.
$this->index->rawSearch(null, $searchQuery) or appropriate signature); assert
the returned raw array contains expected keys (hits, estimatedTotalHits,
facetDistribution when applicable) to verify rawSearch accepts a SearchQuery
object; reference the SearchQuery class and the rawSearch method when locating
where to add the test alongside the other search tests in the file.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@tests/Endpoints/SearchQueryTest.php`:
- Around line 200-231: The test testParametersCanBeAStar asserts presence of
_matchesPosition but never enables it on the SearchQuery; call
$searchQuery->setShowMatchesPosition(true) on the SearchQuery instance (before
the two $this->index->search(...) calls) so that matches positions are returned;
update the SearchQuery setup in testParametersCanBeAStar to include
setShowMatchesPosition(true) alongside setAttributesToRetrieve/crop/highlight to
fix the failing assertions.

---

Nitpick comments:
In `@tests/Endpoints/SearchQueryTest.php`:
- Around line 29-684: Add a new unit test method (e.g.
testRawSearchWithSearchQuery) that constructs a SearchQuery instance, sets a
couple of options (like setLimit(1) or setFacets(['genre'])), and calls
rawSearch on the index with that SearchQuery (e.g. $this->index->rawSearch(null,
$searchQuery) or appropriate signature); assert the returned raw array contains
expected keys (hits, estimatedTotalHits, facetDistribution when applicable) to
verify rawSearch accepts a SearchQuery object; reference the SearchQuery class
and the rawSearch method when locating where to add the test alongside the other
search tests in the file.

ℹ️ Review info
Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 79953999-d9c0-4482-b772-86da2dc2b65f

📥 Commits

Reviewing files that changed from the base of the PR and between 4ce5b00 and 9049bef.

📒 Files selected for processing (2)
  • src/Endpoints/Indexes.php
  • tests/Endpoints/SearchQueryTest.php
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/Endpoints/Indexes.php

Comment thread tests/Endpoints/SearchQueryTest.php Outdated
Comment thread tests/Endpoints/SearchQueryTest.php Outdated

/**
* @internal
* @coversNothing
Copy link
Copy Markdown
Collaborator

@norkunas norkunas Mar 4, 2026

Choose a reason for hiding this comment

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

are these annotations really useful?

@tw2066
Copy link
Copy Markdown
Author

tw2066 commented Mar 18, 2026

The relevant issues have been fixed

Comment thread tests/Endpoints/SearchQueryTest.php Outdated
$this->index->updateDocuments(self::DOCUMENTS)->wait();
}

public function testBasicSearchWithFinitePagination(): void
Copy link
Copy Markdown
Collaborator

@norkunas norkunas Mar 18, 2026

Choose a reason for hiding this comment

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

I don't think that it's necessary to duplicate tests from tests/Endpoints/SearchTest.php

IMHO we should just ensure that SearchQuery is converted to array and that it is passed to the http client.

Or just add a single test case to tests/Endpoints/SearchTest.php where you pass the SearchQuery object and that's enough

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

There's no need to add test cases for this, the toArray method is obvious

@Strift Strift enabled auto-merge March 30, 2026 06:20
@Strift
Copy link
Copy Markdown
Collaborator

Strift commented Mar 30, 2026

Our repository uses rebases for merging PRs via the merge queue. Unfortunately:

This branch cannot be rebased due to conflicts

@tw2066 can you look into resolving these issues? You may perform the rebase manually locally, or open a new PR with a clean history.

Cheers,

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.

4 participants