Skip to content

Conversation

RISHABH4SAHNI
Copy link

@RISHABH4SAHNI RISHABH4SAHNI commented Aug 25, 2025

Add Runnable Examples for Meilisearch Go SDK

This PR implements the requested examples structure as described in the issue:

✅ Examples Added:

  • examples/search/ - Complete search workflow (client init, index creation, documents, search)
  • examples/chat_stream/ - Streaming capabilities and conversational search flow

✅ Features:

  • ✅ Runnable with go run ./examples/search and go run ./examples/chat_stream
  • ✅ Self-contained Go programs with realistic use cases
  • ✅ Comprehensive documentation and error handling
  • ✅ Makefile for easy execution (make search, make chat_stream)
  • ✅ Follows idiomatic Go style

📁 Structure:

examples/ ├── search/ │ ├── main.go # Search example with movies data │ └── README.md # Detailed documentation ├── chat_stream/ │ ├── main.go # Interactive chat streaming │ └── README.md # Setup instructions ├── Makefile # Easy execution commands └── README.md # Overview and usage

🧪 Testing:

  • Both examples compile successfully
  • Directory structure matches issue requirements
  • Commands work: go run ./examples/search and go run ./examples/chat_stream
  • Makefile targets function properly
  • Documentation is comprehensive

📋 Issue Requirements Met:

  • Examples structured by feature (examples/search/, examples/chat_stream/)
  • Each example is a minimal, self-contained Go program
  • Runnable with go run ./examples/...
  • Follows idiomatic Go style
  • Shows client initialization, index creation, adding documents, and performing searches
  • Demonstrates streaming capabilities and conversational search flow

Ready for review and approval! 🚀

Summary by CodeRabbit

  • New Features

    • Added multiple runnable Go examples: interactive CLI chat with real-time streaming, search workflows, document management, index creation & settings, faceted search, task management, and multi-search with multi-query execution.
  • Documentation

    • Added README files for each example describing prerequisites, environment setup (MEILI_HOST / MEILI_API_KEY), step-by-step workflows, sample outputs, and run instructions.

- Add examples/search/ with client initialization, index creation, document management, and search operations
- Add examples/chat_stream/ demonstrating streaming capabilities and conversational flow
- Include comprehensive documentation and Makefile for easy execution
- Examples are structured by feature as requested and runnable with 'go run ./examples/<feature>'
- Follow idiomatic Go style with proper error handling and realistic use cases

Resolves: Add dedicated usage examples under examples/ directory
Copy link

coderabbitai bot commented Aug 25, 2025

Walkthrough

Adds multiple new example programs and accompanying README docs under examples/* demonstrating Meilisearch Go SDK usage: chat streaming, search, document management, index settings, faceted search, task management, and multi-search with environment-based configuration and example document types.

Changes

Cohort / File(s) Summary
Chat streaming example
examples/chat_stream/README.md, examples/chat_stream/main.go
New README and CLI-style Go example: client init from env, workspace discovery, interactive loop, streaming ChatCompletionStreamWithContext usage, real-time chunk printing, EOF/error handling, 60s streaming timeout.
Basic search example
examples/search/README.md, examples/search/main.go
New README and Go example adding Movie type, index creation, settings update, batch indexing with task waits, simple and advanced searches (filters, facets, highlights), and env-based configuration.
Add/update/delete documents
examples/add_documents/README.md, examples/add_documents/main.go
New README and example adding User type; demonstrates CreateIndex, AddDocuments (batch/single), UpdateDocuments, GetDocument(s), DeleteDocument(s), and task-wait helper.
Create index + settings
examples/create_index_settings/README.md, examples/create_index_settings/main.go
New README and example creating articles index and applying comprehensive Settings (attributes, ranking rules, stop words, synonyms, typo tolerance), waiting for tasks and printing settings.
Faceted search
examples/facet_search/README.md, examples/facet_search/main.go
New README and example adding Book type; creates books index, configures filterable/sortable attributes, seeds docs, and demonstrates facet distributions, filtered and facet-specific searches.
Task management
examples/manage_tasks/README.md, examples/manage_tasks/main.go
New README and example adding Document and TaskStats types; creates task_demo index, generates/list tasks, filters tasks, WaitForTask usage, aggregates task stats, and displays task details.
Multi-search
examples/multi_search/README.md, examples/multi_search/main.go
New README and example adding Product type; creates products index, seeds docs, performs client.MultiSearch with per-query params/filters/sorts, and prints per-query hits.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant U as User (CLI)
  participant App as examples/chat_stream/main.go
  participant MS as Meilisearch Server
  rect #F0FAFF
  U->>App: Start (MEILI_HOST / MEILI_API_KEY)
  App->>MS: Health()
  MS-->>App: healthy
  App->>MS: ListWorkspaces(limit=10)
  MS-->>App: workspaces
  end
  loop interactive queries
    U->>App: user message
    App->>MS: ChatCompletionStreamWithContext(workspaceID, messages, stream=true)
    loop stream chunks
      MS-->>App: stream chunk
      App-->>U: print chunk ("Assistant: ...")
    end
    MS-->>App: stream EOF
  end
Loading
sequenceDiagram
  autonumber
  participant App as examples/multi_search/main.go
  participant MS as Meilisearch Server
  participant C as Console
  App->>MS: Create/Ensure index "products"
  MS-->>App: Task UID
  App->>MS: AddDocuments(products)
  MS-->>App: Task UID
  App->>MS: WaitForTask(...)
  MS-->>App: task succeeded
  App->>MS: MultiSearch([q1,q2,q3])
  MS-->>App: Batch results (per-query)
  App-->>C: Print per-query hits & metadata
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Suggested labels

enhancement

Suggested reviewers

  • ja7ad
  • curquiza

Poem

I hop through indexes, swift and bright,
Streaming answers in the night.
I seed and facet, task and cheer,
Examples bloom — the code is near.
A rabbit claps: demos, hooray! 🐇✨

✨ 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 or @coderabbit 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.

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: 8

🧹 Nitpick comments (13)
examples/search/main.go (3)

3-10: Use env-configured host/API key and close the client.

Hardcoded credentials make examples less portable and encourage editing source. Read host/API key from env and close the client to free resources.

Apply:

 import (
 	"context"
 	"fmt"
+	"os"
 	"log"
 	"time"

 	"github.com/meilisearch/meilisearch-go"
 )
@@
-	// Replace with your Meilisearch server URL and API key
-	client := meilisearch.New("http://localhost:7700", meilisearch.WithAPIKey("your-api-key"))
+	// Configure via environment for convenience:
+	// MEILI_HOST (default: http://localhost:7700), MEILI_API_KEY (optional)
+	host := getenv("MEILI_HOST", "http://localhost:7700")
+	apiKey := os.Getenv("MEILI_API_KEY")
+	client := meilisearch.New(host, meilisearch.WithAPIKey(apiKey))
+	defer client.Close()

Add helper (outside the selected lines, e.g., after main):

func getenv(key, def string) string {
	if v := os.Getenv(key); v != "" {
		return v
	}
	return def
}

Also applies to: 25-26


121-124: Optional: print typed results for clarity.

Hits are printed as opaque maps. Consider setting AttributesToRetrieve or unmarshalling hits into Movie for cleaner output.

Example:

searchResult, _ := index.Search("godfather", &meilisearch.SearchRequest{
	AttributesToRetrieve: []string{"id", "title", "year"},
})
for _, h := range searchResult.Hits {
	fmt.Printf("  - %s (%v)\n", h["title"], h["year"])
}

41-58: Handle CreateIndex errors more precisely

Your current code treats any CreateIndex error as “index might already exist,” which can hide genuine failures (e.g. authentication, network issues). Please update the error branch to:

  • Specifically detect the “index already exists” case (for example, use errors.As to match a *meilisearch.Error with Code == "index_already_exists", or check for HTTP 409).
  • For all other errors, return or exit rather than proceeding silently.
  • If the SDK doesn’t expose a distinct error type/code, fall back to verifying existence via GetIndexWithContext and fail if that also errors.

Locations to update:

  • examples/search/main.go at the client.CreateIndex error branch (lines 41–49).

Suggested diff:

@@ examples/search/main.go:41
-   task, err := client.CreateIndex(&meilisearch.IndexConfig{
+   task, err := client.CreateIndex(&meilisearch.IndexConfig{
@@ examples/search/main.go:45
-   if err != nil {
-     log.Printf("Index might already exist: %v", err)
-   } else {
+   if err != nil {
+     // Only ignore the “already exists” error; treat all others as fatal.
+     var meiliErr *meilisearch.Error
+     if errors.As(err, &meiliErr) && meiliErr.Code == "index_already_exists" {
+       log.Printf("Index %q already exists, skipping creation", indexUID)
+     } else {
+       return fmt.Errorf("failed to create index %q: %w", indexUID, err)
+     }
+   } else {
examples/chat_stream/main.go (1)

88-110: setupKnowledgeBase: good flow; consider surfacing “index exists” vs fatal.

The function cleanly waits for tasks and propagates errors. You might treat “already exists” as non-fatal explicitly and only return on other errors to keep example output cleaner.

Also applies to: 112-149

examples/Makefile (3)

1-1: Add a “test” phony to satisfy checkmake, or relax the rule.

If checkmake is wired in CI, an empty test target avoids warnings.

Apply:

-.PHONY: help search chat_stream all clean
+.PHONY: help search chat_stream all clean test

And append:

+test:
+	@echo "No tests for examples; skipping."

16-24: Where do users run this Makefile from?

Targets use relative paths that work when invoked from examples/. Many users will run make at repo root. Either document “make -C examples ” (see README) or make paths repo-root-friendly.

Option A (docs-only): In examples/README.md, show:

  • make -C examples search
  • make -C examples chat_stream

Option B (Makefile): Prefix paths with ./examples/ to support repo-root invocation:

-search:
+search:
 	@echo "Running basic search example..."
-	go run ./search/main.go
+	go run ./examples/search
@@
-chat_stream:
+chat_stream:
 	@echo "Running chat streaming example..."
-	go run ./chat_stream/main.go
+	go run ./examples/chat_stream

4-14: Optional: shorten help body to quiet maxbodylength warning.

Non-blocking tweak if you care about checkmake.

Example:

 help:
-	@echo "Available commands:"
-	@echo "  make search      - Run the basic search example"
-	@echo "  make chat_stream - Run the chat streaming example"
-	@echo "  make all         - Run all examples"
-	@echo "  make clean       - Clean up any temporary files"
-	@echo ""
-	@echo "Prerequisites:"
-	@echo "  - Meilisearch server running on http://localhost:7700"
-	@echo "  - Go 1.20 or higher installed"
+	@echo "Targets: search | chat_stream | all | clean"
+	@echo "Prereqs: Meilisearch @ http://localhost:7700, Go >= 1.20"
examples/README.md (2)

23-35: Clarify where to run Makefile from and show env-based config.

Readers may try “make search” at repo root and hit path issues. Also surface MEILI_HOST/MEILI_API_KEY to avoid code edits.

Apply:

-Each example is self-contained and can be run with:
+Each example is self-contained and can be run with:
@@
-For example:
+For example (from repo root):
 ```bash
 go run ./examples/search
 go run ./examples/chat_stream

@@
-Or using the provided Makefile:
+Or using the provided Makefile (run from repo root with -C):

-make search
-make chat_stream
-make all
+make -C examples search
+make -C examples chat_stream
+make -C examples all

And add under “Configuration”:

```diff
 Before running the examples, make sure to:
 1. Update the Meilisearch server URL in each example
 2. Set the appropriate API key
 3. Ensure your Meilisearch instance has the required features enabled
+4. Alternatively, set environment variables instead of editing code:
+   - MEILI_HOST (default: http://localhost:7700)
+   - MEILI_API_KEY (if authentication is enabled)

Also applies to: 37-43


15-22: Set expectations for chat feature availability.

If chat workspaces/streaming are behind a feature flag or version gate, call it out to reduce confusion.

Add a note:

  • Chat Streaming requires a Meilisearch build with chat APIs enabled. Ensure workspaces are configured and reachable before running the example.
examples/search/README.md (1)

29-47: Augment run instructions with env-based config and a note on filters/facets.

Filtering on year and faceting on genres/year require making those attributes filterable in index settings. Also show env variables to avoid code edits.

Append after step 2:

 2. **Update configuration:**
    Edit `main.go` to match your Meilisearch server URL and API key.
+   Alternatively, export environment variables:
+   ```bash
+   export MEILI_HOST="http://localhost:7700"
+   export MEILI_API_KEY="<your api key>"
+   ```

Append to the end:

 The example will create a "movies" index, add sample movie documents, and demonstrate various search operations with detailed output.
+
+Note: To use the filtered/faceted search example, ensure `year` and `genres` are configured as filterable/faceted attributes on your index. The example can be extended to update settings programmatically before running the searches.
examples/chat_stream/README.md (3)

1-1: Retitle to match the file’s scope (per-example README).

This README lives under examples/chat_stream/, so the title should reflect the Chat Streaming example specifically. The generic title can confuse readers and duplicates top-level docs.

Apply this diff:

-# Meilisearch Go SDK Examples
+# Chat Streaming — Meilisearch Go SDK Example

25-35: Clarify run instructions (repo root vs. this directory) and mention Makefile targets.

Current text uses a placeholder and might be ambiguous when viewed from this subdirectory. Provide explicit commands and include make targets added in this PR.

Apply this diff:

-Each example is self-contained and can be run with:
-
-```bash
-go run ./examples/<example-name>
-```
-
-For example:
-```bash
-go run ./examples/search
-go run ./examples/chat_stream
-```
+From the repository root:
+```bash
+go run ./examples/search
+go run ./examples/chat_stream
+```
+
+Or from this directory:
+```bash
+go run .
+```
+
+Using the Makefile targets:
+```bash
+make search
+make chat_stream
+```

39-41: Be explicit about configuration knobs (host, API key, and feature flags).

“Ensure your Meilisearch instance has the required features enabled” is vague. Readers need exact steps (env vars, flags, or code changes) to run the example successfully.

Please clarify:

  • Which environment variables (if any) the example reads (e.g., MEILI_HOST/MEILI_API_KEY), or how to pass host/key via flags.
  • Whether the server must enable any experimental or streaming endpoints; name them explicitly and show how to enable them.
  • Provide a small snippet showing configuration via env vars or flags to eliminate guesswork.

I can draft these updates once you confirm how main.go wires configuration.

Also applies to: 45-49

📜 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 8a246ef and d95b87b.

📒 Files selected for processing (6)
  • examples/Makefile (1 hunks)
  • examples/README.md (1 hunks)
  • examples/chat_stream/README.md (1 hunks)
  • examples/chat_stream/main.go (1 hunks)
  • examples/search/README.md (1 hunks)
  • examples/search/main.go (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (2)
examples/chat_stream/main.go (5)
meilisearch.go (1)
  • New (18-41)
options.go (1)
  • WithAPIKey (126-130)
types.go (4)
  • Health (666-668)
  • ListChatWorkSpaceQuery (806-809)
  • IndexConfig (90-95)
  • ChatCompletionQuery (811-815)
meilisearch_interface.go (1)
  • ServiceManager (8-82)
stream.go (1)
  • Stream (189-195)
examples/search/main.go (4)
meilisearch.go (1)
  • New (18-41)
options.go (1)
  • WithAPIKey (126-130)
types.go (3)
  • Health (666-668)
  • IndexConfig (90-95)
  • SearchRequest (469-499)
hit.go (1)
  • Hits (12-12)
🪛 LanguageTool
examples/chat_stream/README.md

[grammar] ~7-~7: There might be a mistake here.
Context: ...amples ### 📝 Basic Search Demonstrates core search functionality in...

(QB_NEW_EN)


[grammar] ~9-~9: There might be a mistake here.
Context: ... core search functionality including: - Client initialization and connection test...

(QB_NEW_EN)


[grammar] ~10-~10: There might be a mistake here.
Context: ...initialization and connection testing - Index creation and management - Document ...

(QB_NEW_EN)


[grammar] ~11-~11: There might be a mistake here.
Context: ...sting - Index creation and management - Document addition and indexing - Various ...

(QB_NEW_EN)


[grammar] ~12-~12: There might be a mistake here.
Context: ...ment - Document addition and indexing - Various search operations (basic, filtere...

(QB_NEW_EN)


[grammar] ~13-~13: There might be a mistake here.
Context: ...operations (basic, filtered, faceted) - Task management and waiting for operation...

(QB_NEW_EN)


[grammar] ~13-~13: There might be a mistake here.
Context: ...sk management and waiting for operations ### 💬 Chat Streaming Shows ...

(QB_NEW_EN)


[grammar] ~15-~15: There might be a mistake here.
Context: ... ### 💬 Chat Streaming Shows streaming capabilities and conversa...

(QB_NEW_EN)


[grammar] ~17-~17: There might be a mistake here.
Context: ...pabilities and conversational search: - Chat workspace management - Real-time str...

(QB_NEW_EN)


[grammar] ~18-~18: There might be a mistake here.
Context: ...l search: - Chat workspace management - Real-time streaming responses - Interacti...

(QB_NEW_EN)


[grammar] ~19-~19: There might be a mistake here.
Context: ...ement - Real-time streaming responses - Interactive chat sessions - Knowledge bas...

(QB_NEW_EN)


[grammar] ~20-~20: There might be a mistake here.
Context: ...responses - Interactive chat sessions - Knowledge base integration - Context-awar...

(QB_NEW_EN)


[grammar] ~21-~21: There might be a mistake here.
Context: ...sessions - Knowledge base integration - Context-aware responses ## Running Examp...

(QB_NEW_EN)


[grammar] ~21-~21: There might be a mistake here.
Context: ...se integration - Context-aware responses ## Running Examples Each example is self-co...

(QB_NEW_EN)


[grammar] ~39-~39: There might be a mistake here.
Context: ...` ## Prerequisites - Go 1.20 or higher - Meilisearch server running (default: htt...

(QB_NEW_EN)


[grammar] ~40-~40: There might be a mistake here.
Context: ...running (default: http://localhost:7700) - Valid API key (if authentication is enab...

(QB_NEW_EN)


[grammar] ~45-~45: There might be a mistake here.
Context: ...fore running the examples, make sure to: 1. Update the Meilisearch server URL in eac...

(QB_NEW_EN)


[grammar] ~52-~52: There might be a mistake here.
Context: ...s follow idiomatic Go style and include: - Comprehensive error handling - Clear doc...

(QB_NEW_EN)


[grammar] ~53-~53: There might be a mistake here.
Context: ... include: - Comprehensive error handling - Clear documentation and comments - Reali...

(QB_NEW_EN)


[grammar] ~54-~54: There might be a mistake here.
Context: ...dling - Clear documentation and comments - Realistic use cases - Best practices for...

(QB_NEW_EN)


[grammar] ~55-~55: There might be a mistake here.
Context: ...ation and comments - Realistic use cases - Best practices for production usage ## ...

(QB_NEW_EN)


[grammar] ~60-~60: There might be a mistake here.
Context: ... Contributing When adding new examples: - Follow the established directory structu...

(QB_NEW_EN)

examples/search/README.md

[grammar] ~5-~5: There might be a mistake here.
Context: ...initialization** with connection testing - Index creation with primary key config...

(QB_NEW_EN)


[grammar] ~6-~6: There might be a mistake here.
Context: ...reation** with primary key configuration - Document management (adding documents ...

(QB_NEW_EN)


[grammar] ~7-~7: There might be a mistake here.
Context: ...agement** (adding documents to an index) - Search operations with various paramet...

(QB_NEW_EN)


[grammar] ~8-~8: There might be a mistake here.
Context: ...ns** with various parameters and filters - Task management (waiting for async ope...

(QB_NEW_EN)


[grammar] ~16-~16: There might be a mistake here.
Context: ...to the index 4. Search Capabilities: - Simple text search - Filtered search ...

(QB_NEW_EN)


[grammar] ~17-~17: There might be a mistake here.
Context: ... Capabilities**: - Simple text search - Filtered search with conditions - Fac...

(QB_NEW_EN)


[grammar] ~18-~18: There might be a mistake here.
Context: ...rch - Filtered search with conditions - Faceted search with distribution - Hi...

(QB_NEW_EN)


[grammar] ~19-~19: There might be a mistake here.
Context: ...ns - Faceted search with distribution - Highlighted results - Pagination cont...

(QB_NEW_EN)


[grammar] ~20-~20: There might be a mistake here.
Context: ...th distribution - Highlighted results - Pagination controls ## Prerequisites -...

(QB_NEW_EN)


[grammar] ~25-~25: There might be a mistake here.
Context: ...s ## Prerequisites - Go 1.20 or higher - Meilisearch server running (default: `ht...

(QB_NEW_EN)


[grammar] ~26-~26: There might be a mistake here.
Context: ...nning (default: http://localhost:7700) - Valid API key (if authentication is enab...

(QB_NEW_EN)


[grammar] ~40-~40: There might be a mistake here.
Context: ...rch ``` 2. Update configuration: Edit main.go to match your Meilisearch...

(QB_NEW_EN)

examples/README.md

[grammar] ~7-~7: There might be a mistake here.
Context: ...amples ### 📝 Basic Search Demonstrates core search functionality in...

(QB_NEW_EN)


[grammar] ~9-~9: There might be a mistake here.
Context: ... core search functionality including: - Client initialization and connection test...

(QB_NEW_EN)


[grammar] ~10-~10: There might be a mistake here.
Context: ...initialization and connection testing - Index creation and management - Document ...

(QB_NEW_EN)


[grammar] ~11-~11: There might be a mistake here.
Context: ...sting - Index creation and management - Document addition and indexing - Various ...

(QB_NEW_EN)


[grammar] ~12-~12: There might be a mistake here.
Context: ...ment - Document addition and indexing - Various search operations (basic, filtere...

(QB_NEW_EN)


[grammar] ~13-~13: There might be a mistake here.
Context: ...operations (basic, filtered, faceted) - Task management and waiting for operation...

(QB_NEW_EN)


[grammar] ~13-~13: There might be a mistake here.
Context: ...sk management and waiting for operations ### 💬 Chat Streaming Shows ...

(QB_NEW_EN)


[grammar] ~15-~15: There might be a mistake here.
Context: ... ### 💬 Chat Streaming Shows streaming capabilities and conversa...

(QB_NEW_EN)


[grammar] ~17-~17: There might be a mistake here.
Context: ...pabilities and conversational search: - Chat workspace management - Real-time str...

(QB_NEW_EN)


[grammar] ~18-~18: There might be a mistake here.
Context: ...l search: - Chat workspace management - Real-time streaming responses - Interacti...

(QB_NEW_EN)


[grammar] ~19-~19: There might be a mistake here.
Context: ...ement - Real-time streaming responses - Interactive chat sessions - Knowledge bas...

(QB_NEW_EN)


[grammar] ~20-~20: There might be a mistake here.
Context: ...responses - Interactive chat sessions - Knowledge base integration - Context-awar...

(QB_NEW_EN)


[grammar] ~21-~21: There might be a mistake here.
Context: ...sessions - Knowledge base integration - Context-aware responses ## Running Examp...

(QB_NEW_EN)


[grammar] ~21-~21: There might be a mistake here.
Context: ...se integration - Context-aware responses ## Running Examples Each example is self-co...

(QB_NEW_EN)


[grammar] ~46-~46: There might be a mistake here.
Context: ...` ## Prerequisites - Go 1.20 or higher - Meilisearch server running (default: htt...

(QB_NEW_EN)


[grammar] ~47-~47: There might be a mistake here.
Context: ...running (default: http://localhost:7700) - Valid API key (if authentication is enab...

(QB_NEW_EN)


[grammar] ~52-~52: There might be a mistake here.
Context: ...fore running the examples, make sure to: 1. Update the Meilisearch server URL in eac...

(QB_NEW_EN)


[grammar] ~59-~59: There might be a mistake here.
Context: ...s follow idiomatic Go style and include: - Comprehensive error handling - Clear doc...

(QB_NEW_EN)


[grammar] ~60-~60: There might be a mistake here.
Context: ... include: - Comprehensive error handling - Clear documentation and comments - Reali...

(QB_NEW_EN)


[grammar] ~61-~61: There might be a mistake here.
Context: ...dling - Clear documentation and comments - Realistic use cases - Best practices for...

(QB_NEW_EN)


[grammar] ~62-~62: There might be a mistake here.
Context: ...ation and comments - Realistic use cases - Best practices for production usage ## ...

(QB_NEW_EN)


[grammar] ~67-~67: There might be a mistake here.
Context: ... Contributing When adding new examples: - Follow the established directory structu...

(QB_NEW_EN)

🪛 checkmake (0.2.2)
examples/Makefile

[warning] 4-4: Target body for "help" exceeds allowed length of 5 (9).

(maxbodylength)


[warning] 1-1: Missing required phony target "test"

(minphony)

🔇 Additional comments (2)
examples/search/main.go (1)

96-112: LGTM on async task handling.

AddDocuments + WaitForTaskWithContext with a bounded timeout is a solid pattern for examples.

examples/chat_stream/README.md (1)

17-21: Confirmed: Workspace management and Knowledge Base Integration are implemented
The example’s setupKnowledgeBase function (lines 36–39, 88–105) and its ListChatWorkspaces call (lines 41–54) directly demonstrate “Knowledge base integration” and “Chat workspace management,” respectively. No changes to the feature list are necessary.

@ja7ad
Copy link
Collaborator

ja7ad commented Aug 25, 2025

@RISHABH4SAHNI Possible add more examples:

  • multi-search
  • facet search
  • add documents
  • create index and settings
  • manage tasks

- Implement ALL CodeRabbit suggestions across examples
- Add missing imports (errors, io, os, encoding/json)
- Environment-based configuration (MEILI_HOST, MEILI_API_KEY)
- Proper client lifecycle with defer client.Close()
- Robust EOF handling with errors.Is(err, io.EOF)
- Fixed ChatCompletionQuery types and removed unsupported fields
- Fixed SearchRequest field names (Facets vs FacetsDistribution)
- Proper facet distribution JSON parsing
- Dynamic workspace selection instead of hardcoded values
- Fixed broken relative links in README files
- Added 5 new comprehensive examples:
  - add_documents: Document management operations
  - create_index_settings: Index configuration
  - facet_search: Advanced faceted search
  - manage_tasks: Task management and monitoring
  - multi_search: Multi-index search operations
- Consistent getenv() helper across all examples
- Production-ready error handling and resource cleanup
- Updated documentation with environment variable configuration
@RISHABH4SAHNI
Copy link
Author

@RISHABH4SAHNI Possible add more examples:

  • multi-search
  • facet search
  • add documents
  • create index and settings
  • manage tasks

ADDED

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: 20

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
examples/search/README.md (1)

27-30: Close the code fence for the run command.

The closing ``` is missing.

 3. **Run the example:**
    ```bash
    go run ./examples/search
+   ```
♻️ Duplicate comments (1)
examples/chat_stream/README.md (1)

3-7: Good: fixed the broken relative link.

The link to the sibling example now correctly uses ../search. This resolves the previously reported broken link.

🧹 Nitpick comments (19)
examples/search/README.md (1)

1-2: Clarify prerequisites at the top instead of sample output lines.

These two bullets read like runtime output. Make them explicit prerequisites for running the example.

-- Meilisearch server running (default: `http://localhost:7700`)
-- Valid API key (if authentication is enabled)
+## Prerequisites
+- A running Meilisearch server (default: http://localhost:7700)
+- A valid API key (if authentication is enabled)
examples/chat_stream/README.md (1)

9-11: Normalize the “setup” bullets under a Prerequisites section.

Numbering starts at 2 and reads like prerequisites rather than steps. Make it a proper section.

-2. **Enterprise Setup**: Configure Meilisearch with LLM integration
-3. **Workspace Configuration**: Set up appropriate chat workspaces
+## Prerequisites
+- Meilisearch instance with chat/LLM features enabled
+- At least one configured chat workspace
examples/facet_search/README.md (3)

28-36: Add a short “Prerequisites” section with a one-liner to start Meilisearch.

This makes the example truly copy/paste runnable for newcomers.

Apply this diff to insert the section before “Configuration”:

@@
-## Configuration
+## Prerequisites
+
+Make sure a Meilisearch instance is running.
+
+Quickstart (Docker):
+```bash
+docker run -d --name meilisearch -p 7700:7700 -e MEILI_MASTER_KEY="masterKey" getmeili/meilisearch:latest
+```
+
+## Configuration

49-50: Add “Cleanup” instructions to remove the sample index.

Keeps local instances tidy after running examples.

Apply this diff:

-The example will create a "books" index, configure facetable attributes, add sample book data, and demonstrate various faceted search scenarios including basic faceting, advanced filtering, and facet-specific searches.
+The example will create a "books" index, configure facetable attributes, add sample book data, and demonstrate various faceted search scenarios including basic faceting, advanced filtering, and facet-specific searches.
+
+## Cleanup
+Remove the example index when you're done:
+```bash
+curl -s -X DELETE "$MEILI_HOST/indexes/books" -H "Authorization: Bearer $MEILI_API_KEY"
+```

5-8: Punctuate bullet list items or keep consistent parallel fragments.

Minor readability tweak: end each bullet with a period, or keep all as pure noun phrases without trailing punctuation.

Example:

-- **Facet distribution** for search results
-- **Filterable attributes** configuration
-- **Facet-specific searches** with targeted queries
-- **Combined filtering** with multiple facets
+- **Facet distribution** for search results.
+- **Filterable attributes** configuration.
+- **Facet-specific searches** with targeted queries.
+- **Combined filtering** with multiple facets.
examples/create_index_settings/README.md (2)

55-61: Mention how to run a local Meilisearch server (quickstart).

Improves DX and reduces setup friction.

Apply this diff to add a short prerequisite snippet above the configuration block:

-## Configuration
+## Prerequisites
+
+Start a local Meilisearch (Docker):
+```bash
+docker run -d --name meilisearch -p 7700:7700 -e MEILI_MASTER_KEY="masterKey" getmeili/meilisearch:latest
+```
+
+## Configuration

69-70: Add “Cleanup” step for the articles index.

Helps avoid leftover state across repeated runs.

Apply this diff:

-The example will create an "articles" index, configure comprehensive settings, add sample articles, and demonstrate how the settings improve search results.
+The example will create an "articles" index, configure comprehensive settings, add sample articles, and demonstrate how the settings improve search results.
+
+## Cleanup
+```bash
+curl -s -X DELETE "$MEILI_HOST/indexes/articles" -H "Authorization: Bearer $MEILI_API_KEY"
+```
examples/manage_tasks/README.md (3)

51-59: Add a quickstart Meilisearch run command.

Keeps setup self-contained like other examples.

Apply this diff to insert prerequisites above the configuration:

-## Configuration
+## Prerequisites
+
+Start a local Meilisearch (Docker):
+```bash
+docker run -d --name meilisearch -p 7700:7700 -e MEILI_MASTER_KEY="masterKey" getmeili/meilisearch:latest
+```
+
+## Configuration

67-68: Tighten wording to avoid split infinitive.

Minor style tweak for clarity.

Apply this diff:

-The example will create various tasks, demonstrate different ways to monitor and filter them, and show how to properly handle asynchronous operations in Meilisearch.
+The example will create various tasks, demonstrate different ways to monitor and filter them, and show how to handle asynchronous operations properly in Meilisearch.

75-76: Add “Cleanup” instructions to drop the demo index.

Prevents index accumulation during repeated runs.

Apply this diff:

 - Monitor task performance with statistics
+
+## Cleanup
+```bash
+curl -s -X DELETE "$MEILI_HOST/indexes/task_demo" -H "Authorization: Bearer $MEILI_API_KEY"
+```
examples/multi_search/README.md (2)

25-33: Add a quickstart to run Meilisearch before configuration.

Aligns with other READMEs and improves first-run success.

Apply this diff:

-## Configuration
+## Prerequisites
+
+Start a local Meilisearch (Docker):
+```bash
+docker run -d --name meilisearch -p 7700:7700 -e MEILI_MASTER_KEY="masterKey" getmeili/meilisearch:latest
+```
+
+## Configuration

46-47: Add “Cleanup” section to remove the products index.

Keeps the local instance clean across runs.

Apply this diff:

-The example will create a "products" index, add sample product data, and demonstrate multiple simultaneous search queries with different parameters, filters, and sorting options.
+The example will create a "products" index, add sample product data, and demonstrate multiple simultaneous search queries with different parameters, filters, and sorting options.
+
+## Cleanup
+```bash
+curl -s -X DELETE "$MEILI_HOST/indexes/products" -H "Authorization: Bearer $MEILI_API_KEY"
+```
examples/add_documents/README.md (3)

31-39: Mention primary key expectations for the “users” index.

Clarify that the example uses a primary key (commonly id) and whether it is set at index creation or inferred from documents.

Apply this diff:

 ## Configuration
@@
 export MEILI_API_KEY="your-api-key"

+Note: This example creates a users index with primary key id. If the index already exists with a different primary key, adjust the example or delete the existing index first.


---

`41-45`: **Add a quickstart to start Meilisearch before running the example.**

Improves “it just works” experience.

Apply this diff:

```diff
 ## Running the Example
@@
 ```bash
+docker run -d --name meilisearch -p 7700:7700 -e MEILI_MASTER_KEY="masterKey" getmeili/meilisearch:latest
+
 go run ./examples/add_documents

---

`47-48`: **Add “Cleanup” step for the users index.**

Avoids state leaking across repeated runs.

Apply this diff:

```diff
-The example will create a "users" index and demonstrate all document management operations with detailed logging of each step and task completion.
+The example will create a "users" index and demonstrate all document management operations with detailed logging of each step and task completion.
+
+## Cleanup
+```bash
+curl -s -X DELETE "$MEILI_HOST/indexes/users" -H "Authorization: Bearer $MEILI_API_KEY"
+```
examples/create_index_settings/main.go (1)

33-44: Index creation: continue-on-exists path is fine; consider surfacing non-existence-related errors.

Logging and continuing when the index “might already exist” is ok for examples. If you want slightly clearer diagnostics, check the error kind and only suppress the known “already exists” case.

examples/add_documents/main.go (1)

126-149: Minor: consider aligning ID types for readability.

You create integer IDs but pass string IDs to DeleteDocument/GetDocument. This works with the current client, but using a consistent type (either always strings or always integers) improves clarity for users copy-pasting the example.

Example (only if the SDK accepts non-string IDs):

- doc, err := index.GetDocument("2", nil)
+ doc, err := index.GetDocument(2, nil)
examples/manage_tasks/main.go (2)

169-187: Status pretty-print switch is fine; optional: use typed constants for clarity.

Comparing against raw strings works because TaskStatus’s underlying type is string. If you want stronger typing, switch on meilisearch.TaskStatus("succeeded"), etc.


98-109: Optional: add timeouts to long-running list operations.

GetTasks calls can hang on slow networks. Consider GetTasksWithContext variants with short timeouts to keep examples snappy.

Also applies to: 130-137

📜 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 d95b87b and ffc404a.

📒 Files selected for processing (14)
  • examples/add_documents/README.md (1 hunks)
  • examples/add_documents/main.go (1 hunks)
  • examples/chat_stream/README.md (1 hunks)
  • examples/chat_stream/main.go (1 hunks)
  • examples/create_index_settings/README.md (1 hunks)
  • examples/create_index_settings/main.go (1 hunks)
  • examples/facet_search/README.md (1 hunks)
  • examples/facet_search/main.go (1 hunks)
  • examples/manage_tasks/README.md (1 hunks)
  • examples/manage_tasks/main.go (1 hunks)
  • examples/multi_search/README.md (1 hunks)
  • examples/multi_search/main.go (1 hunks)
  • examples/search/README.md (1 hunks)
  • examples/search/main.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • examples/search/main.go
🧰 Additional context used
🧬 Code graph analysis (6)
examples/manage_tasks/main.go (3)
meilisearch.go (1)
  • New (18-41)
options.go (1)
  • WithAPIKey (126-130)
types.go (4)
  • IndexConfig (90-95)
  • Settings (134-156)
  • TasksQuery (316-331)
  • Task (289-302)
examples/create_index_settings/main.go (3)
meilisearch.go (1)
  • New (18-41)
options.go (1)
  • WithAPIKey (126-130)
types.go (5)
  • IndexConfig (90-95)
  • Settings (134-156)
  • TypoTolerance (164-170)
  • MinWordSizeForTypos (173-176)
  • Pagination (179-181)
examples/add_documents/main.go (4)
meilisearch.go (1)
  • New (18-41)
options.go (1)
  • WithAPIKey (126-130)
types.go (2)
  • DocumentsQuery (587-595)
  • IndexConfig (90-95)
meilisearch_interface.go (1)
  • ServiceManager (8-82)
examples/multi_search/main.go (4)
meilisearch.go (1)
  • New (18-41)
options.go (1)
  • WithAPIKey (126-130)
types.go (3)
  • MultiSearchRequest (511-514)
  • SearchRequest (469-499)
  • IndexConfig (90-95)
meilisearch_interface.go (1)
  • ServiceManager (8-82)
examples/facet_search/main.go (4)
meilisearch.go (1)
  • New (18-41)
options.go (1)
  • WithAPIKey (126-130)
types.go (5)
  • SearchRequest (469-499)
  • FacetSearchRequest (564-572)
  • IndexConfig (90-95)
  • Settings (134-156)
  • SearchResponse (528-542)
meilisearch_interface.go (1)
  • ServiceManager (8-82)
examples/chat_stream/main.go (5)
meilisearch.go (1)
  • New (18-41)
options.go (1)
  • WithAPIKey (126-130)
types.go (3)
  • ListChatWorkSpaceQuery (806-809)
  • ChatCompletionQuery (811-815)
  • ChatCompletionMessage (817-820)
meilisearch_interface.go (1)
  • ServiceManager (8-82)
stream.go (1)
  • Stream (189-195)
🪛 LanguageTool
examples/add_documents/README.md

[grammar] ~5-~5: There might be a mistake here.
Context: ...ocuments** (single and batch operations) - Updating documents with new data - **R...

(QB_NEW_EN)


[grammar] ~6-~6: There might be a mistake here.
Context: ...) - Updating documents with new data - Retrieving documents by ID and in batc...

(QB_NEW_EN)


[grammar] ~7-~7: There might be a mistake here.
Context: ...rieving documents** by ID and in batches - Deleting documents (single and multipl...

(QB_NEW_EN)


[grammar] ~8-~8: There might be a mistake here.
Context: ...leting documents** (single and multiple) - Task monitoring for all operations ##...

(QB_NEW_EN)


[grammar] ~25-~25: There might be a mistake here.
Context: ... existing documents - GetDocument() - Retrieve single document by ID - `GetDocuments()...

(QB_NEW_EN)


[grammar] ~27-~27: There might be a mistake here.
Context: ... with pagination - DeleteDocument() - Delete single document - DeleteDocuments() -...

(QB_NEW_EN)

examples/chat_stream/README.md

[grammar] ~3-~3: There might be a mistake here.
Context: ...mples ### 📝 Basic Search Basic search functionality with index cre...

(QB_NEW_EN)


[grammar] ~4-~4: There might be a mistake here.
Context: ...nagement, and various search operations. ### 💬 Chat Streaming Interactive chat experi...

(QB_NEW_EN)


[grammar] ~6-~6: There might be a mistake here.
Context: ...arch operations. ### 💬 Chat Streaming Interactive chat experience with streamin...

(QB_NEW_EN)


[grammar] ~7-~7: There might be a mistake here.
Context: ...esponses and knowledge base integration. 2. Enterprise Setup: Configure Meilisearch...

(QB_NEW_EN)

examples/create_index_settings/README.md

[grammar] ~5-~5: There might be a mistake here.
Context: ...reation** with primary key specification - Advanced settings configuration for op...

(QB_NEW_EN)


[grammar] ~6-~6: There might be a mistake here.
Context: ...tings** configuration for optimal search - Ranking rules customization - **Attrib...

(QB_NEW_EN)


[grammar] ~7-~7: There might be a mistake here.
Context: ...search - Ranking rules customization - Attribute configuration for search, fi...

(QB_NEW_EN)


[grammar] ~8-~8: There might be a mistake here.
Context: ...ion** for search, filtering, and sorting - Typo tolerance and synonym managem...

(QB_NEW_EN)


[grammar] ~15-~15: There might be a mistake here.
Context: ...nfiguration 3. Attribute Management: - Searchable attributes (search priority) ...

(QB_NEW_EN)


[grammar] ~16-~16: There might be a mistake here.
Context: ... Searchable attributes (search priority) - Displayed attributes (result fields) ...

(QB_NEW_EN)


[grammar] ~17-~17: There might be a mistake here.
Context: ... - Displayed attributes (result fields) - Filterable attributes (filter capabiliti...

(QB_NEW_EN)


[grammar] ~18-~18: There might be a mistake here.
Context: ...terable attributes (filter capabilities) - Sortable attributes (sorting options) 4....

(QB_NEW_EN)


[grammar] ~19-~19: There might be a mistake here.
Context: ... - Sortable attributes (sorting options) 4. Search Enhancement: - Stop words co...

(QB_NEW_EN)


[grammar] ~20-~20: There might be a mistake here.
Context: ...ting options) 4. Search Enhancement: - Stop words configuration - Synonyms f...

(QB_NEW_EN)


[grammar] ~21-~21: There might be a mistake here.
Context: ...ncement**: - Stop words configuration - Synonyms for better matching - Typo t...

(QB_NEW_EN)


[grammar] ~22-~22: There might be a mistake here.
Context: ...ration - Synonyms for better matching - Typo tolerance settings 5. **Performance...

(QB_NEW_EN)


[grammar] ~23-~23: There might be a mistake here.
Context: ...er matching - Typo tolerance settings 5. Performance Settings: - Search cuto...

(QB_NEW_EN)


[grammar] ~24-~24: There might be a mistake here.
Context: ...ce settings 5. Performance Settings: - Search cutoff time - Pagination limit...

(QB_NEW_EN)


[grammar] ~25-~25: There might be a mistake here.
Context: ...ance Settings**: - Search cutoff time - Pagination limits - Faceting configur...

(QB_NEW_EN)


[grammar] ~26-~26: There might be a mistake here.
Context: ...earch cutoff time - Pagination limits - Faceting configuration 6. **Index Inform...

(QB_NEW_EN)


[grammar] ~27-~27: There might be a mistake here.
Context: ...ation limits - Faceting configuration 6. Index Information: Retrieve index meta...

(QB_NEW_EN)


[grammar] ~32-~32: There might be a mistake here.
Context: ...# Settings Configured ### Ranking Rules - words: Matches more words first - **ty...

(QB_NEW_EN)


[grammar] ~41-~41: There might be a mistake here.
Context: ...for rating-based ranking ### Attributes - Searchable: title, content, author, ta...

(QB_NEW_EN)


[grammar] ~42-~42: There might be a mistake here.
Context: ...archable**: title, content, author, tags - Filterable: category, author, featured...

(QB_NEW_EN)


[grammar] ~43-~43: There might be a mistake here.
Context: ...atured, rating, publish_date, word_count - Sortable: publish_date, rating, word_c...

(QB_NEW_EN)


[grammar] ~44-~44: There might be a mistake here.
Context: ...able**: publish_date, rating, word_count - Displayed: id, title, author, category...

(QB_NEW_EN)


[grammar] ~47-~47: There might be a mistake here.
Context: ...rating, featured ### Search Enhancement - Stop Words: Common words ignored in se...

(QB_NEW_EN)


[grammar] ~48-~48: There might be a mistake here.
Context: ... Words**: Common words ignored in search - Synonyms: Related terms for better mat...

(QB_NEW_EN)


[grammar] ~49-~49: There might be a mistake here.
Context: ...yms**: Related terms for better matching - Typo Tolerance: Configurable typo hand...

(QB_NEW_EN)


[grammar] ~50-~50: There might be a mistake here.
Context: ... Tolerance**: Configurable typo handling - Distinct Results: Avoid duplicates by ...

(QB_NEW_EN)

examples/facet_search/README.md

[grammar] ~5-~5: There might be a mistake here.
Context: ...Facet distribution* for search results - Filterable attributes configuration - ...

(QB_NEW_EN)


[grammar] ~6-~6: There might be a mistake here.
Context: ... Filterable attributes configuration - Facet-specific searches with targeted ...

(QB_NEW_EN)


[grammar] ~7-~7: There might be a mistake here.
Context: ...pecific searches** with targeted queries - Combined filtering with multiple facet...

(QB_NEW_EN)


[grammar] ~22-~22: There might be a mistake here.
Context: ...c.) - language: Publication language - publish_year: Year of publication - **...

(QB_NEW_EN)


[grammar] ~23-~23: There might be a mistake here.
Context: ... - publish_year: Year of publication - rating: Book rating - publisher: P...

(QB_NEW_EN)


[grammar] ~24-~24: There might be a mistake here.
Context: ...of publication - rating: Book rating - publisher: Publishing house - **in_pri...

(QB_NEW_EN)


[grammar] ~25-~25: There might be a mistake here.
Context: ...rating - publisher: Publishing house - in_print: Availability status ## Conf...

(QB_NEW_EN)


[grammar] ~49-~49: There might be a mistake here.
Context: ... filtering, and facet-specific searches.

(QB_NEW_EN)

examples/manage_tasks/README.md

[grammar] ~5-~5: There might be a mistake here.
Context: ...sk creation** through various operations - Task monitoring and status tracking - ...

(QB_NEW_EN)


[grammar] ~6-~6: There might be a mistake here.
Context: ... Task monitoring and status tracking - Task filtering by type, status, and in...

(QB_NEW_EN)


[grammar] ~7-~7: There might be a mistake here.
Context: ...k filtering** by type, status, and index - Task statistics and performance monito...

(QB_NEW_EN)


[grammar] ~8-~8: There might be a mistake here.
Context: ... statistics** and performance monitoring - Async operation handling with proper w...

(QB_NEW_EN)


[grammar] ~16-~16: There might be a mistake here.
Context: ... 4. Task Filtering: Filter tasks by: - Task type (documentAdditionOrUpdate, ind...

(QB_NEW_EN)


[grammar] ~17-~17: There might be a mistake here.
Context: ...ntAdditionOrUpdate, indexCreation, etc.) - Status (succeeded, failed, processing, e...

(QB_NEW_EN)


[grammar] ~18-~18: There might be a mistake here.
Context: ...succeeded, failed, processing, enqueued) - Index UID - Date ranges 5. **Task Mon...

(QB_NEW_EN)


[grammar] ~19-~19: There might be a mistake here.
Context: ...ed, processing, enqueued) - Index UID - Date ranges 5. Task Monitoring: Wait...

(QB_NEW_EN)


[grammar] ~20-~20: There might be a mistake here.
Context: ...nqueued) - Index UID - Date ranges 5. Task Monitoring: Wait for task complet...

(QB_NEW_EN)


[grammar] ~27-~27: There might be a mistake here.
Context: ...dexCreation**: Index creation operations - documentAdditionOrUpdate: Document add...

(QB_NEW_EN)


[grammar] ~28-~28: There might be a mistake here.
Context: ...Update**: Document add/update operations - settingsUpdate: Settings configuration...

(QB_NEW_EN)


[grammar] ~29-~29: There might be a mistake here.
Context: ...Update**: Settings configuration changes - documentDeletion: Document deletion op...

(QB_NEW_EN)


[grammar] ~30-~30: There might be a mistake here.
Context: ...Deletion**: Document deletion operations - indexDeletion: Index deletion operatio...

(QB_NEW_EN)


[style] ~67-~67: Try moving the adverb to make the sentence clearer.
Context: ...o monitor and filter them, and show how to properly handle asynchronous operations in Meilisearch. ## Best Practices Show...

(SPLIT_INFINITIVE)

examples/multi_search/README.md

[grammar] ~5-~5: There might be a mistake here.
Context: ... Simultaneous queries across indexes - Different search parameters for each q...

(QB_NEW_EN)


[grammar] ~6-~6: There might be a mistake here.
Context: ...erent search parameters** for each query - Batch processing of search requests - ...

(QB_NEW_EN)


[grammar] ~7-~7: There might be a mistake here.
Context: ... Batch processing of search requests - Performance optimization through paral...

(QB_NEW_EN)


[grammar] ~12-~12: There might be a mistake here.
Context: ...t search queries with various parameters 2. Mixed Filters: Each query can have its...

(QB_NEW_EN)


[grammar] ~13-~13: There might be a mistake here.
Context: ...ry can have its own filtering conditions 3. Different Sorting: Queries can use dif...

(QB_NEW_EN)


[grammar] ~14-~14: There might be a mistake here.
Context: ...ies can use different sorting strategies 4. Batch Results: Process multiple search...

(QB_NEW_EN)


[grammar] ~15-~15: There might be a mistake here.
Context: ...cess multiple search results efficiently 5. Performance: Execute multiple searches...

(QB_NEW_EN)


[grammar] ~20-~20: There might be a mistake here.
Context: ...ultiple widgets requiring different data - Comparison searches: Side-by-side sear...

(QB_NEW_EN)


[grammar] ~21-~21: There might be a mistake here.
Context: ... searches**: Side-by-side search results - Related content: Find related items wi...

(QB_NEW_EN)


[grammar] ~22-~22: There might be a mistake here.
Context: ...nd related items with different criteria - Analytics: Gather multiple search metr...

(QB_NEW_EN)

examples/search/README.md

[grammar] ~1-~1: There might be a mistake here.
Context: ...nning (default: http://localhost:7700) - Valid API key (if authentication is enab...

(QB_NEW_EN)

🪛 markdownlint-cli2 (0.17.2)
examples/chat_stream/README.md

24-24: Multiple headings with the same content

(MD024, no-duplicate-heading)

examples/search/README.md

19-19: Fenced code blocks should have a language specified

(MD040, fenced-code-language)

🔇 Additional comments (11)
examples/chat_stream/main.go (3)

51-66: LGTM on ChatCompletionQuery shape.

Using Messages []*meilisearch.ChatCompletionMessage and Stream: true matches the SDK types shown in this repository. No unsupported fields are present.


1-13: No unused imports detected — build successful

The examples/chat_stream/main.go file builds without any “imported and not used” errors, indicating that all imported packages are currently in use. No pruning of imports is required at this time. Should future refactoring remove the REPL or timeout logic, you can revisit and clean up any now-unused imports.


22-26: Replace broken “Test connection” block with a real version probe
The current snippet references an undefined err and doesn’t actually check the Meilisearch instance. Please replace lines 22–26 with something like:

-   // Test connection
-   fmt.Println("Testing connection to Meilisearch...")
-       log.Fatalf("Failed to setup knowledge base: %v", err)
-   }
+   // Test connection
+   fmt.Println("Testing connection to Meilisearch...")
+   if v, err := client.GetVersion(); err != nil {
+       log.Fatalf("Connection failed: %v\nCheck MEILI_HOST (%s) and MEILI_API_KEY.", err, host)
+   } else {
+       fmt.Printf("Connected to Meilisearch %s\n", v.PackageVersion)
+   }

Please verify that:

  • client.GetVersion() is the correct method on the Meilisearch Go SDK.
  • The returned struct uses a PackageVersion field for the version string.
  • The variables client and host are defined and in scope.

You can confirm via:

#!/usr/bin/env bash
# Verify method exists in SDK (using PCRE for \s)
rg -n 'GetVersion\s*\(' -P -g '!**/vendor/**'
go build ./examples/chat_stream
examples/multi_search/README.md (1)

3-9: Multi-Search support confirmed

  • The example in examples/multi_search/main.go calls client.MultiSearch(multiSearchRequest) (line 74), demonstrating that the SDK implements and exposes MultiSearch.
  • Since this repository is the Go SDK (its root go.mod defines module github.com/meilisearch/meilisearch-go), the example pulls in the local module directly—no additional require entry is needed for compilation.
examples/add_documents/README.md (1)

21-30: Clarify AddDocuments vs UpdateDocuments semantics in examples/add_documents/README.md

Add explicit notes under the “Operations Covered” section to set clear expectations:

  • File: examples/add_documents/README.md
    Lines: 23–24

Suggested diff:

 ## Operations Covered

 - `AddDocuments()` - Add documents to index
+  > Note: Fully replaces existing documents (any fields missing in the new document are removed).
 - `UpdateDocuments()` - Update existing documents
+  > Note: Partially updates (merges) existing documents (fields missing in the new document are preserved).

Please verify these behaviors against the Meilisearch Go SDK version you’re using (check the go.mod in the module containing these examples) to ensure they match your server/SDK version.

examples/create_index_settings/main.go (1)

77-81: Invalid map literal for synonyms (slice type omitted).

In Go, nested slice literals in a map must include the slice type. Current code will not compile.

Apply this diff:

-		Synonyms: map[string][]string{
-			"programming": {"coding", "development"},
-			"javascript":  {"js", "ecmascript"},
-			"golang":      {"go"},
-		},
+		Synonyms: map[string][]string{
+			"programming": []string{"coding", "development"},
+			"javascript":  []string{"js", "ecmascript"},
+			"golang":      []string{"go"},
+		},

Likely an incorrect or invalid review comment.

examples/multi_search/main.go (1)

48-71: LGTM overall; solid multi-search demo and results printing.

Once filterable/sortable settings are added, the example is cohesive and easy to follow. Environment handling and task waits look good.

examples/add_documents/main.go (1)

48-86: Document add flows are clear and correctly synchronized with tasks.

Creation, batch add, single add, and waits are implemented cleanly. Good example ergonomics and messaging.

examples/facet_search/main.go (1)

118-137: Task waits: ctx reuse is correct; overall setup flow looks good.

Index creation, settings update, and document addition are properly synchronized with timeouts. Once the compile-time issues above are fixed, this example should run smoothly.

Also applies to: 147-155

examples/manage_tasks/main.go (2)

191-204: Nice touch with statistics; logic is straightforward and clear.

The aggregation over task statuses is easy to follow and yields useful quick stats for users.

Also applies to: 217-234


20-33: Connectivity check and client setup are clean and consistent across examples.

Using env vars with defaults and IsHealthy() early fail-fast is great for DX.

- Fix duplicate MinWordSizeForTypos line in create_index_settings
- Add missing helper functions (waitForTask, stringPtr, getenv)
- Fix custom ranking rule syntax: desc(rating) instead of rating:desc
- Add admin API key requirement note for task management
- All examples now fully compliant with CodeRabbit AI suggestions
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: 9

♻️ Duplicate comments (6)
examples/manage_tasks/README.md (1)

61-61: Good follow-up: admin key requirement is documented

You addressed the prior review by explicitly noting that listing/filtering tasks generally requires an Admin API key. This prevents common 401/403 confusion when users try with a Search key.

examples/create_index_settings/README.md (1)

39-39: Ranking rule syntax is now correct.

The previous issue about using rating:desc is resolved with desc(rating). LGTM.

examples/chat_stream/README.md (1)

13-17: Relative link fix and self-link removal look good.

Switching to ../search and making “Chat Streaming” plain text resolves the broken links noted earlier.

examples/chat_stream/main.go (2)

1-15: Good: package declaration and required imports are in place.

The previously missing package clause and EOF/error imports are correctly included.


17-23: Good: env-based client configuration and proper Close().

Reading MEILI_HOST/MEILI_API_KEY and deferring client.Close() makes the example safer and reproducible.

examples/multi_search/main.go (1)

119-135: Nice: filterable/sortable attributes configured before running filtered/sorted queries

This addresses the earlier “missing settings” concern; the example will now work when filtering on category/in_stock/price and sorting by price.

🧹 Nitpick comments (22)
examples/manage_tasks/README.md (4)

50-51: Add a short “Prerequisites” section before Configuration

Helps users verify they have the basics (running server, Go toolchain) before exporting env vars.

Apply this diff to insert a concise prerequisites section:

@@
- 
+## Prerequisites
+
+- A running Meilisearch server (local or remote).
+- Go installed (1.20+ recommended).
+- Network access to the MEILI_HOST you configure below.
+
 ## Configuration

25-32: Clarify that the task type list is a subset and version-dependent

Task types can vary across Meilisearch versions; calling this out avoids readers assuming it’s exhaustive.

Apply this diff to add a clarifying note:

 ## Task Types Covered
@@
 - **indexDeletion**: Index deletion operations
+
+Note: This is a commonly used subset. Available task types may vary by Meilisearch version—refer to the official Tasks API documentation for the complete and up‑to‑date list.

16-21: Be explicit about which date fields are filterable

Naming typical date fields improves discoverability when users translate this README to code.

Apply this diff to expand the “Date ranges” bullet:

    - Index UID
-   - Date ranges
+   - Date ranges (e.g., enqueuedAt, startedAt, finishedAt)

69-69: Minor style polish: avoid split infinitive

Slightly smoother phrasing, no change in meaning.

Apply this diff:

-The example will create various tasks, demonstrate different ways to monitor and filter them, and show how to properly handle asynchronous operations in Meilisearch.
+The example will create various tasks, demonstrate different ways to monitor and filter them, and show how to handle asynchronous operations properly in Meilisearch.
examples/create_index_settings/README.md (3)

25-27: Name concrete settings to avoid ambiguity.

Use the actual Meilisearch settings keys so readers can map bullets to code/config precisely.

-   - Search cutoff time
-   - Pagination limits
-   - Faceting configuration
+   - searchCutoffMs (abort long-running searches)
+   - pagination.maxTotalHits (cap total-hits computation)
+   - faceting.maxValuesPerFacet (limit facet buckets)

47-52: Prefer property names to improve reader mapping.

Using the actual settings keys improves copy-pasteability and reduces confusion.

-**Search Enhancement**
+**Search Enhancements**

-- **Stop Words**: Common words ignored in search
-- **Synonyms**: Related terms for better matching
-- **Typo Tolerance**: Configurable typo handling
-- **Distinct Results**: Avoid duplicates by author
+- **stopWords**: Common words ignored in search
+- **synonyms**: Related terms for better matching
+- **typoTolerance**: Configurable typo handling
+- **distinctAttribute (author)**: Avoid duplicates by author

63-69: Add a short note about async tasks and re-runs.

Settings updates are async; the example likely waits on the task. Also help users re-run cleanly if the index already exists.

 ## Running the Example
@@
 go run ./examples/create_index_settings

-The example will create an "articles" index, configure comprehensive settings, add sample articles, and demonstrate how the settings improve search results.
+The example will create an "articles" index, configure comprehensive settings, add sample articles, and demonstrate how the settings improve search results.
+
+Notes:
+- Settings updates are asynchronous in Meilisearch; this example waits for the update task to complete before proceeding.
+- If you re-run the example and the articles index already exists, delete it first (from the Meilisearch dashboard/API) or use a different index UID.


</blockquote></details>
<details>
<summary>examples/chat_stream/README.md (4)</summary><blockquote>

`19-24`: **Clarify enterprise dependency and add quick pointers.**

Consider adding one sentence that this example only works with Meilisearch Enterprise builds that expose the Chat APIs, and a short note to consult the official docs on enabling LLM integration and creating chat workspaces.

---

`25-35`: **Document model/workspace overrides via environment.**

Readers will likely want to choose the chat model and/or a specific workspace. Suggest documenting optional env vars and mirroring them in code:

```diff
 ## Configuration

 The example supports configuration via environment variables:

 ```bash
 # Set Meilisearch server URL (optional, defaults to http://localhost:7700)
 export MEILI_HOST="http://localhost:7700"

 # Set API key (optional, but recommended for production)
 export MEILI_API_KEY="your-api-key"
+
+# (Optional) Select chat model used by the LLM connector
+export MEILI_CHAT_MODEL="gpt-3.5-turbo"
+
+# (Optional) Force a specific chat workspace UID
+export MEILI_WORKSPACE_ID="my-workspace"

---

`46-55`: **Mention the Makefile target as an alternative run path.**

Since the PR adds a Makefile, advertise it alongside go run:

```diff
 ```bash
 # Set environment variables (optional)
 export MEILI_HOST="http://localhost:7700"
 export MEILI_API_KEY="your-api-key"

-# Run the example
+# Run the example
 go run ./examples/chat_stream
+
+# Or via Makefile (from repo root)
+make chat_stream

---

`5-9`: **Polish list style for consistency (optional).**

End each bullet with a period and keep parallel structure for a cleaner read.

```diff
-- **Interactive chat sessions** with streaming responses
-- **Workspace management** and automatic workspace selection
-- **Real-time streaming** with proper EOF handling
-- **Environment-based configuration** for flexible deployment
-- **Graceful error handling** and resource cleanup
+- **Interactive chat sessions** with streaming responses.
+- **Workspace management** and automatic workspace selection.
+- **Real-time streaming** with proper EOF handling.
+- **Environment-based configuration** for flexible deployment.
+- **Graceful error handling** and resource cleanup.
examples/chat_stream/main.go (5)

37-54: Allow overriding workspace via env var.

Make it easy to target a specific workspace non-interactively (CI demos, docs). Minimal change:

 	if err != nil {
 		log.Printf("Warning: could not list chat workspaces: %v", err)
 	} else {
 		fmt.Printf("Found %d chat workspaces\n", len(workspaces.Results))
 		for _, ws := range workspaces.Results {
 			fmt.Printf("  - Workspace: %s\n", ws.UID)
 		}
 		if len(workspaces.Results) > 0 && workspaces.Results[0].UID != "" {
 			workspaceID = workspaces.Results[0].UID
 		}
 	}
+
+	// Optional override from environment
+	if v := os.Getenv("MEILI_WORKSPACE_ID"); v != "" {
+		workspaceID = v
+	}

75-93: Make the model configurable via MEILI_CHAT_MODEL.

Hardcoding "gpt-3.5-turbo" may not match server configuration. Let users set a model name:

 func performChatStream(client meilisearch.ServiceManager, workspaceID string, query string) error {
 	ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
 	defer cancel()
 	
 	// Create a chat completion query with streaming enabled
+	model := getenv("MEILI_CHAT_MODEL", "gpt-3.5-turbo")
 	chatQuery := &meilisearch.ChatCompletionQuery{
-		Model: "gpt-3.5-turbo",
+		Model: model,
 		Messages: []*meilisearch.ChatCompletionMessage{

104-119: Good EOF handling; consider printing all choices per chunk.

errors.Is(err, io.EOF) is the right check. If the SDK can send multiple choices, iterate them to avoid dropping content:

-		// Print the streaming content from choices
-		if chunk != nil && len(chunk.Choices) > 0 {
-			if chunk.Choices[0].Delta.Content != nil && *chunk.Choices[0].Delta.Content != "" {
-				fmt.Print(*chunk.Choices[0].Delta.Content)
-			}
-		}
+		// Print streaming content from all choices (adjust field names if needed)
+		if chunk != nil && len(chunk.Choices) > 0 {
+			for _, choice := range chunk.Choices {
+				if choice.Delta.Content != nil && *choice.Delta.Content != "" {
+					fmt.Print(*choice.Delta.Content)
+				}
+			}
+		}

124-128: Knowledge base setup is a stub—either remove from flow or implement a minimal example.

As-is, setupKnowledgeBase() implies required prep but does nothing. Either:

  • remove the call and keep the example focused on streaming; or
  • add a tiny index with a few docs to ground the demo.

I can draft a minimal KB setup aligned with the search example if helpful.


24-31: Use a context-aware health check with timeout

To prevent the application from hanging if Meilisearch is unreachable, switch from the blocking Health() call to HealthWithContext with a short timeout.

• File: examples/chat_stream/main.go, lines 24–31
• Ensure you import the context and time packages

Suggested diff:

--- a/examples/chat_stream/main.go
+++ b/examples/chat_stream/main.go
@@ -24,7 +24,12 @@ func main() {
 	// Test connection
 	fmt.Println("Testing connection to Meilisearch...")
-	health, err := client.Health()
+	// Use a context with timeout to avoid hanging indefinitely
+	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+	defer cancel()
+	health, err := client.HealthWithContext(ctx)
 	if err != nil {
 		log.Fatalf("Failed to connect to Meilisearch: %v", err)
 	}
examples/multi_search/main.go (3)

88-91: Print key fields for readability instead of raw map dumps

Dumping the entire hit map is noisy. Extract name/price (and fall back to the raw hit if the assertion fails) to make output concise.

-		for j, hit := range result.Hits {
-			fmt.Printf("  %d. %v\n", j+1, hit)
-		}
+		for j, hit := range result.Hits {
+			if m, ok := hit.(map[string]any); ok {
+				name, _ := m["name"].(string)
+				price, _ := m["price"].(float64)
+				fmt.Printf("  %d. %s — $%.2f\n", j+1, name, price)
+			} else {
+				fmt.Printf("  %d. %v\n", j+1, hit)
+			}
+		}

100-106: Minor: hoist the index UID into a package-level const for reuse

Not required, but it avoids repeating the string and reduces typo risk if reused later.

 package main

 import (
@@
 )

+const indexUID = "products"
+
 // Product represents a product document
@@
 func setupProductsIndex(client meilisearch.ServiceManager) error {
 	fmt.Println("Setting up products index...")
-	
-	indexUID := "products"
-	
+
 	// Create index
 	task, err := client.CreateIndex(&meilisearch.IndexConfig{

73-77: Use a context-bound MultiSearch to prevent hanging

The SDK exposes MultiSearchWithContext (see meilisearch_interface.go:116) which your current MultiSearch call delegates to with context.Background(). In CLI examples it’s safer to bound that context with a timeout to avoid indefinite hangs on network issues.

• File: examples/multi_search/main.go (around lines 73–77)
• Update imports to include "context" and "time" if not already present

Suggested diff (optional refactor):

--- a/examples/multi_search/main.go
+++ b/examples/multi_search/main.go
@@ 1,6 import (
+   "context"
+   "time"
    "log"
    "github.com/meilisearch/meilisearch-go"
 )

 func main() {
@@ -70,7 +72,11 @@ func main() {
     // Execute multi-search
-    results, err := client.MultiSearch(multiSearchRequest)
+    ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+    defer cancel()
+    results, err := client.MultiSearchWithContext(
+        ctx,
+        multiSearchRequest,
+    )
     if err != nil {
         log.Fatalf("Multi-search failed: %v", err)
     }
examples/search/README.md (1)

1-3: Add a “Prerequisites” heading and fix minor grammar.

Improves scannability and clears the LanguageTool warning by turning fragments into sentences.

+## Prerequisites
- - Meilisearch server running (default: `http://localhost:7700`)
- - Valid API key (if authentication is enabled)
+ - Meilisearch server running (default: `http://localhost:7700`).
+ - Valid API key (if authentication is enabled).
examples/search/main.go (2)

83-83: Don’t highlight a non-existent field.

AttributesToHighlight includes "overview", but Movie has no Overview field. Remove it or add the field.

Option A (remove):

-		AttributesToHighlight: []string{"title", "overview"},
+		AttributesToHighlight: []string{"title"},

Option B (add to type):

type Movie struct {
	ID       string   `json:"id"`
	Title    string   `json:"title"`
	Year     int      `json:"year"`
	Rating   float64  `json:"rating"`
	Genres   []string `json:"genres"`
	Overview string   `json:"overview"`
}

94-104: Prefer integer counts for facet distribution.

Facet counts are integers; unmarshal into map[string]map[string]int to avoid noisy decimals in output.

-		var facets map[string]map[string]float64
+		var facets map[string]map[string]int
 		if err := json.Unmarshal(searchResult.FacetDistribution, &facets); err != nil {
 			log.Printf("Failed to parse facetDistribution: %v", err)
 		} else {
 			for facet, distribution := range facets {
 				fmt.Printf("  %s: %v\n", facet, distribution)
 			}
 		}
📜 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 ffc404a and 79b5b90.

📒 Files selected for processing (10)
  • examples/chat_stream/README.md (1 hunks)
  • examples/chat_stream/main.go (1 hunks)
  • examples/create_index_settings/README.md (1 hunks)
  • examples/create_index_settings/main.go (1 hunks)
  • examples/facet_search/main.go (1 hunks)
  • examples/manage_tasks/README.md (1 hunks)
  • examples/manage_tasks/main.go (1 hunks)
  • examples/multi_search/main.go (1 hunks)
  • examples/search/README.md (1 hunks)
  • examples/search/main.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • examples/facet_search/main.go
  • examples/manage_tasks/main.go
  • examples/create_index_settings/main.go
🧰 Additional context used
🧬 Code graph analysis (3)
examples/search/main.go (4)
meilisearch.go (1)
  • New (18-41)
options.go (1)
  • WithAPIKey (126-130)
types.go (2)
  • Settings (134-156)
  • SearchRequest (469-499)
hit.go (1)
  • Hits (12-12)
examples/multi_search/main.go (5)
meilisearch.go (1)
  • New (18-41)
options.go (1)
  • WithAPIKey (126-130)
types.go (4)
  • MultiSearchRequest (511-514)
  • SearchRequest (469-499)
  • IndexConfig (90-95)
  • Settings (134-156)
hit.go (1)
  • Hits (12-12)
meilisearch_interface.go (1)
  • ServiceManager (8-82)
examples/chat_stream/main.go (5)
meilisearch.go (1)
  • New (18-41)
options.go (1)
  • WithAPIKey (126-130)
types.go (4)
  • Health (666-668)
  • ListChatWorkSpaceQuery (806-809)
  • ChatCompletionQuery (811-815)
  • ChatCompletionMessage (817-820)
meilisearch_interface.go (1)
  • ServiceManager (8-82)
stream.go (1)
  • Stream (189-195)
🪛 LanguageTool
examples/search/README.md

[grammar] ~1-~1: There might be a mistake here.
Context: ...nning (default: http://localhost:7700) - Valid API key (if authentication is enab...

(QB_NEW_EN)

examples/chat_stream/README.md

[grammar] ~5-~5: There might be a mistake here.
Context: ...chat sessions** with streaming responses - Workspace management and automatic wor...

(QB_NEW_EN)


[grammar] ~6-~6: There might be a mistake here.
Context: ...ment** and automatic workspace selection - Real-time streaming with proper EOF ha...

(QB_NEW_EN)


[grammar] ~7-~7: There might be a mistake here.
Context: ...ime streaming** with proper EOF handling - Environment-based configuration for fl...

(QB_NEW_EN)


[grammar] ~8-~8: There might be a mistake here.
Context: ... configuration** for flexible deployment - Graceful error handling and resource c...

(QB_NEW_EN)


[grammar] ~13-~13: There might be a mistake here.
Context: ...mples ### 📝 Basic Search Basic search functionality with index cre...

(QB_NEW_EN)


[grammar] ~14-~14: There might be a mistake here.
Context: ...nagement, and various search operations. ### 💬 Chat Streaming Interactive chat experi...

(QB_NEW_EN)


[grammar] ~16-~16: There might be a mistake here.
Context: ...arch operations. ### 💬 Chat Streaming Interactive chat experience with streamin...

(QB_NEW_EN)


[grammar] ~17-~17: There might be a mistake here.
Context: ...esponses and knowledge base integration. ## Prerequisites 1. **Meilisearch Enterpris...

(QB_NEW_EN)


[grammar] ~39-~39: There might be a mistake here.
Context: ... Configuration**: Uses MEILI_HOST and MEILI_API_KEY 2. Workspace Discovery: Automatically lis...

(QB_NEW_EN)


[grammar] ~40-~40: There might be a mistake here.
Context: ...y lists and selects available workspaces 3. Interactive Loop: Simple REPL interfac...

(QB_NEW_EN)


[grammar] ~41-~41: There might be a mistake here.
Context: ...mple REPL interface for chat interaction 4. Streaming Chat: Real-time streaming re...

(QB_NEW_EN)


[grammar] ~42-~42: There might be a mistake here.
Context: ...aming responses with proper EOF handling 5. Resource Management: Proper client and...

(QB_NEW_EN)


[grammar] ~43-~43: There might be a mistake here.
Context: ...ment**: Proper client and stream cleanup 6. Error Handling: Graceful error handlin...

(QB_NEW_EN)

examples/create_index_settings/README.md

[grammar] ~5-~5: There might be a mistake here.
Context: ...reation** with primary key specification - Advanced settings configuration for op...

(QB_NEW_EN)


[grammar] ~6-~6: There might be a mistake here.
Context: ...tings** configuration for optimal search - Ranking rules customization - **Attrib...

(QB_NEW_EN)


[grammar] ~7-~7: There might be a mistake here.
Context: ...search - Ranking rules customization - Attribute configuration for search, fi...

(QB_NEW_EN)


[grammar] ~8-~8: There might be a mistake here.
Context: ...ion** for search, filtering, and sorting - Typo tolerance and synonym managem...

(QB_NEW_EN)


[grammar] ~15-~15: There might be a mistake here.
Context: ...nfiguration 3. Attribute Management: - Searchable attributes (search priority) ...

(QB_NEW_EN)


[grammar] ~16-~16: There might be a mistake here.
Context: ... Searchable attributes (search priority) - Displayed attributes (result fields) ...

(QB_NEW_EN)


[grammar] ~17-~17: There might be a mistake here.
Context: ... - Displayed attributes (result fields) - Filterable attributes (filter capabiliti...

(QB_NEW_EN)


[grammar] ~18-~18: There might be a mistake here.
Context: ...terable attributes (filter capabilities) - Sortable attributes (sorting options) 4....

(QB_NEW_EN)


[grammar] ~19-~19: There might be a mistake here.
Context: ... - Sortable attributes (sorting options) 4. Search Enhancement: - Stop words co...

(QB_NEW_EN)


[grammar] ~20-~20: There might be a mistake here.
Context: ...ting options) 4. Search Enhancement: - Stop words configuration - Synonyms f...

(QB_NEW_EN)


[grammar] ~21-~21: There might be a mistake here.
Context: ...ncement**: - Stop words configuration - Synonyms for better matching - Typo t...

(QB_NEW_EN)


[grammar] ~22-~22: There might be a mistake here.
Context: ...ration - Synonyms for better matching - Typo tolerance settings 5. **Performance...

(QB_NEW_EN)


[grammar] ~23-~23: There might be a mistake here.
Context: ...er matching - Typo tolerance settings 5. Performance Settings: - Search cuto...

(QB_NEW_EN)


[grammar] ~24-~24: There might be a mistake here.
Context: ...ce settings 5. Performance Settings: - Search cutoff time - Pagination limit...

(QB_NEW_EN)


[grammar] ~25-~25: There might be a mistake here.
Context: ...ance Settings**: - Search cutoff time - Pagination limits - Faceting configur...

(QB_NEW_EN)


[grammar] ~26-~26: There might be a mistake here.
Context: ...earch cutoff time - Pagination limits - Faceting configuration 6. **Index Inform...

(QB_NEW_EN)


[grammar] ~27-~27: There might be a mistake here.
Context: ...ation limits - Faceting configuration 6. Index Information: Retrieve index meta...

(QB_NEW_EN)


[grammar] ~32-~32: There might be a mistake here.
Context: ...# Settings Configured ### Ranking Rules - words: Matches more words first - **ty...

(QB_NEW_EN)


[grammar] ~41-~41: There might be a mistake here.
Context: ...for rating-based ranking ### Attributes - Searchable: title, content, author, ta...

(QB_NEW_EN)


[grammar] ~42-~42: There might be a mistake here.
Context: ...archable**: title, content, author, tags - Filterable: category, author, featured...

(QB_NEW_EN)


[grammar] ~43-~43: There might be a mistake here.
Context: ...atured, rating, publish_date, word_count - Sortable: publish_date, rating, word_c...

(QB_NEW_EN)


[grammar] ~44-~44: There might be a mistake here.
Context: ...able**: publish_date, rating, word_count - Displayed: id, title, author, category...

(QB_NEW_EN)


[grammar] ~47-~47: There might be a mistake here.
Context: ...rating, featured ### Search Enhancement - Stop Words: Common words ignored in se...

(QB_NEW_EN)


[grammar] ~48-~48: There might be a mistake here.
Context: ... Words**: Common words ignored in search - Synonyms: Related terms for better mat...

(QB_NEW_EN)


[grammar] ~49-~49: There might be a mistake here.
Context: ...yms**: Related terms for better matching - Typo Tolerance: Configurable typo hand...

(QB_NEW_EN)


[grammar] ~50-~50: There might be a mistake here.
Context: ... Tolerance**: Configurable typo handling - Distinct Results: Avoid duplicates by ...

(QB_NEW_EN)

examples/manage_tasks/README.md

[grammar] ~5-~5: There might be a mistake here.
Context: ...sk creation** through various operations - Task monitoring and status tracking - ...

(QB_NEW_EN)


[grammar] ~6-~6: There might be a mistake here.
Context: ... Task monitoring and status tracking - Task filtering by type, status, and in...

(QB_NEW_EN)


[grammar] ~7-~7: There might be a mistake here.
Context: ...k filtering** by type, status, and index - Task statistics and performance monito...

(QB_NEW_EN)


[grammar] ~8-~8: There might be a mistake here.
Context: ... statistics** and performance monitoring - Async operation handling with proper w...

(QB_NEW_EN)


[grammar] ~16-~16: There might be a mistake here.
Context: ... 4. Task Filtering: Filter tasks by: - Task type (documentAdditionOrUpdate, ind...

(QB_NEW_EN)


[grammar] ~17-~17: There might be a mistake here.
Context: ...ntAdditionOrUpdate, indexCreation, etc.) - Status (succeeded, failed, processing, e...

(QB_NEW_EN)


[grammar] ~18-~18: There might be a mistake here.
Context: ...succeeded, failed, processing, enqueued) - Index UID - Date ranges 5. **Task Mon...

(QB_NEW_EN)


[grammar] ~19-~19: There might be a mistake here.
Context: ...ed, processing, enqueued) - Index UID - Date ranges 5. Task Monitoring: Wait...

(QB_NEW_EN)


[grammar] ~20-~20: There might be a mistake here.
Context: ...nqueued) - Index UID - Date ranges 5. Task Monitoring: Wait for task complet...

(QB_NEW_EN)


[grammar] ~27-~27: There might be a mistake here.
Context: ...dexCreation**: Index creation operations - documentAdditionOrUpdate: Document add...

(QB_NEW_EN)


[grammar] ~28-~28: There might be a mistake here.
Context: ...Update**: Document add/update operations - settingsUpdate: Settings configuration...

(QB_NEW_EN)


[grammar] ~29-~29: There might be a mistake here.
Context: ...Update**: Settings configuration changes - documentDeletion: Document deletion op...

(QB_NEW_EN)


[grammar] ~30-~30: There might be a mistake here.
Context: ...Deletion**: Document deletion operations - indexDeletion: Index deletion operatio...

(QB_NEW_EN)


[style] ~69-~69: Try moving the adverb to make the sentence clearer.
Context: ...o monitor and filter them, and show how to properly handle asynchronous operations in Meilisearch. ## Best Practices Show...

(SPLIT_INFINITIVE)

🔇 Additional comments (4)
examples/create_index_settings/README.md (1)

56-57: Confirm default host fallback behavior

Verified that main.go uses getenv("MEILI_HOST", "http://localhost:7700") to fall back to the default URL when MEILI_HOST is unset.

File: examples/create_index_settings/README.md (lines 56–57)

-# Set Meilisearch server URL (optional, defaults to http://localhost:7700)
+# Set Meilisearch server URL (optional; if unset, the example uses http://localhost:7700)
examples/chat_stream/main.go (2)

56-73: Good: simple REPL UX with graceful exit.

The loop is clear and friendly. Trimming input and accepting quit/exit covers common flows.


95-101: Streaming method usage matches SDK interface
Verified that the call in examples/chat_stream/main.go:

stream, err := client.ChatCompletionStreamWithContext(ctx, workspaceID, chatQuery)

exactly matches the interface declaration in chat_interface.go:23:

ChatCompletionStreamWithContext(ctx context.Context, workspace string, query *ChatCompletionQuery) (*Stream[*ChatCompletionStreamChunk], error)

and the underlying implementation in chat.go:14. No changes required.

examples/multi_search/main.go (1)

103-117: Couldn’t locate any Meilisearch-specific error type or helper for “already exists” in the SDK—errors are returned as plain Go errors wrapping the HTTP response. To distinguish a 409 “index already exists” from other failures, you’ll need to inspect the HTTP status code on the underlying response. For example, after calling CreateIndex:

task, err := client.CreateIndex(&meilisearch.IndexConfig{Uid: indexUID, PrimaryKey: "id"})
if err != nil {
    var meiliErr *meilisearch.Error // or the SDK’s error type if named differently
    if errors.As(err, &meiliErr) && meiliErr.StatusCode == http.StatusConflict {
        // index already exists, proceed
        log.Printf("Index %q exists, skipping creation", indexUID)
    } else {
        // some other error—fail fast
        return fmt.Errorf("failed to create index: %w", err)
    }
} else {
    ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
    defer cancel()
    _, err = client.WaitForTaskWithContext(ctx, task.TaskUID, 100*time.Millisecond)
    if err != nil {
        return fmt.Errorf("index creation failed: %w", err)
    }
}

• You’ll need to import “errors” and “net/http”.
• Replace “*meilisearch.Error” with whatever error type the SDK actually returns (inspect in the SDK’s source).
• This branches specifically on 409 Conflict, so other errors aren’t swallowed.

- Updated add_documents/README.md with actual User struct and 8 operations
- Updated chat_stream/README.md with actual interactive chat features
- Updated search/README.md with actual Movie struct and 2 search operations
- Updated multi_search/README.md with actual Product struct and 3 concurrent queries
- Updated create_index_settings/README.md with actual Article index settings
- Updated manage_tasks/README.md with actual 8 task management operations
- Updated facet_search/README.md with actual Book struct and 3 facet operations
- All READMEs now accurately reflect the corresponding main.go implementations
- Added detailed configuration examples and expected outputs
- Included actual function calls, struct definitions, and operation sequences
- Enhanced create_index_settings README with detailed ranking rules explanation
- Expanded manage_tasks README with task filtering and monitoring examples
- Improved facet_search README with advanced filtering patterns and use cases
- Added consistent structure: data models, operations, configuration, expected output
- Included comprehensive code examples and best practices sections
- Standardized formatting and documentation depth across all examples
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: 10

♻️ Duplicate comments (4)
examples/manage_tasks/README.md (1)

163-167: Nice: Admin API key caveat is now documented.

This addresses the earlier review asking to call out that listing/filtering tasks typically requires an Admin API key.

examples/search/README.md (2)

16-24: Fenced Go block and language spec look good.

This addresses the earlier markdownlint complaint about missing fenced code language.


94-101: Code fence properly closed.

The previously reported unclosed fence under “Run the example” is now fixed.

examples/create_index_settings/README.md (1)

55-56: Custom ranking rule syntax looks correct (desc(rating)).

The README now uses the correct Meilisearch syntax desc(rating) instead of rating:desc. Good fix.

🧹 Nitpick comments (37)
examples/manage_tasks/README.md (7)

48-66: Use the taskName parameter (or remove it) and prefer SDK constants for status checks.

taskName is unused; also consider using TaskStatus constants if exposed by the SDK for clarity and typo-safety.

Apply this diff to make taskName useful and simplify the failed-status check:

 func displayTaskInfo(taskName string, task *meilisearch.Task) {
-    fmt.Printf("Task #%d:\n", task.UID)
+    fmt.Printf("Task %q (UID: %d):\n", taskName, task.UID)
@@
-    if task.Status == meilisearch.TaskStatus("failed") {
+    // If your SDK exposes a constant (e.g., meilisearch.TaskStatusFailed), prefer it here:
+    if task.Status == meilisearch.TaskStatus("failed") {
         fmt.Printf("  - Error: %v\n", task.Error)
     }
 }

If the Go SDK exposes constants like meilisearch.TaskStatusFailed, replace the string cast accordingly. Would you like me to verify the current SDK surface and update the snippet?


118-133: Avoid indefinite waits: show a context-aware wait with timeout.

Relying only on a polling interval can block indefinitely if a task stalls. Showing a context-based wait improves resilience.

If supported by your SDK version, consider documenting a context-aware variant alongside the current example:

-finalTask, err := client.WaitForTask(addTask.TaskUID, 100*time.Millisecond)
+// Recommended: context-aware wait with timeout
+ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
+defer cancel()
+finalTask, err := client.WaitForTaskWithContext(ctx, addTask.TaskUID, 100*time.Millisecond)

If WaitForTaskWithContext isn’t available, you can keep the original snippet but add a note about potential long waits and recommend a reasonable timeout.


85-101: Clarify pagination semantics of “From” and show rolling pagination.

In Meilisearch, “From” is a starting task UID, not a zero-based page offset. Showing a rolling “from last UID” example will prevent confusion.

-tasks, err := client.GetTasks(&meilisearch.TasksQuery{
-    Limit: 10,
-    From:  0,
+// From is the starting Task UID (exclusive). Use the last seen UID to paginate.
+tasks, err := client.GetTasks(&meilisearch.TasksQuery{
+    Limit: 10,
+    From:  0, // 0 means "from the beginning"; set to lastTaskUID for next page
@@
-})
+})
+
+// Example rolling pagination
+var all []meilisearch.Task
+var from int64 = 0
+for {
+    page, err := client.GetTasks(&meilisearch.TasksQuery{Limit: 100, From: from})
+    if err != nil || len(page.Results) == 0 {
+        break
+    }
+    all = append(all, page.Results...)
+    from = page.Results[len(page.Results)-1].UID // start after the last UID of this page
+}

Please confirm the exact field names (Results, UID) for the current SDK version.


74-82: Task type list may be incomplete; add a brief caveat and cross-reference.

Depending on Meilisearch version, additional task types (e.g., index swap, snapshot/dump creation) may appear. A short caveat plus a pointer to official task type docs will future-proof the README.

-### **Task Type Categories**
+### **Task Type Categories**
@@
 - **taskDeletion**: Task cleanup operations
+
+Note: The exact set of task types can vary by Meilisearch version (e.g., index swaps, snapshots/dumps). Refer to the official Meilisearch docs for the authoritative, up-to-date list.

Also: “taskCancelation” is intentionally spelled with a single “l” to match the API type; do not change it.


168-177: Consider adding a Makefile target for parity with other examples.

Other examples are runnable via Makefile targets; adding make manage_tasks improves consistency.

 ## Running the Example
@@
 go run ./examples/manage_tasks
+
+# Or via Makefile (if added)
+make manage_tasks

If a target doesn’t exist yet, I can draft the Makefile stanza.


142-152: Provide a concrete “stats” snippet to match the narrative.

You describe duration, success rate, and distribution; adding a compact code sample will make this section actionable.

 ### **Performance Metrics**
 - **Task Duration**: Execution time for completed tasks
 - **Success Rate**: Percentage of succeeded vs failed tasks
 - **Task Distribution**: Count by type and status
 - **Processing Patterns**: Peak times and operation frequencies
@@
 ### **Error Analysis**
 - **Failed Task Details**: Complete error information
 - **Failure Patterns**: Common failure types and causes
 - **Recovery Strategies**: Retry logic and error handling
+
+#### Example: Compute basic stats
+```go
+var total, succeeded, failed int
+distByType := map[meilisearch.TaskType]int{}
+distByStatus := map[meilisearch.TaskStatus]int{}
+var totalDuration time.Duration
+
+for _, t := range allTasks { // from a paginated GetTasks collection
+    total++
+    distByType[t.Type]++
+    distByStatus[t.Status]++
+    if t.Status == meilisearch.TaskStatus("succeeded") {
+        succeeded++
+    } else if t.Status == meilisearch.TaskStatus("failed") {
+        failed++
+    }
+    if t.Duration != "" {
+        if d, err := time.ParseDuration(t.Duration); err == nil {
+            totalDuration += d
+        }
+    }
+}
+fmt.Printf("Success rate: %.1f%% (%d/%d)\n", 100*float64(succeeded)/float64(total), succeeded, total)
+fmt.Printf("Avg duration (succeeded): %s\n", time.Duration(int64(totalDuration)/int64(max(succeeded,1))))
+fmt.Printf("By type: %#v\nBy status: %#v\n", distByType, distByStatus)
+```

If you want, I can align the field names with the exact SDK structs in this repo.


20-31: Prefer a typed struct for documents in Go examples.

Typed models improve IDE support and reduce runtime type surprises versus map[string]interface{}.

-Documents := []map[string]interface{}{
-    {"id": 1, "title": "Task Management Guide", "category": "tutorial"},
-    {"id": 2, "title": "Advanced Meilisearch", "category": "guide"},
-    {"id": 3, "title": "Performance Optimization", "category": "advanced"},
-}
+type Document struct {
+    ID       int    `json:"id"`
+    Title    string `json:"title"`
+    Category string `json:"category"`
+}
+documents := []Document{
+    {ID: 1, Title: "Task Management Guide", Category: "tutorial"},
+    {ID: 2, Title: "Advanced Meilisearch", Category: "guide"},
+    {ID: 3, Title: "Performance Optimization", Category: "advanced"},
+}

If the companion main.go already defines Document, reuse that here.

examples/search/README.md (3)

78-81: Clarify the Go type used for facet distribution.

The README calls searchResult.FacetDistribution a “JSON raw message”. In the Go SDK it’s typically a nested map type (e.g., map[string]map[string]int] or SDK alias). Using the exact type helps readers parse it correctly.

If your code returns a Go map (not json.RawMessage), apply:

-- `searchResult.FacetDistribution`: JSON raw message for facet data
+- `searchResult.FacetDistribution`: map[string]map[string]int (facet counts)

If the SDK returns a different concrete type in your version, replace the above with that exact type.


141-145: Confirm timeout usage; adjust docs or add code accordingly.

The README claims a “10-second timeout for indexing operations.” If context.WithTimeout(..., 10*time.Second) (or equivalent) isn’t present in examples/search/main.go, either add it to the code or remove this bullet to keep docs accurate.

Proposed removal if not implemented:

- - **Timeout Management**: 10-second timeout for indexing operations

Alternatively, I can provide a patch to wrap the task wait with a context.WithTimeout.


92-101: Offer Makefile-based run command (matches PR’s Makefile targets).

README currently only shows go run. Since this PR adds a Makefile target, adding it here improves discoverability.

Apply this insertion after the existing code block:

   go run ./examples/search

+Or using the Makefile:
+
+bash +make search +


</blockquote></details>
<details>
<summary>examples/add_documents/README.md (6)</summary><blockquote>

`74-78`: **Clarify task-waiting helper and timeout semantics.**

The text says operations use `waitForTask()` with a “10-second timeout.” Please make the function name and mechanism explicit and consistent with main.go (SDK’s `WaitForTask` vs your helper `waitForTask`, and whether the timeout comes from `context.WithTimeout`).


```diff
- - **Task Waiting**: All operations wait for completion using `waitForTask()`
+ - **Task Waiting**: All operations wait for completion using a helper `waitForTask(...)` that wraps the SDK’s `WaitForTask`
- - **Timeout Management**: 10-second timeout for task completion
+ - **Timeout Management**: 10-second timeout enforced via `context.WithTimeout` in the helper

If main.go uses a different function name, mirror it here.


103-141: Add a language to the fenced code block for Expected Output.

Markdown linters flag fenced blocks without a language. Use “console” or “text” for terminal output.

-```
+```console
 Testing connection to Meilisearch...
 ✅ Connected to Meilisearch
 ...
 Document management examples completed successfully! 🎉

---

`29-33`: **Be explicit about existing-index handling.**

You mention handling existing indexes “gracefully” but don’t state the behavior. Spell out if you detect and reuse an existing index or catch an “already exists” error and continue.


```diff
- - Handles existing index scenarios gracefully
+ - If the "users" index already exists, the example detects it and reuses the existing index (no-op), otherwise it creates it.

46-48: Tighten phrasing for retrieval bullets.

Minor clarity/readability improvements.

- - **By ID**: Get specific user by ID (User #2)
- - **Bulk Query**: Retrieve multiple documents with pagination
+ - **By ID**: Retrieve a specific user (ID 2)
+ - **Bulk**: Retrieve multiple documents with pagination

81-98: Avoid duplicating environment variable exports.

You show the same MEILI_HOST and MEILI_API_KEY exports in both “Configuration” and “Running the Example.” Consider keeping the definitive snippet in one place and linking to it from the other to reduce maintenance overhead.

 ## Configuration
 ...
 ```bash
 # Set Meilisearch server URL (defaults to http://localhost:7700)
 export MEILI_HOST="http://localhost:7700"
 
 # Set API key (recommended for production)
 export MEILI_API_KEY="your-api-key"

Running the Example

-```bash
-# Set environment variables (optional)
-export MEILI_HOST="http://localhost:7700"
-export MEILI_API_KEY="your-api-key"

-# Run the example
-go run ./examples/add_documents
- +See “Configuration” above for environment variables. Then run: +bash
+go run ./examples/add_documents
+```


---

`89-99`: **Add prerequisites so examples run first-try.**

A short “Prerequisites” note helps new users (e.g., ensure a Meilisearch instance is running).


```diff
 ## Running the Example
+
+### Prerequisites
+Ensure a Meilisearch instance is running and accessible at `$MEILI_HOST`:
+```bash
+docker run -it --rm -p 7700:7700 -e MEILI_MASTER_KEY=$MEILI_API_KEY getmeili/meilisearch:latest
+```
+
 ```bash
 # Set environment variables (optional)
 export MEILI_HOST="http://localhost:7700"
 export MEILI_API_KEY="your-api-key"
 
 # Run the example
 go run ./examples/add_documents

</blockquote></details>
<details>
<summary>examples/multi_search/README.md (7)</summary><blockquote>

`3-3`: **Avoid "multi-index" claim; this example runs all queries against a single index.**

Rephrase to "multiple searches in a single request (multi-search)". Mentioning "multi-index" is misleading unless the example actually includes queries to different indexes.


Apply this diff:

```diff
-This example demonstrates simultaneous multi-index searching using the Meilisearch Go SDK with a product catalog:
+This example demonstrates executing multiple searches in a single request (multi-search) using the Meilisearch Go SDK with a product catalog:

75-86: Budget query either needs an in-stock constraint or adjusted expected output.

With only price < 100, coffee items ($15.99 and $24.99) also match, so expecting only “Wireless Mouse” is inconsistent. Two viable fixes:

  • Add stock constraint to the filter (keeps the expected output).
  • Or keep the filter as-is and update the expected output to list all matching products sorted by price.

Recommend adding an in-stock filter for clarity.

-    Filter:   []string{"price < 100"},
+    Filter:   []string{"price < 100 AND in_stock = true"},

85-87: Align narrative with the updated filter.

If adopting the in-stock constraint above, clarify that expectation reflects in-stock items under $100.

-- **Expected**: Wireless Mouse ($29.99), etc., sorted by price ascending
+- **Expected**: In-stock products under $100 (e.g., Wireless Mouse — $29.99), sorted by price ascending

141-162: Add a language identifier to the fenced code block.

Markdown lint: fenced blocks should specify a language. Use "text" for console-like output.

-```
+```text
 ...
-```
+```

165-169: Verify whether the Go client needs closing.

The canonical Meilisearch Go client typically doesn’t expose Close(); HTTP clients are generally reusable without explicit teardown. If your example code does not define a custom client with Close(), replace this bullet with guidance to reuse a single client instance.

-- **Resource Management**: Proper client cleanup with `defer client.Close()`
+- **Resource Management**: Reuse a single client instance; no explicit close required

90-95: Be precise about server-side concurrency.

“Concurrent execution” might overpromise; multi-search batches multiple queries into one request. Consider softening to “processed together in a single request,” unless you have a source confirming parallel execution within the engine.

-- **Concurrent execution**: Searches run simultaneously on server
+- **Batched execution**: Multiple queries are processed together on the server

120-139: Reduce repetition in env var setup.

You define MEILI_HOST and MEILI_API_KEY in both “Configuration” and “Running the Example.” Consider keeping the detailed export steps in one section and referencing it from the other to avoid drift.

-## Running the Example
-
-```bash
-# Set environment variables (optional)
-export MEILI_HOST="http://localhost:7700"  
-export MEILI_API_KEY="your-api-key"
-
-# Run the multi-search example
-go run ./examples/multi_search
-```
+## Running the Example
+
+```bash
+# After setting the environment variables shown above:
+go run ./examples/multi_search
+```
examples/create_index_settings/README.md (2)

143-146: Clarify stringPtr helper usage.

The snippets use stringPtr("...") but the README doesn’t show the helper. Add a tiny helper function so readers can copy-paste and run without guessing.

You can insert this directly above the settings snippet in the README:

// Helper for pointer fields in settings examples
func stringPtr(s string) *string { return &s }

178-194: Add a language to the “Expected Output” code fence (MD040).

Label the code block to satisfy markdownlint and improve rendering.

-```
+```text
 Testing connection to Meilisearch...
 ✅ Connected to Meilisearch (status: available)
 ...
 Index and settings configuration completed successfully! 🎉

</blockquote></details>
<details>
<summary>examples/chat_stream/README.md (7)</summary><blockquote>

`134-135`: **Grammar: singular “workspace” when count is 1**

Minor copy fix in Expected Output.


```diff
-Found 1 chat workspaces
+Found 1 chat workspace

66-75: Add Windows/PowerShell environment setup

Many users on Windows will benefit from a PowerShell variant alongside the Bash example.

 ## Configuration
@@
 ```bash
 # Set Meilisearch server URL (defaults to http://localhost:7700)
 export MEILI_HOST="http://localhost:7700"
 
 # Set API key (required for Enterprise features)
 export MEILI_API_KEY="your-enterprise-api-key"

+powershell +# Windows PowerShell +$env:MEILI_HOST = "http://localhost:7700" +$env:MEILI_API_KEY = "your-enterprise-api-key" +


---

`76-85`: **Deduplicate env var exports in “Running” and add Makefile target**

Avoid repeating configuration and surface the provided Makefile target for consistency with the PR.


```diff
 ## Running the Example
 
 ```bash
-# Set environment variables
-export MEILI_HOST="http://localhost:7700"
-export MEILI_API_KEY="your-enterprise-api-key"
-
 # Run the interactive chat
 go run ./examples/chat_stream
+
+# Or via Makefile
+make chat_stream

---

`1-10`: **Add cross-link to the basic search example**

A short “See also” improves discoverability of related examples and fixes earlier feedback about linking between examples (using a correct sibling path).


```diff
 # Chat Streaming Example
 
 This example demonstrates interactive chat streaming using the Meilisearch Go SDK with enterprise chat capabilities:
 
+- See also: [Basic Search example](../search)
+
 - **Interactive chat sessions** with streaming responses  
 - **Workspace discovery** and automatic workspace selection
 - **Real-time streaming** with proper EOF handling and content parsing

147-155: Tone down “Production Ready” claim for an example

Examples are great starting points, but “production ready” is a strong claim. Suggest wording that sets expectations while still highlighting best practices.

 - **Interactive Design**: User-friendly REPL interface
-- **Production Ready**: Enterprise-grade chat implementation
+- **Production considerations**: Patterns you can adapt for enterprise chat implementations

17-20: Clarify placeholder functionality for knowledge base setup and stream cleanup

Call out that setupKnowledgeBase is a no-op placeholder and confirm that the code sample shows defer stream.Close() since it’s referenced below, to prevent confusion when readers copy/paste.

If defer stream.Close() is not already shown in the main.go snippet, consider adding a minimal snippet or note here to illustrate it explicitly.

Also applies to: 112-116


61-65: Update README with minimum Meilisearch version for chat streaming

I’ve confirmed that the Go SDK already defines and exposes the required types and methods—ListChatWorkspaces, ChatCompletionQuery, ChatCompletionStreamWithContext, and ChatCompletionMessage—in types.go (lines 811–817), chat_interface.go (lines 21–23), and the example in examples/chat_stream/main.go (e.g. line 96). No API name changes are needed in the code or README.

However, the example README should specify the minimum Meilisearch Enterprise (self-hosted) version that supports the experimental chat-streaming feature. According to the official docs, chat completions are available starting in Meilisearch v1.15.1 (with the chatCompletions experimental feature enabled) (meilisearch.com).

Please update the relevant sections in examples/chat_stream/README.md (lines 21–25, 36–50, and 61–65) to include a prerequisite bullet such as:

- **Meilisearch Enterprise**: Chat functionality requires Meilisearch Enterprise
+ **Meilisearch Enterprise (≥ v1.15.1)**: Chat completions are available from v1.15.1 onward.  
  Enable the experimental chat feature:
  
    curl -X PATCH 'http://localhost:7700/experimental-features/' \
      -H 'Authorization: Bearer <master-key>' \
      -H 'Content-Type: application/json' \
      --data-binary '{"chatCompletions": true}'

This will ensure users know exactly which Meilisearch version to run before using the chat-streaming example.

examples/facet_search/README.md (5)

48-53: Don’t advertise “series” as filterable unless the code actually sets it.

The settings snippet includes series in FilterableAttributes. If Book doesn’t have Series or you don’t seed values, this is misleading and can cause confusion when users facet on a non-existent attribute.

Proposed README fix (if Series is not present in code/documents):

 settingsTask, err := index.UpdateSettings(&meilisearch.Settings{
-    FilterableAttributes: []string{"genre", "language", "publish_year", "rating", "publisher", "in_print", "series"},
+    FilterableAttributes: []string{"genre", "language", "publish_year", "rating", "publisher", "in_print"},
     SortableAttributes:   []string{"rating", "publish_year", "pages"},
 })

55-63: Sync the facet capabilities list with the actual filterable attributes.

If Series isn’t supported/seeded, remove it from the bullets below to avoid 404s/empty facets in UIs.

 - **in_print**: Availability status (true/false)
-- **series**: Book series for collection-based filtering

5-11: Revise “JSON facet parsing” bullet to reflect Go SDK usage.

Since we’re iterating a map (no JSON parsing), update the bullet to avoid instructing readers to unmarshal.

 - **JSON facet parsing** with proper error handling
+ - **Facet distribution printing** (no manual JSON parsing needed)

32-43: Dataset accuracy and consistency (titles/authorship).

  • “The Matrix” is not a book title by “Simulacra”; likely intended “Simulacra and Simulation” by Jean Baudrillard (nonfiction, 1981).
  • “Blade Runner” is the film title; the book is “Do Androids Dream of Electric Sheep?” by Philip K. Dick (1968).

If you want a pure “books” dataset, consider correcting these to actual book titles/authors or swap with other canonical sci‑fi/cyberpunk books to avoid confusing readers.

Example fixes:

- **"The Matrix"** - Simulacra, Sci-Fi, 1999, 4.2 rating, In Print
- **"Blade Runner"** - Philip K. Dick, Cyberpunk, 1968, 4.3 rating, Out of Print
+ **"Simulacra and Simulation"** - Jean Baudrillard, Nonfiction, 1981, 4.2 rating, In Print
+ **"Do Androids Dream of Electric Sheep?"** - Philip K. Dick, Sci-Fi, 1968, 4.3 rating, Out of Print

195-195: Prefer “Example Output” over “Expected Output.”

Results (counts, order) vary with dataset/version/settings. Label this section as an example to set correct expectations.

-### **Expected Output**
+### **Example Output**
📜 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 2616275 and c10d1bf.

📒 Files selected for processing (7)
  • examples/add_documents/README.md (1 hunks)
  • examples/chat_stream/README.md (1 hunks)
  • examples/create_index_settings/README.md (1 hunks)
  • examples/facet_search/README.md (1 hunks)
  • examples/manage_tasks/README.md (1 hunks)
  • examples/multi_search/README.md (1 hunks)
  • examples/search/README.md (1 hunks)
🧰 Additional context used
🪛 LanguageTool
examples/manage_tasks/README.md

[grammar] ~5-~5: There might be a mistake here.
Context: ...* through various Meilisearch operations - Real-time task monitoring with status ...

(QB_NEW_EN)


[grammar] ~6-~6: There might be a mistake here.
Context: ...h status tracking and completion waiting - Advanced task filtering by type, statu...

(QB_NEW_EN)


[grammar] ~7-~7: There might be a mistake here.
Context: ... by type, status, index, and date ranges - Task statistics calculation and perfor...

(QB_NEW_EN)


[grammar] ~8-~8: There might be a mistake here.
Context: ...calculation** and performance monitoring - Asynchronous operation handling with p...

(QB_NEW_EN)


[grammar] ~9-~9: There might be a mistake here.
Context: ...andling** with proper timeout management - Error handling for failed tasks with d...

(QB_NEW_EN)


[grammar] ~14-~14: There might be a mistake here.
Context: ...Operations ### 1. Index Creation Task - Creates "task_demo" index with primary k...

(QB_NEW_EN)


[grammar] ~16-~16: There might be a mistake here.
Context: ... with primary key "id" - Task Type: indexCreation - Expected Status: succeeded (quick op...

(QB_NEW_EN)


[grammar] ~17-~17: There might be a mistake here.
Context: ... Status**: succeeded (quick operation) - Demonstrates basic async operation with ...

(QB_NEW_EN)


[grammar] ~28-~28: There might be a mistake here.
Context: ...y": "advanced"}, } ``` - Task Type: documentAdditionOrUpdate - Expected Status: `succeeded` (with pro...

(QB_NEW_EN)


[grammar] ~29-~29: There might be a mistake here.
Context: ...us**: succeeded (with processing time) - Shows document indexing with task monito...

(QB_NEW_EN)


[grammar] ~39-~39: There might be a mistake here.
Context: ...string{"title"}, } ``` - Task Type: settingsUpdate - Expected Status: `succeeded` (configur...

(QB_NEW_EN)


[grammar] ~40-~40: There might be a mistake here.
Context: ...us**: succeeded (configuration change) - Demonstrates settings modification with ...

(QB_NEW_EN)


[grammar] ~45-~45: There might be a mistake here.
Context: ...n Display ### Individual Task Details For each task, the example displays: ```...

(QB_NEW_EN)


[grammar] ~68-~68: There might be a mistake here.
Context: ...or) } } ``` ### Task Status Types - enqueued: Task queued and waiting for ...

(QB_NEW_EN)


[grammar] ~69-~69: There might be a mistake here.
Context: ...: Task queued and waiting for processing - processing: Task currently being execu...

(QB_NEW_EN)


[grammar] ~70-~70: There might be a mistake here.
Context: ... currently being executed by Meilisearch - succeeded: Task completed successfully...

(QB_NEW_EN)


[grammar] ~71-~71: There might be a mistake here.
Context: ...sk completed successfully without errors - failed: Task failed with error details...

(QB_NEW_EN)


[grammar] ~74-~74: There might be a mistake here.
Context: ...ls available ### Task Type Categories - indexCreation: Index creation and init...

(QB_NEW_EN)


[grammar] ~75-~75: There might be a mistake here.
Context: ...ion**: Index creation and initialization - documentAdditionOrUpdate: Document ind...

(QB_NEW_EN)


[grammar] ~76-~76: There might be a mistake here.
Context: ...rUpdate**: Document indexing and updates - settingsUpdate: Index settings and con...

(QB_NEW_EN)


[grammar] ~77-~77: There might be a mistake here.
Context: ...Index settings and configuration changes - documentDeletion: Document removal ope...

(QB_NEW_EN)


[grammar] ~78-~78: There might be a mistake here.
Context: ...tDeletion**: Document removal operations - indexDeletion: Index deletion operatio...

(QB_NEW_EN)


[grammar] ~79-~79: There might be a mistake here.
Context: ...dexDeletion**: Index deletion operations - taskCancelation: Task cancellation ope...

(QB_NEW_EN)


[grammar] ~80-~80: There might be a mistake here.
Context: ...celation**: Task cancellation operations - taskDeletion: Task cleanup operations ...

(QB_NEW_EN)


[grammar] ~98-~98: There might be a mistake here.
Context: ...number of tasks to retrieve (pagination) - From: Starting task UID for pagination...

(QB_NEW_EN)


[grammar] ~99-~99: There might be a mistake here.
Context: ...From**: Starting task UID for pagination - Statuses: Filter by multiple task stat...

(QB_NEW_EN)


[grammar] ~100-~100: There might be a mistake here.
Context: ...by multiple task statuses simultaneously - Use Case: Monitor tasks across differe...

(QB_NEW_EN)


[grammar] ~112-~112: There might be a mistake here.
Context: ...Types: Filter by specific task types - Use Case: Monitor document-related ope...

(QB_NEW_EN)


[grammar] ~113-~113: There might be a mistake here.
Context: ...document-related operations specifically - Benefits: Focus on relevant operation ...

(QB_NEW_EN)


[grammar] ~134-~134: There might be a mistake here.
Context: ... } } ``` #### WaitForTask Parameters - TaskUID: Unique identifier of task to ...

(QB_NEW_EN)


[grammar] ~135-~135: There might be a mistake here.
Context: ...**: Unique identifier of task to monitor - Interval: Polling interval (100ms for ...

(QB_NEW_EN)


[grammar] ~136-~136: Ensure spelling is correct
Context: ...nitor - Interval: Polling interval (100ms for responsive monitoring) - *Returns...

(QB_NEW_EN_ORTHOGRAPHY_ERROR_IDS_1)


[grammar] ~136-~136: There might be a mistake here.
Context: ...terval (100ms for responsive monitoring) - Returns: Final task state with complet...

(QB_NEW_EN)


[grammar] ~137-~137: There might be a mistake here.
Context: ...Final task state with completion details - Error Handling: Comprehensive error re...

(QB_NEW_EN)


[grammar] ~142-~142: There might be a mistake here.
Context: ... and Analysis ### Performance Metrics - Task Duration: Execution time for comp...

(QB_NEW_EN)


[grammar] ~143-~143: There might be a mistake here.
Context: ...on**: Execution time for completed tasks - Success Rate: Percentage of succeeded ...

(QB_NEW_EN)


[grammar] ~144-~144: There might be a mistake here.
Context: ... Percentage of succeeded vs failed tasks - Task Distribution: Count by type and s...

(QB_NEW_EN)


[grammar] ~145-~145: There might be a mistake here.
Context: ...Distribution**: Count by type and status - Processing Patterns: Peak times and op...

(QB_NEW_EN)


[grammar] ~148-~148: There might be a mistake here.
Context: ...ration frequencies ### Error Analysis - Failed Task Details: Complete error in...

(QB_NEW_EN)


[grammar] ~149-~149: There might be a mistake here.
Context: ...sk Details**: Complete error information - Failure Patterns: Common failure types...

(QB_NEW_EN)


[grammar] ~150-~150: There might be a mistake here.
Context: ...terns**: Common failure types and causes - Recovery Strategies: Retry logic and e...

(QB_NEW_EN)


[grammar] ~163-~163: There might be a mistake here.
Context: ...API key has appropriate permissions for: - Task listing and filtering - Task status...

(QB_NEW_EN)


[grammar] ~164-~164: There might be a mistake here.
Context: ...ssions for: - Task listing and filtering - Task status monitoring - Task cancella...

(QB_NEW_EN)


[grammar] ~165-~165: There might be a mistake here.
Context: ...g and filtering - Task status monitoring - Task cancellation (if needed) ## Runnin...

(QB_NEW_EN)

examples/create_index_settings/README.md

[grammar] ~5-~5: There might be a mistake here.
Context: ...primary key specification and validation - Advanced settings configuration for op...

(QB_NEW_EN)


[grammar] ~6-~6: There might be a mistake here.
Context: ...uration** for optimal search performance - Custom ranking rules for relevance fin...

(QB_NEW_EN)


[grammar] ~7-~7: There might be a mistake here.
Context: ...anking rules** for relevance fine-tuning - Comprehensive attribute configuration ...

(QB_NEW_EN)


[grammar] ~8-~8: There might be a mistake here.
Context: ...ion** for search, filtering, and sorting - Typo tolerance settings with configura...

(QB_NEW_EN)


[grammar] ~9-~9: There might be a mistake here.
Context: ... settings** with configurable thresholds - Stop words and synonyms for enhanced s...

(QB_NEW_EN)


[grammar] ~10-~10: There might be a mistake here.
Context: ...d synonyms** for enhanced search quality - Task monitoring with proper completion...

(QB_NEW_EN)


[grammar] ~34-~34: There might be a mistake here.
Context: ...The example includes 3 diverse articles: - "Getting Started with Meilisearch" - T...

(QB_NEW_EN)


[grammar] ~35-~35: There might be a mistake here.
Context: ...hn Doe, Rating: 4.5, 750 words, Featured - "Advanced Search Techniques" - Technol...

(QB_NEW_EN)


[grammar] ~36-~36: There might be a mistake here.
Context: ...h, Rating: 4.8, 1200 words, Not Featured - "Building Modern Applications" - Devel...

(QB_NEW_EN)


[grammar] ~41-~41: There might be a mistake here.
Context: ...s Configuration ### 1. Index Creation - Creates "articles" index with "id" as pr...

(QB_NEW_EN)


[grammar] ~42-~42: There might be a mistake here.
Context: ...articles" index with "id" as primary key - Validates index creation with task compl...

(QB_NEW_EN)


[grammar] ~43-~43: There might be a mistake here.
Context: ...ex creation with task completion waiting - Displays success confirmation with detai...

(QB_NEW_EN)


[grammar] ~59-~59: There might be a mistake here.
Context: ... } ``` #### Ranking Rule Explanation: - words: Articles matching more query wo...

(QB_NEW_EN)


[grammar] ~74-~74: There might be a mistake here.
Context: ...riority - matches in titles rank highest - content: Main content searchability - ...

(QB_NEW_EN)


[grammar] ~75-~75: There might be a mistake here.
Context: ... content: Main content searchability - author: Author name searching - **tags...

(QB_NEW_EN)


[grammar] ~76-~76: There might be a mistake here.
Context: ...lity - author: Author name searching - tags: Tag-based search capabilities #...

(QB_NEW_EN)


[grammar] ~90-~90: There might be a mistake here.
Context: ...category (Technology, Development, etc.) - author: Filter by specific authors - *...

(QB_NEW_EN)


[grammar] ~91-~91: There might be a mistake here.
Context: ...- author: Filter by specific authors - featured: Filter featured vs regular a...

(QB_NEW_EN)


[grammar] ~92-~92: There might be a mistake here.
Context: ...d**: Filter featured vs regular articles - rating: Numeric range filtering (ratin...

(QB_NEW_EN)


[grammar] ~93-~93: There might be a mistake here.
Context: ...: Numeric range filtering (rating > 4.0) - publish_date: Date-based filtering - *...

(QB_NEW_EN)


[grammar] ~94-~94: There might be a mistake here.
Context: ...- publish_date: Date-based filtering - word_count: Length-based filtering ##...

(QB_NEW_EN)


[grammar] ~123-~123: There might be a mistake here.
Context: ...xpands search queries with related terms - Improves search recall for technical ter...

(QB_NEW_EN)


[grammar] ~146-~146: There might be a mistake here.
Context: ... one result per author in search results - Prevents author over-representation in r...

(QB_NEW_EN)

examples/chat_stream/README.md

[grammar] ~5-~5: There might be a mistake here.
Context: ...chat sessions** with streaming responses - Workspace discovery and automatic work...

(QB_NEW_EN)


[grammar] ~6-~6: There might be a mistake here.
Context: ...very** and automatic workspace selection - Real-time streaming with proper EOF ha...

(QB_NEW_EN)


[grammar] ~7-~7: There might be a mistake here.
Context: ... proper EOF handling and content parsing - Environment-based configuration for fl...

(QB_NEW_EN)


[grammar] ~8-~8: There might be a mistake here.
Context: ... configuration** for flexible deployment - Graceful error handling and comprehens...

(QB_NEW_EN)


[grammar] ~13-~13: There might be a mistake here.
Context: ...at Features ### 1. Connection Testing - Tests connection to Meilisearch server w...

(QB_NEW_EN)


[grammar] ~14-~14: There might be a mistake here.
Context: ... to Meilisearch server with health check - Displays server health status for verifi...

(QB_NEW_EN)


[grammar] ~17-~17: There might be a mistake here.
Context: ...ification ### 2. Knowledge Base Setup - Initializes basic knowledge base (placeh...

(QB_NEW_EN)


[grammar] ~18-~18: There might be a mistake here.
Context: ... (placeholder for actual implementation) - Sets up foundation for chat functionalit...

(QB_NEW_EN)


[grammar] ~21-~21: There might be a mistake here.
Context: ...ctionality ### 3. Workspace Discovery - Lists available chat workspaces using ...

(QB_NEW_EN)


[grammar] ~22-~22: There might be a mistake here.
Context: ...Lists available chat workspaces** using ListChatWorkspaces() - Auto-selects workspace: Uses first ava...

(QB_NEW_EN)


[grammar] ~26-~26: There might be a mistake here.
Context: ... UIDs ### 4. Interactive Chat Session - REPL Interface: Read-Eval-Print Loop f...

(QB_NEW_EN)


[grammar] ~27-~27: There might be a mistake here.
Context: ...al-Print Loop for continuous interaction - User Input: Accepts natural language q...

(QB_NEW_EN)


[grammar] ~28-~28: There might be a mistake here.
Context: ...ut**: Accepts natural language questions - Exit Commands: Type 'quit' or 'exit' t...

(QB_NEW_EN)


[grammar] ~29-~29: There might be a mistake here.
Context: ...**: Type 'quit' or 'exit' to end session - Streaming Responses: Real-time streami...

(QB_NEW_EN)


[grammar] ~54-~54: There might be a mistake here.
Context: ...roper errors.Is(err, io.EOF) detection - Content parsing: Extracts content from...

(QB_NEW_EN)


[grammar] ~55-~55: There might be a mistake here.
Context: ...ontent parsing**: Extracts content from chunk.Choices[0].Delta.Content - Pointer handling: Safely dereferences ...

(QB_NEW_EN)


[grammar] ~56-~56: There might be a mistake here.
Context: ...**: Safely dereferences content pointers - Real-time display: Prints streaming co...

(QB_NEW_EN)


[grammar] ~117-~117: There might be a mistake here.
Context: ... actual errors ### Content Processing - Null checks: Validates `chunk != nil &...

(QB_NEW_EN)


[grammar] ~118-~118: There might be a mistake here.
Context: ...ocessing** - Null checks: Validates chunk != nil && len(chunk.Choices) > 0 - Content validation: Checks for non-emp...

(QB_NEW_EN)


[grammar] ~119-~119: There might be a mistake here.
Context: ...ks for non-empty content before printing - Pointer handling: Safely dereferences ...

(QB_NEW_EN)


[grammar] ~122-~122: There might be a mistake here.
Context: ...lta.Content` ### Interactive Features - Health Check: Verifies server availabi...

(QB_NEW_EN)


[grammar] ~123-~123: There might be a mistake here.
Context: ...ck**: Verifies server availability with client.Health() - Workspace Listing: Discovers available...

(QB_NEW_EN)


[grammar] ~124-~124: There might be a mistake here.
Context: ...overs available workspaces automatically - REPL Loop: Continuous interaction unti...

(QB_NEW_EN)


[grammar] ~125-~125: There might be a mistake here.
Context: ...nuous interaction until 'quit' or 'exit' - Graceful Exit: Clean shutdown with pro...

(QB_NEW_EN)


[grammar] ~149-~149: There might be a mistake here.
Context: ...ation**: Flexible host and API key setup - Resource Management: Proper client and...

(QB_NEW_EN)


[grammar] ~150-~150: There might be a mistake here.
Context: ...ment**: Proper client and stream cleanup - Timeout Handling: Appropriate timeouts...

(QB_NEW_EN)


[grammar] ~151-~151: There might be a mistake here.
Context: ...Appropriate timeouts for chat operations - Error Handling: Graceful error handlin...

(QB_NEW_EN)


[grammar] ~152-~152: There might be a mistake here.
Context: ...error handling with informative messages - Interactive Design: User-friendly REPL...

(QB_NEW_EN)


[grammar] ~153-~153: There might be a mistake here.
Context: ...e Design**: User-friendly REPL interface - Production Ready: Enterprise-grade cha...

(QB_NEW_EN)

examples/add_documents/README.md

[grammar] ~46-~46: There might be a mistake here.
Context: ... 5. Document Retrieval - By ID: Get specific user by ID (User #2) - **Bulk ...

(QB_NEW_EN)


[grammar] ~65-~65: There might be a mistake here.
Context: ...nts - AddDocuments([]User{newUser}) - Add single User document - `UpdateDocuments...

(QB_NEW_EN)


[grammar] ~69-~69: There might be a mistake here.
Context: ...th pagination - DeleteDocument("4") - Delete single User by ID - `DeleteDocuments([]...

(QB_NEW_EN)


[grammar] ~74-~74: There might be a mistake here.
Context: ...ll operations wait for completion using waitForTask() - Task Monitoring: Displays task IDs for...

(QB_NEW_EN)


[grammar] ~75-~75: There might be a mistake here.
Context: ...toring**: Displays task IDs for tracking - Error Handling: Graceful handling of t...

(QB_NEW_EN)


[grammar] ~76-~76: There might be a mistake here.
Context: ...ng**: Graceful handling of task failures - Timeout Management: 10-second timeout ...

(QB_NEW_EN)

examples/facet_search/README.md

[grammar] ~5-~5: There might be a mistake here.
Context: ...tion analysis** alongside search results - Multi-facet filtering with complex boo...

(QB_NEW_EN)


[grammar] ~6-~6: There might be a mistake here.
Context: ...t filtering** with complex boolean logic - Facet-specific searches for targeted f...

(QB_NEW_EN)


[grammar] ~7-~7: There might be a mistake here.
Context: ...earches** for targeted facet exploration - Advanced filter combinations with cate...

(QB_NEW_EN)


[grammar] ~8-~8: There might be a mistake here.
Context: ... with category, rating, and date filters - Comprehensive book catalog with rich f...

(QB_NEW_EN)


[grammar] ~9-~9: There might be a mistake here.
Context: ...catalog** with rich facetable attributes - JSON facet parsing with proper error h...

(QB_NEW_EN)


[grammar] ~34-~34: There might be a mistake here.
Context: ... 8 diverse books across multiple genres: - "The Hobbit" - J.R.R. Tolkien, Fantasy...

(QB_NEW_EN)


[grammar] ~35-~35: There might be a mistake here.
Context: ...ien, Fantasy, 1937, 4.8 rating, In Print - "Dune" - Frank Herbert, Sci-Fi, 1965, ...

(QB_NEW_EN)


[grammar] ~36-~36: There might be a mistake here.
Context: ...bert, Sci-Fi, 1965, 4.6 rating, In Print - "1984" - George Orwell, Fiction, 1949,...

(QB_NEW_EN)


[grammar] ~37-~37: There might be a mistake here.
Context: ...ell, Fiction, 1949, 4.7 rating, In Print - "Foundation" - Isaac Asimov, Sci-Fi, 1...

(QB_NEW_EN)


[grammar] ~38-~38: There might be a mistake here.
Context: ..., Sci-Fi, 1951, 4.5 rating, Out of Print - "Neuromancer" - William Gibson, Cyberp...

(QB_NEW_EN)


[grammar] ~39-~39: There might be a mistake here.
Context: ...n, Cyberpunk, 1984, 4.4 rating, In Print - "The Matrix" - Simulacra, Sci-Fi, 1999...

(QB_NEW_EN)


[grammar] ~40-~40: There might be a mistake here.
Context: ...acra, Sci-Fi, 1999, 4.2 rating, In Print - "Blade Runner" - Philip K. Dick, Cyber...

(QB_NEW_EN)


[grammar] ~41-~41: There might be a mistake here.
Context: ...yberpunk, 1968, 4.3 rating, Out of Print - "Snow Crash" - Neal Stephenson, Cyberp...

(QB_NEW_EN)


[grammar] ~58-~58: There might be a mistake here.
Context: ...ar of publication for temporal filtering - rating: Numeric rating for quality-bas...

(QB_NEW_EN)


[grammar] ~59-~59: There might be a mistake here.
Context: ...meric rating for quality-based filtering - publisher: Publishing house for brand-...

(QB_NEW_EN)


[grammar] ~60-~60: There might be a mistake here.
Context: ...blishing house for brand-based filtering - in_print: Availability status (true/fa...

(QB_NEW_EN)


[grammar] ~61-~61: There might be a mistake here.
Context: ...rint**: Availability status (true/false) - series: Book series for collection-bas...

(QB_NEW_EN)


[grammar] ~106-~106: There might be a mistake here.
Context: ...0, }) ``` #### Advanced Filter Syntax - Boolean Logic: AND, `OR` operators f...

(QB_NEW_EN)


[grammar] ~107-~107: There might be a mistake here.
Context: ..., ORoperators for complex conditions - **Comparison Operators**:>, <, >=`, ...

(QB_NEW_EN)


[grammar] ~109-~109: There might be a mistake here.
Context: ..., <=, =, != - Numeric Ranges: rating > 4.0 AND rating < 5.0 - String Matching: genre = "fantasy" (...

(QB_NEW_EN)


[grammar] ~110-~110: There might be a mistake here.
Context: ...ing**: genre = "fantasy" (exact match) - Multiple Conditions: `genre = fantasy ...

(QB_NEW_EN)


[grammar] ~122-~122: There might be a mistake here.
Context: ...", }) ``` #### FacetSearch Parameters - FacetName: Target facet attribute ("ge...

(QB_NEW_EN)


[grammar] ~123-~123: There might be a mistake here.
Context: ...acet attribute ("genre", "author", etc.) - FacetQuery: Search within facet values...

(QB_NEW_EN)


[grammar] ~128-~128: There might be a mistake here.
Context: ...earch #### Use Cases for Facet Search - Auto-complete: Suggest genre names as ...

(QB_NEW_EN)


[grammar] ~129-~129: There might be a mistake here.
Context: ...nre names as user types "sci" → "sci-fi" - Facet Exploration: Discover available ...

(QB_NEW_EN)


[grammar] ~130-~130: There might be a mistake here.
Context: ...Discover available values within a facet - Contextual Faceting: Find facet values...

(QB_NEW_EN)


[grammar] ~131-~131: There might be a mistake here.
Context: ... facet values relevant to current search - Facet Validation: Check if specific fa...

(QB_NEW_EN)


[grammar] ~136-~136: There might be a mistake here.
Context: ...bution Benefits ### Search Refinement - Category Counts: "Show 15 sci-fi books...

(QB_NEW_EN)


[grammar] ~142-~142: There might be a mistake here.
Context: ...lters ### User Experience Enhancement - Interactive Filtering: Click facet val...

(QB_NEW_EN)

examples/multi_search/README.md

[grammar] ~5-~5: There might be a mistake here.
Context: ...hes** with different queries and filters - Single API call for multiple search op...

(QB_NEW_EN)


[grammar] ~6-~6: There might be a mistake here.
Context: ...PI call** for multiple search operations - Product index setup with comprehensive...

(QB_NEW_EN)


[grammar] ~7-~7: There might be a mistake here.
Context: ...setup** with comprehensive configuration - Filter combinations with category, sto...

(QB_NEW_EN)


[grammar] ~8-~8: There might be a mistake here.
Context: ...category, stock status, and price ranges - Sorting operations with price-based or...

(QB_NEW_EN)


[grammar] ~9-~9: There might be a mistake here.
Context: ...g operations** with price-based ordering - Performance optimization through batch...

(QB_NEW_EN)


[grammar] ~31-~31: There might be a mistake here.
Context: ...The example includes 6 diverse products: - Gaming Laptop - TechBrand, $1299.99, E...

(QB_NEW_EN)


[grammar] ~32-~32: There might be a mistake here.
Context: ...chBrand, $1299.99, Electronics, In Stock - Organic Coffee - CoffeeCorp, $15.99, F...

(QB_NEW_EN)


[grammar] ~33-~33: There might be a mistake here.
Context: ...- CoffeeCorp, $15.99, Food, Out of Stock - Wireless Mouse - TechBrand, $29.99, El...

(QB_NEW_EN)


[grammar] ~34-~34: There might be a mistake here.
Context: ...TechBrand, $29.99, Electronics, In Stock - Coffee Beans - CoffeeCorp, $24.99, Foo...

(QB_NEW_EN)


[grammar] ~35-~35: There might be a mistake here.
Context: ...- CoffeeCorp, $24.99, Food, Out of Stock - Bluetooth Headphones - AudioTech, $199...

(QB_NEW_EN)


[grammar] ~36-~36: There might be a mistake here.
Context: ...udioTech, $199.99, Electronics, In Stock - Desk Chair - FurniturePlus, $249.99, F...

(QB_NEW_EN)


[grammar] ~41-~41: There might be a mistake here.
Context: ...-Search Operations ### 1. Index Setup - Creates "products" index with "id" as pr...

(QB_NEW_EN)


[grammar] ~43-~43: There might be a mistake here.
Context: ...rimary key - Filterable attributes: ["category", "in_stock", "price", "brand"] - Sortable attributes: ["price"] - Wai...

(QB_NEW_EN)


[grammar] ~44-~44: There might be a mistake here.
Context: ...", "brand"]- **Sortable attributes**:["price"]` - Waits for settings configuration before ...

(QB_NEW_EN)


[grammar] ~60-~60: There might be a mistake here.
Context: ...``` - Purpose: Find laptop products in electronics category - Expected: Ga...

(QB_NEW_EN)


[grammar] ~90-~90: There might be a mistake here.
Context: ...h Benefits ### Performance Advantages - Single API call: Reduces network round...

(QB_NEW_EN)


[grammar] ~92-~92: There might be a mistake here.
Context: ...xecution**: Searches run simultaneously on server - Reduced latency: No sequen...

(QB_NEW_EN)


[grammar] ~96-~96: There might be a mistake here.
Context: ...tilization ### Use Cases Demonstrated - Category-based filtering: Electronics ...

(QB_NEW_EN)


[grammar] ~97-~97: There might be a mistake here.
Context: ...ring**: Electronics vs Food vs Furniture - Stock status filtering: Available vs O...

(QB_NEW_EN)


[grammar] ~98-~98: There might be a mistake here.
Context: ...s filtering**: Available vs Out of Stock - Price range filtering: Budget-consciou...

(QB_NEW_EN)


[grammar] ~99-~99: There might be a mistake here.
Context: ...e filtering**: Budget-conscious shopping - Sorting integration: Price-based produ...

(QB_NEW_EN)


[grammar] ~100-~100: There might be a mistake here.
Context: ...egration**: Price-based product ordering - Mixed query types: Text search vs filt...

(QB_NEW_EN)


[grammar] ~113-~113: There might be a mistake here.
Context: ...lts ``` ### Individual Result Display For each search result: - **Query identi...

(QB_NEW_EN)


[grammar] ~114-~114: There might be a mistake here.
Context: ...Result Display** For each search result: - Query identification: Shows search que...

(QB_NEW_EN)


[grammar] ~168-~168: There might be a mistake here.
Context: ...anagement**: Proper client cleanup with defer client.Close() - Filter Syntax: Proper filter expressio...

(QB_NEW_EN)

examples/search/README.md

[grammar] ~5-~5: There might be a mistake here.
Context: ...reation** with primary key specification - Settings configuration for optimal sea...

(QB_NEW_EN)


[grammar] ~6-~6: There might be a mistake here.
Context: ...uration** for optimal search performance - Document indexing with movie data - **...

(QB_NEW_EN)


[grammar] ~7-~7: There might be a mistake here.
Context: ... - Document indexing with movie data - Simple text search with basic queries ...

(QB_NEW_EN)


[grammar] ~8-~8: There might be a mistake here.
Context: ...Simple text search* with basic queries - Advanced search with filters, facets, ...

(QB_NEW_EN)


[grammar] ~9-~9: There might be a mistake here.
Context: ...* with filters, facets, and highlighting - Facet distribution parsing and display...

(QB_NEW_EN)


[grammar] ~28-~28: There might be a mistake here.
Context: ... The example includes 5 classic movies: - The Dark Knight (2008) - Action, Crime...

(QB_NEW_EN)


[grammar] ~29-~29: There might be a mistake here.
Context: ...08) - Action, Crime, Drama - Rating: 9.0 - Inception (2010) - Action, Sci-Fi, Thr...

(QB_NEW_EN)


[grammar] ~30-~30: There might be a mistake here.
Context: ...- Action, Sci-Fi, Thriller - Rating: 8.8 - The Godfather (1972) - Crime, Drama - ...

(QB_NEW_EN)


[grammar] ~31-~31: There might be a mistake here.
Context: ...er** (1972) - Crime, Drama - Rating: 9.2 - Pulp Fiction (1994) - Crime, Drama - R...

(QB_NEW_EN)


[grammar] ~32-~32: There might be a mistake here.
Context: ...on** (1994) - Crime, Drama - Rating: 8.9 - Fight Club (1999) - Drama - Rating: 8....

(QB_NEW_EN)


[grammar] ~37-~37: There might be a mistake here.
Context: ...tions Demonstrated ### 1. Index Setup - Creates "movies" index with "id" as prim...

(QB_NEW_EN)


[grammar] ~43-~43: There might be a mistake here.
Context: ...ore indexing ### 2. Document Indexing - Adds 5 movie documents to the index - Us...

(QB_NEW_EN)


[grammar] ~49-~49: There might be a mistake here.
Context: ...ion with task ID ### 3. Simple Search - Query: "action" - Results: Movies...

(QB_NEW_EN)


[grammar] ~50-~50: There might be a mistake here.
Context: ...3. Simple Search** - Query: "action" - Results: Movies containing "action" in...

(QB_NEW_EN)


[grammar] ~51-~51: There might be a mistake here.
Context: ... Movies containing "action" in any field - Limit: 5 results maximum - Display...

(QB_NEW_EN)


[grammar] ~52-~52: There might be a mistake here.
Context: ...any field - Limit: 5 results maximum - Display: Shows movie title, year, and ...

(QB_NEW_EN)


[grammar] ~55-~55: There might be a mistake here.
Context: ...g ### 4. Advanced Search with Filters - Query: "drama" - Filter: `year > 1...

(QB_NEW_EN)


[grammar] ~56-~56: There might be a mistake here.
Context: ...arch with Filters** - Query: "drama" - Filter: year > 1990 (movies after 19...

(QB_NEW_EN)


[grammar] ~57-~57: There might be a mistake here.
Context: ...ter**: year > 1990 (movies after 1990) - Facets: ["genres", "year"] for distr...

(QB_NEW_EN)


[grammar] ~58-~58: There might be a mistake here.
Context: ...res", "year"]` for distribution analysis - Highlighting: Highlights matches in ti...

(QB_NEW_EN)


[grammar] ~59-~59: There might be a mistake here.
Context: ...Highlights matches in title and overview - Limit: 10 results maximum ### **5. Fa...

(QB_NEW_EN)


[grammar] ~62-~62: There might be a mistake here.
Context: ...um ### 5. Facet Distribution Analysis - Parses FacetDistribution JSON response...

(QB_NEW_EN)


[grammar] ~63-~63: There might be a mistake here.
Context: ...Parses FacetDistribution JSON response - Shows genre and year distribution statis...

(QB_NEW_EN)


[grammar] ~64-~64: There might be a mistake here.
Context: ...s genre and year distribution statistics - Handles JSON parsing errors gracefully -...

(QB_NEW_EN)


[grammar] ~65-~65: There might be a mistake here.
Context: ...- Handles JSON parsing errors gracefully - Displays facet counts for search results...

(QB_NEW_EN)


[grammar] ~71-~71: There might be a mistake here.
Context: ...er: Filter expression ("year > 1990") - Facets: Facet fields for distribution (["genr...

(QB_NEW_EN)


[grammar] ~72-~72: There might be a mistake here.
Context: ... for distribution (["genres", "year"]) - AttributesToHighlight: Fields to highlight (`["title", "overv...

(QB_NEW_EN)


[grammar] ~73-~73: There might be a mistake here.
Context: ...s to highlight (["title", "overview"]) - Limit: Maximum number of results (5, 10) ###...

(QB_NEW_EN)


[grammar] ~76-~76: There might be a mistake here.
Context: ...sults (5, 10) ### Response Processing - searchResult.Hits: Array of matching documents - `searchR...

(QB_NEW_EN)


[grammar] ~77-~77: There might be a mistake here.
Context: ...esult.Hits: Array of matching documents - searchResult.FacetDistribution`: JSON raw message for facet data - Erro...

(QB_NEW_EN)


[grammar] ~78-~78: There might be a mistake here.
Context: ...bution`: JSON raw message for facet data - Error handling for search operations - T...

(QB_NEW_EN)


[grammar] ~79-~79: There might be a mistake here.
Context: ...a - Error handling for search operations - Type conversion for numeric fields (`hit...

(QB_NEW_EN)


[grammar] ~133-~133: There might be a mistake here.
Context: ...anagement**: Proper client cleanup with defer client.Close() - Facet Processing: Safe JSON unmarshall...

(QB_NEW_EN)


[grammar] ~141-~141: There might be a mistake here.
Context: ...0-second timeout for indexing operations - Settings First: Apply index settings b...

(QB_NEW_EN)


[grammar] ~142-~142: There might be a mistake here.
Context: ...y index settings before adding documents - Batch Operations: Efficient bulk docum...

(QB_NEW_EN)


[grammar] ~143-~143: There might be a mistake here.
Context: ...ions**: Efficient bulk document indexing - Type Safety: Proper type conversion fo...

(QB_NEW_EN)


[grammar] ~144-~144: There might be a mistake here.
Context: ...roper type conversion for search results - JSON Handling: Safe parsing of facet d...

(QB_NEW_EN)

🪛 markdownlint-cli2 (0.17.2)
examples/create_index_settings/README.md

89-89: Fenced code blocks should have a language specified

(MD040, fenced-code-language)

examples/add_documents/README.md

103-103: Fenced code blocks should have a language specified

(MD040, fenced-code-language)

examples/multi_search/README.md

142-142: Fenced code blocks should have a language specified

(MD040, fenced-code-language)

🔇 Additional comments (6)
examples/search/README.md (1)

130-136: Verify “client.Close()” guidance; remove if the SDK client doesn’t require closing.

Many HTTP-based clients don’t expose Close(). If your example code doesn’t actually call client.Close(), this bullet will mislead users.

Apply if not applicable:

- - **Resource Management**: Proper client cleanup with `defer client.Close()`

If there is a custom client with Close(), consider linking to the code line or briefly noting why it’s needed (e.g., streaming connections).

examples/add_documents/README.md (2)

1-11: Overall: clear, practical walkthrough.

Good structure and coverage of the full document lifecycle, with task-waiting and error-handling called out. Once the small inconsistencies and lint nits above are addressed, this will be very solid developer-facing documentation.


64-71: No discrepancies between README and main.go found. The method names (AddDocuments, UpdateDocuments, GetDocument, GetDocuments, DeleteDocument, DeleteDocuments) and the DocumentsQuery type, as well as string ID parameters, all match exactly what’s used in examples/add_documents/main.go. No updates are needed.

examples/multi_search/README.md (2)

146-159: Expected output for Query 3 must reflect the chosen fix.

  • If you add in_stock = true, “Found 1 results: Wireless Mouse …” is correct.
  • If you keep only price < 100, this section should list all matching products (Coffee items and Wireless Mouse), sorted ascending.

Ensure the README matches the code and dataset to avoid confusion.


41-46: LGTM: Good emphasis on configuring filterable/sortable attributes and waiting for tasks.

Accurately reflects best practice for Meilisearch settings before searching.

examples/create_index_settings/README.md (1)

72-73: Update README examples to use plain slices for attribute settings

The README snippets for SearchableAttributes (lines 72–73) and DisplayedAttributes (lines 81–82) currently use pointer-to-slice literals (&[]string{…}), but the Go SDK’s Settings struct defines these fields as plain []string. Copy-pasting the current examples will result in a type mismatch (you cannot assign a *[]string to a []string field).

Please update the examples in examples/create_index_settings/README.md as follows:

  • Lines 72–73:

    -SearchableAttributes: &[]string{"title", "content", "author", "tags"}
    +SearchableAttributes: []string{"title", "content", "author", "tags"}
  • Lines 81–82:

    -DisplayedAttributes: &[]string{"id", "title", "author", "category", "publish_date", "rating", "featured"}
    +DisplayedAttributes: []string{"id", "title", "author", "category", "publish_date", "rating", "featured"}

The existing FilterableAttributes (lines 88–90) and SortableAttributes (lines 99–100) already use []string and can remain unchanged.

After updating, please verify that the example compiles without errors.

Likely an incorrect or invalid review comment.

@RISHABH4SAHNI RISHABH4SAHNI requested a review from ja7ad August 25, 2025 13:31
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: 5

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
examples/create_index_settings/README.md (1)

44-45: Missing document insertion and search implementation in example
The README for examples/create_index_settings states the example “adds sample articles” and “demonstrates how the settings improve search results,” but a scan of examples/create_index_settings/main.go shows no calls to insert documents (AddDocuments*) or execute searches (Search(...)).

• File affected: examples/create_index_settings/main.go
– No AddDocuments, AddDocumentsInBatches, or AddDocumentsJSON calls found
– No Search(...) calls found

To resolve, please choose one of the following:

  1. Implement steps 4–5 under “What it does” in main.go:
    • Add sample article insertion code (e.g., client.Index("articles").AddDocuments(...))
    • Perform and log one or more search queries to demonstrate settings impact
  2. Otherwise, update the README paragraph to accurately reflect the current example’s behavior (e.g., remove or rephrase the claims about adding documents and running searches).
♻️ Duplicate comments (6)
examples/multi_search/README.md (1)

23-23: Fix filter value casing to avoid 0 results; clarify wording.

Meilisearch string filters are case-sensitive. If your dataset stores Category as "Electronics", searching for "electronics" will not match. Also, “in electronics category” reads better with an article.

Apply:

-   - Search for "laptop" in electronics category
+   - Search for "laptop" in the "Electronics" category
examples/manage_tasks/README.md (1)

26-31: Admin API key requirement is clearly documented now — good catch and resolution.

The README now explicitly uses an admin key placeholder and clarifies the requirement.

examples/create_index_settings/README.md (1)

25-25: Ranking rules list looks good (and no invalid custom rule syntax).

Thanks for avoiding the previously flagged “rating:desc” form. If you later showcase a custom rule, use asc(field)/desc(field), e.g., desc(rating).

examples/facet_search/README.md (2)

25-25: “8 books” in README likely mismatches seeded count; update to actual number or seed 8.

The README says “8 sample books” and shows “✅ Added 8 books…”, but the example typically seeds 5. Keep docs and code in sync.

Option A (docs fix to 5):

-1. Create a "books" index with 8 sample books
+1. Create a "books" index with 5 sample books
-✅ Added 8 books to the index
+✅ Added 5 books to the index

Option B (code change): seed 8 books in examples/facet_search/main.go to match the README.

#!/bin/bash
# Count seeded docs quickly (heuristic by Title occurrences)
rg -n 'Title:\s*"' examples/facet_search/main.go | wc -l

Also applies to: 48-48


10-22: Fix Book struct to match the runnable example (ID type, Tags vs Series).

README shows ID as string and includes Series, but the example code uses ID int and Tags []string (no Series). Readers copying this will hit compile/runtime confusion. Align the README with the code.

Apply:

 type Book struct {
-    ID          string  `json:"id"`
+    ID          int     `json:"id"`
     Title       string  `json:"title"`
     Author      string  `json:"author"`
     Genre       string  `json:"genre"`
     Language    string  `json:"language"`
     PublishYear int     `json:"publish_year"`
     Rating      float64 `json:"rating"`
-    Publisher   string  `json:"publisher"`
+    Publisher   string  `json:"publisher"`
     Pages       int     `json:"pages"`
     InPrint     bool    `json:"in_print"`
-    Series      string  `json:"series"`
+    Tags        []string `json:"tags"`
 }

Run to confirm the struct used in code and fields referenced elsewhere:

#!/bin/bash
rg -n -C2 'type\s+Book\s+struct' examples/facet_search/main.go
rg -n 'Tags|Series' examples/facet_search/main.go
examples/search/README.md (1)

30-35: Restructure “Run it” into numbered steps and fix stray fence.

  • Add the missing “Start the Meilisearch server” step for completeness.
  • Remove the extra stray triple backticks (Line 35) that open an unlabeled code block and break formatting (MD040/MD046).

Apply this diff:

-## Run it
-
-```bash
-go run ./examples/search
-```
-```
+## Run it
+
+1. Start the Meilisearch server:
+   ```bash
+   ./meilisearch
+   ```
+   Or with Docker:
+   ```bash
+   docker run -it --rm -p 7700:7700 getmeili/meilisearch:latest
+   ```
+
+2. Run the example:
+   ```bash
+   go run ./examples/search
+   ```
+   # Alternatively, if using the repo's Makefile:
+   ```bash
+   make search
+   ```
🧹 Nitpick comments (15)
examples/multi_search/README.md (3)

22-22: Minor grammar: spell out small numbers.

Improve readability and match style.

-3. Run 3 searches simultaneously:
+3. Run three searches simultaneously:

21-21: Clarify which attributes are filterable vs. sortable (price must be sortable).

Price needs to be declared sortable for the “sorted by price” example to work. Make this explicit to prevent confusion.

-2. Configure filterable attributes for categories, stock status, price, and brand
+2. Configure filterable attributes (category, in_stock, brand) and a sortable attribute (price)

7-17: Optional: avoid float for money in examples.

Using float64 for currency can introduce rounding surprises. For an example it’s fine, but consider documenting that production code should use integer cents or a decimal type.

examples/manage_tasks/README.md (3)

17-23: Minor wording polish for the “Task information shown” lead-in.

-For each task you see:
+For each task, you'll see:

7-14: Clarify which “document operations” are shown in the type filter example.

Being explicit improves scannability and sets expectations.

-7. Filter tasks by type (document operations only)
+7. Filter tasks by type (document operations only: documentAdditionOrUpdate, documentDeletion)

44-52: Optional: Note that durations in sample output are illustrative.

Real timings vary by dataset and hardware; a short note avoids confusion.

-   Duration: 2ms
+   Duration: 2ms  # example; actual timings vary
@@
-   Duration: 15ms
+   Duration: 15ms  # example; actual timings vary
@@
-   Duration: 8ms
+   Duration: 8ms  # example; actual timings vary
examples/create_index_settings/README.md (3)

28-30: Clarify Pagination vs. “Max results” to match Meilisearch terminology

“Max results: 1000 per search” can be misread as per-page size. In settings, this is Pagination.maxTotalHits (a cap on total matching hits). Per-page sizing is controlled at query time (limit/hitsPerPage).

Apply this diff:

- - **Typo tolerance**: 1 typo for 5+ letter words, 2 typos for 9+ letter words
- - **Max results**: 1000 per search
+ - **Typo tolerance**: 1 typo for 5+ letter words, 2 typos for 9+ letter words
+ - **Pagination**: maxTotalHits = 1000 (cap on total matching hits); per-page limits are set at query time (e.g., hitsPerPage/limit)

7-18: Optional: call out task waiting explicitly in the flow

Settings updates are asynchronous. Consider amending step 3 to mention waiting for task completion before verification.

Apply this diff:

-3. Verify the settings were applied
+3. Wait for all settings-update tasks to complete, then verify the settings were applied

22-27: Make synonyms mapping unambiguous with a concrete shape (SDK-consistent)

The examples are clear, but a brief code-shaped mapping avoids ambiguity about directionality.

For example (Go SDK shape):

Synonyms: map[string][]string{
  "programming": {"coding", "development"},
  "javascript":  {"js", "ecmascript"},
  "golang":      {"go"},
}
examples/facet_search/README.md (2)

26-27: List exact filterable/sortable attributes to mirror the code.

To prevent drift, enumerate the precise attributes you configure (e.g., genre, language, publish_year, rating, publisher, in_print, tags) and sortable attributes (rating, publish_year, pages). This keeps README and code aligned.

Example update:

-2. Configure filterable attributes (genre, language, rating, etc.)
+2. Configure filterable attributes: genre, language, publish_year, rating, publisher, in_print, tags
+   and sortable attributes: rating, publish_year, pages

43-69: Unclosed/unstyled fenced code block (markdownlint MD040) and rendering issue.

There’s a stray ````` fence at Line 43 without a language and no closing fence for the output block. Use a language (text) and close the block to fix rendering and MD040.

-```
+```text
 Testing connection to Meilisearch...
 ✅ Connected to Meilisearch (status: available)

 📚 Setting up books index with facetable attributes...
 ✅ Added 8 books to the index

 1. Basic faceted search with distribution:
 Search: 'fiction' - Found 4 results
 Facet distribution:
   genre: {"fiction": 1, "sci-fi": 2, "cyberpunk": 1}
   language: {"english": 4}
   publish_year: {"1949": 1, "1965": 1, "1984": 1, "1992": 1}

 2. Faceted search with filters:
 Search: '' with filter 'genre = fantasy AND publish_year > 2000'
 Found 0 results (no fantasy books after 2000 in dataset)
 Refining to: 'genre = sci-fi AND rating > 4.0'
 Found 3 results with high-rated sci-fi books

 3. Facet-specific search:
 Facet search for 'sci' in genre facet with query 'space':
 Found 2 matching facet values: ["sci-fi"]

 Faceted search example completed successfully! 🎉
 
 The example will create a "books" index, configure facetable attributes, add sample book data, and demonstrate various faceted search scenarios including basic faceting, advanced filtering, and facet-specific searches.
- 
+```

Note: If you apply the earlier “8→5 books” change, reflect it here too.

examples/search/README.md (1)

23-29: Optional: clarify API key usage.

Consider noting that for a local, unsecured Meilisearch instance the API key may be omitted, while production setups should set MEILI_API_KEY.

Possible wording to append after the code block:
“Note: If your local Meilisearch isn’t secured, MEILI_API_KEY can be left unset. For production, configure a key with appropriate permissions.”

examples/chat_stream/README.md (3)

7-12: Align exit instructions and use inline code formatting for commands.

Bullet list says only 'quit' while the closing paragraph mentions 'quit' or 'exit'. Also, prefer inline code formatting (backticks) for commands.

 - Type 'quit' to exit
+ - Type `quit` or `exit` to exit

And in Line 31, switch single quotes to backticks:

-The example will start an interactive chat session where you can ask questions and receive streaming responses. Type 'quit' or 'exit' to end the session.
+The example will start an interactive chat session where you can ask questions and receive streaming responses. Type `quit` or `exit` to end the session.

Also applies to: 31-31


26-31: Offer Makefile-based run command (if present) for convenience.

PR summary mentions a top-level Makefile with a chat_stream target. Adding it here improves UX.

 ```bash
 go run ./examples/chat_stream

+Or with the Makefile:
+
+bash +make chat_stream +


Please confirm the Makefile target is named exactly `chat_stream`; if it differs, adjust accordingly.

---

`15-16`: **Clarify Enterprise prerequisite with a brief note about OSS compatibility.**

Since chat is Enterprise-only, add a one-liner noting the example won’t work against Community/OSS servers and will return a feature-not-available error.




Suggested addition right below Line 15:

```md
Note: Chat features are not available in the Community (OSS) edition. Running this example against a non-Enterprise server will fail with a feature-not-available error.
📜 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 c10d1bf and 1fe04d8.

📒 Files selected for processing (7)
  • examples/add_documents/README.md (1 hunks)
  • examples/chat_stream/README.md (1 hunks)
  • examples/create_index_settings/README.md (1 hunks)
  • examples/facet_search/README.md (1 hunks)
  • examples/manage_tasks/README.md (1 hunks)
  • examples/multi_search/README.md (1 hunks)
  • examples/search/README.md (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • examples/add_documents/README.md
🧰 Additional context used
🪛 markdownlint-cli2 (0.17.2)
examples/chat_stream/README.md

29-29: Fenced code blocks should have a language specified

(MD040, fenced-code-language)

examples/facet_search/README.md

43-43: Fenced code blocks should have a language specified

(MD040, fenced-code-language)

examples/manage_tasks/README.md

38-38: Fenced code blocks should have a language specified

(MD040, fenced-code-language)

examples/search/README.md

39-39: Fenced code blocks should have a language specified

(MD040, fenced-code-language)

🪛 LanguageTool
examples/create_index_settings/README.md

[grammar] ~7-~7: There might be a mistake here.
Context: ...1. Create an "articles" index with "id" as primary key 2. Configure comprehensive ...

(QB_NEW_EN)


[grammar] ~8-~8: There might be a mistake here.
Context: ...key 2. Configure comprehensive settings: - Searchable attributes (title, content, a...

(QB_NEW_EN)


[grammar] ~9-~9: There might be a mistake here.
Context: ...ttributes (title, content, author, tags) - Displayed attributes (what fields to ret...

(QB_NEW_EN)


[grammar] ~10-~10: There might be a mistake here.
Context: ...layed attributes (what fields to return) - Filterable attributes (what can be used ...

(QB_NEW_EN)


[grammar] ~11-~11: There might be a mistake here.
Context: ...attributes (what can be used in filters) - Sortable attributes (what can be sorted)...

(QB_NEW_EN)


[grammar] ~12-~12: There might be a mistake here.
Context: ...Sortable attributes (what can be sorted) - Ranking rules (how to order results) ...

(QB_NEW_EN)


[grammar] ~13-~13: There might be a mistake here.
Context: ... - Ranking rules (how to order results) - Stop words (common words to ignore) -...

(QB_NEW_EN)


[grammar] ~14-~14: There might be a mistake here.
Context: ... - Stop words (common words to ignore) - Synonyms (alternative words) - Typo t...

(QB_NEW_EN)


[grammar] ~15-~15: There might be a mistake here.
Context: ...gnore) - Synonyms (alternative words) - Typo tolerance (allow spelling mistakes)...

(QB_NEW_EN)


[grammar] ~16-~16: There might be a mistake here.
Context: ...Typo tolerance (allow spelling mistakes) - Pagination limits 3. Verify the settings...

(QB_NEW_EN)


[grammar] ~17-~17: There might be a mistake here.
Context: ...pelling mistakes) - Pagination limits 3. Verify the settings were applied ## Set...

(QB_NEW_EN)


[grammar] ~22-~22: There might be a mistake here.
Context: ...archable**: title, content, author, tags - Filterable: category, author, publish_...

(QB_NEW_EN)


[grammar] ~23-~23: There might be a mistake here.
Context: ..., author, publish_date, status, featured - Sortable: publish_date, title, author ...

(QB_NEW_EN)


[grammar] ~24-~24: There might be a mistake here.
Context: ...Sortable*: publish_date, title, author - Ranking rules: words, typo, proximity,...

(QB_NEW_EN)


[grammar] ~25-~25: There might be a mistake here.
Context: ...o, proximity, attribute, sort, exactness - Stop words: the, a, an, and, or, but, ...

(QB_NEW_EN)


[grammar] ~26-~26: There might be a mistake here.
Context: ..., but, in, on, at, to, for, of, with, by - Synonyms: programming = coding/develop...

(QB_NEW_EN)


[grammar] ~27-~27: There might be a mistake here.
Context: ... javascript = js/ecmascript, golang = go - Typo tolerance: 1 typo for 5+ letter w...

(QB_NEW_EN)


[grammar] ~28-~28: There might be a mistake here.
Context: ...etter words, 2 typos for 9+ letter words - Max results: 1000 per search ## Confi...

(QB_NEW_EN)

examples/facet_search/README.md

[grammar] ~28-~28: There might be a mistake here.
Context: ...rs like "genre = fantasy AND rating > 4.0" 5. Search within specific facets (like find...

(QB_NEW_EN)

examples/manage_tasks/README.md

[grammar] ~17-~17: There might be a mistake here.
Context: ...nformation shown For each task you see: - Task ID and type - Status (enqueued, pro...

(QB_NEW_EN)


[grammar] ~18-~18: There might be a mistake here.
Context: ...or each task you see: - Task ID and type - Status (enqueued, processing, succeeded,...

(QB_NEW_EN)


[grammar] ~19-~19: There might be a mistake here.
Context: ...enqueued, processing, succeeded, failed) - Start and finish times - Duration - Erro...

(QB_NEW_EN)


[grammar] ~20-~20: There might be a mistake here.
Context: ...ceeded, failed) - Start and finish times - Duration - Error details if it failed #...

(QB_NEW_EN)


[grammar] ~21-~21: There might be a mistake here.
Context: ...led) - Start and finish times - Duration - Error details if it failed ## Configura...

(QB_NEW_EN)

examples/multi_search/README.md

[grammar] ~22-~22: There might be a mistake here.
Context: ... brand 3. Run 3 searches simultaneously: - Search for "laptop" in electronics categ...

(QB_NEW_EN)


[grammar] ~23-~23: There might be a mistake here.
Context: ...imultaneously: - Search for "laptop" in electronics category - Search for "c...

(QB_NEW_EN)

🔇 Additional comments (4)
examples/multi_search/README.md (2)

46-46: Verify client.Close() actually exists on the SDK client type.

The Meilisearch Go client typically doesn’t expose Close(); adding this as guidance could mislead users or fail to compile if copied. If you added a wrapper for streaming connections, call that out explicitly; otherwise suggest closing idle HTTP connections when using a custom transport.

Proposed wording:

-- **Resource Management**: Proper client cleanup with `defer client.Close()`
+- **Resource Management**: If your client exposes a Close/shutdown (e.g., for streaming wrappers), `defer` it. Otherwise rely on Go’s HTTP connection reuse, and close idle connections if you created a custom transport.

41-48: Nice checklist of best practices.

Clear, actionable bullets that align with Meilisearch’s task model and multi-search flow.

examples/search/README.md (1)

37-55: Nice “Best Practices” and “Advanced Usage” sections.

Clear, actionable points (settings-first, waiting on tasks, batching, timeouts) mirror the example’s intent and help users avoid common pitfalls.

examples/chat_stream/README.md (1)

1-3: Clear, scoped README for the chat streaming example.

Concise objective and context are well-presented. Nice work.

ja7ad
ja7ad previously approved these changes Aug 28, 2025
@ja7ad
Copy link
Collaborator

ja7ad commented Aug 28, 2025

Copy link

codecov bot commented Aug 28, 2025

Codecov Report

❌ Patch coverage is 0% with 967 lines in your changes missing coverage. Please review.
✅ Project coverage is 67.60%. Comparing base (56d3527) to head (0f77661).
⚠️ Report is 13 commits behind head on main.

Files with missing lines Patch % Lines
examples/manage_tasks/main.go 0.00% 203 Missing ⚠️
examples/add_documents/main.go 0.00% 154 Missing ⚠️
examples/facet_search/main.go 0.00% 137 Missing ⚠️
examples/search/main.go 0.00% 125 Missing ⚠️
examples/multi_search/main.go 0.00% 124 Missing ⚠️
examples/create_index_settings/main.go 0.00% 119 Missing ⚠️
examples/chat_stream/main.go 0.00% 105 Missing ⚠️

❗ There is a different number of reports uploaded between BASE (56d3527) and HEAD (0f77661). Click for more details.

HEAD has 2 uploads less than BASE
Flag BASE (56d3527) HEAD (0f77661)
4 2
Additional details and impacted files
@@             Coverage Diff             @@
##             main     #703       +/-   ##
===========================================
- Coverage   85.80%   67.60%   -18.20%     
===========================================
  Files          22       29        +7     
  Lines        3614     4581      +967     
===========================================
- Hits         3101     3097        -4     
- Misses        366     1337      +971     
  Partials      147      147               

☔ 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.

@ja7ad ja7ad added the documentation Improvements or additions to documentation label Aug 28, 2025
@ja7ad ja7ad enabled auto-merge September 4, 2025 12:40
@ja7ad ja7ad disabled auto-merge September 4, 2025 12:41
@ja7ad
Copy link
Collaborator

ja7ad commented Sep 4, 2025

@RISHABH4SAHNI Please fix linter issue for merge

@ja7ad
Copy link
Collaborator

ja7ad commented Sep 4, 2025

@RISHABH4SAHNI please fix linter issues:

https://github.com/meilisearch/meilisearch-go/actions/runs/17471740625/job/49621655451#step:4:1

@ja7ad
Copy link
Collaborator

ja7ad commented Sep 4, 2025

@RISHABH4SAHNI again failed: https://github.com/meilisearch/meilisearch-go/actions/runs/17471894663/job/49622169780#step:4:1

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: 2

♻️ Duplicate comments (2)
examples/facet_search/main.go (2)

80-84: LGTM: correct FacetSearchRequest field.

Q is the right field (maps to JSON q); Query would not compile. Good fix.


162-175: LGTM: correct handling of FacetDistribution (json.RawMessage).

Unmarshalling into a typed map then iterating is the right approach; error path is handled.

🧹 Nitpick comments (1)
examples/facet_search/main.go (1)

102-117: Tighten error handling for CreateIndex.

Treat non-“already exists” errors as fatal instead of logging and continuing, to avoid masking setup issues.

If the SDK exposes a typed API error or status code, branch on that and return on other errors. I can draft the exact check if you confirm the error type helper available in this repo.

📜 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 83fb23c and 42723d6.

📒 Files selected for processing (2)
  • examples/add_documents/main.go (1 hunks)
  • examples/facet_search/main.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • examples/add_documents/main.go
🧰 Additional context used
🧬 Code graph analysis (1)
examples/facet_search/main.go (4)
meilisearch.go (1)
  • New (18-41)
options.go (1)
  • WithAPIKey (126-130)
types.go (5)
  • SearchRequest (502-532)
  • FacetSearchRequest (597-605)
  • IndexConfig (104-109)
  • Settings (148-170)
  • SearchResponse (561-575)
meilisearch_interface.go (1)
  • ServiceManager (8-82)
🔇 Additional comments (1)
examples/facet_search/main.go (1)

55-57: LGTM: correct request field for facets.

Using Facets (not FacetsDistribution) is correct and compiles.

@RISHABH4SAHNI
Copy link
Author

@ja7ad can you approve?

@ja7ad
Copy link
Collaborator

ja7ad commented Sep 4, 2025

@RISHABH4SAHNI
Copy link
Author

yeah give me some time i am trying to correct it.

@ja7ad
Copy link
Collaborator

ja7ad commented Sep 4, 2025

@RISHABH4SAHNI please check lint issues on your local before push:

golangci-lint run -v

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: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
examples/search/main.go (1)

1-148: Correct undefined field in facet_search example
Vet fails in examples/facet_search/main.go:90: facetResult.FacetHits is not a field on *json.RawMessage. Update the example to unmarshal the raw JSON (e.g. into a map[string]map[string]float64) or use the proper response type instead of calling FacetHits.

♻️ Duplicate comments (2)
examples/multi_search/main.go (2)

119-134: Nice: settings configured before queries that need them

Filterable/sortable attributes are correctly set for category, in_stock, and price; this prevents runtime filter/sort errors. Matches prior feedback.


51-56: Good fix: quoted string literal in filter

Using category = "electronics" avoids “invalid filter” parsing issues.

🧹 Nitpick comments (8)
examples/multi_search/main.go (4)

3-11: Handle CreateIndex errors explicitly; only continue on “index already exists”

Currently we log and proceed on any error, which can mask real failures (permissions, network). Gate the happy-path on the specific API error; otherwise return.

Apply this diff:

@@
-import (
+import (
+	"errors"
 	"context"
 	"fmt"
 	"log"
 	"os"
 	"time"
@@
 	// Create index
 	task, err := client.CreateIndex(&meilisearch.IndexConfig{
 		Uid:        indexUID,
 		PrimaryKey: "id",
 	})
 	if err != nil {
-		log.Printf("Index might already exist: %v", err)
+		var apiErr *meilisearch.Error
+		if errors.As(err, &apiErr) && apiErr.Code == "index_already_exists" {
+			fmt.Println("Index already exists; continuing")
+		} else {
+			return fmt.Errorf("create index: %w", err)
+		}
 	} else {
 		ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
 		defer cancel()
 		
 		_, err = client.WaitForTaskWithContext(ctx, task.TaskUID, 100*time.Millisecond)
 		if err != nil {
 			return fmt.Errorf("index creation failed: %w", err)
 		}
 	}

Also applies to: 103-117


165-170: Minor: tolerate accidental whitespace in env vars

Trim spaces so MEILI_HOST=" http://localhost:7700 " works predictably.

Apply this diff (add import strings as needed):

 func getenv(key, def string) string {
-	if v := os.Getenv(key); v != "" {
+	if v := strings.TrimSpace(os.Getenv(key)); v != "" {
 		return v
 	}
 	return def
 }

73-77: Use context-aware MultiSearchWithContext to avoid hanging on slow networks
The SDK already exposes MultiSearchWithContext (meilisearch_interface.go:116) which you can call with a timeout. For example:

-	// Execute multi-search
-	results, err := client.MultiSearch(multiSearchRequest)
+	// Execute multi-search with 5s timeout
+	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+	defer cancel()
+	results, err := client.MultiSearchWithContext(ctx, multiSearchRequest)

34-37: Use a context-bounded health check via HealthWithContext
IsHealthy() invokes HealthWithContext with a background context, which can hang indefinitely. Replace it with a timed context:

ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()

health, err := client.HealthWithContext(ctx)
if err != nil || health.Status != "available" {
    log.Fatalf("Meilisearch is not available: %v", err)
}
fmt.Println("✅ Connected to Meilisearch")

Optionally fall back to client.IsHealthy() or client.Health() on SDK versions without HealthWithContext.

examples/search/main.go (4)

117-127: Use integer counts for facet distribution.

Facet counts are integers. Unmarshal into map[string]map[string]int to avoid fractional printing.

-		var facets map[string]map[string]float64
+		var facets map[string]map[string]int

59-61: Avoid ctx/cancel shadowing; rename to prevent linter warnings.

The second ctx, cancel := shadows the earlier pair. Rename for clarity and to appease linters.

-		ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
-		defer cancel()
-		_, err = client.WaitForTaskWithContext(ctx, settingsTask.TaskUID, 100*time.Millisecond)
+		settingsCtx, settingsCancel := context.WithTimeout(context.Background(), 5*time.Second)
+		defer settingsCancel()
+		_, err = client.WaitForTaskWithContext(settingsCtx, settingsTask.TaskUID, 100*time.Millisecond)

20-27: Optional: actually verify connectivity.

Consider calling a lightweight health/version endpoint and failing fast if Meilisearch isn’t reachable.


91-98: Nit: requesting highlights for a non-existent field.

overview isn’t in Movie. Harmless, but you can drop it to keep the example tight.

-		AttributesToHighlight: []string{"title", "overview"},
+		AttributesToHighlight: []string{"title"},
📜 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 b0651c9 and 9c0ea23.

📒 Files selected for processing (3)
  • examples/facet_search/main.go (1 hunks)
  • examples/multi_search/main.go (1 hunks)
  • examples/search/main.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • examples/facet_search/main.go
🧰 Additional context used
🧬 Code graph analysis (2)
examples/search/main.go (4)
meilisearch.go (1)
  • New (18-41)
options.go (1)
  • WithAPIKey (126-130)
types.go (2)
  • Settings (148-170)
  • SearchRequest (502-532)
hit.go (1)
  • Hits (12-12)
examples/multi_search/main.go (4)
meilisearch.go (1)
  • New (18-41)
options.go (1)
  • WithAPIKey (126-130)
types.go (4)
  • MultiSearchRequest (544-547)
  • SearchRequest (502-532)
  • IndexConfig (104-109)
  • Settings (148-170)
meilisearch_interface.go (1)
  • ServiceManager (8-82)
🔇 Additional comments (4)
examples/search/main.go (4)

53-67: Good placement of settings update after index exists and task wait.

Applying filterable attributes post-indexing and waiting for the task is correct and avoids 404s.


37-52: Document ingestion flow looks solid.

Clear logging, timeout-bounded wait, and error handling are on point.


132-138: Model definition LGTM.

JSON tags align with the payload used for indexing.


140-147: Helper is fine.

Straightforward env fallback with zero surprises.

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

♻️ Duplicate comments (3)
examples/search/main.go (2)

79-98: Fix: stop unmarshaling already-decoded hit fields

json.Unmarshal expects []byte; hit["..."] is an interface{} value. Use type assertions.

-	for i, hit := range searchResult.Hits {
-		// Decode hit data properly
-		var title string
-		var year float64
-		var rating float64
-
-		if err := json.Unmarshal(hit["title"], &title); err != nil {
-		log.Printf("Failed to unmarshal title: %v", err)
-		title = "unknown"
-		}
-		if err := json.Unmarshal(hit["year"], &year); err != nil {
-			log.Printf("Failed to unmarshal year: %v", err)
-			year = 0
-		}
-		if err := json.Unmarshal(hit["rating"], &rating); err != nil {
-			log.Printf("Failed to unmarshal rating: %v", err)
-			rating = 0.0
-		}
-
-		fmt.Printf("  %d. %s (%d) - Rating: %.1f\n", i+1, title, int(year), rating)
-	}
+	for i, hit := range searchResult.Hits {
+		title, _ := hit["title"].(string)
+		year := 0
+		if y, ok := hit["year"].(float64); ok {
+			year = int(y)
+		} else if yi, ok := hit["year"].(int); ok {
+			year = yi
+		}
+		rating := 0.0
+		if r, ok := hit["rating"].(float64); ok {
+			rating = r
+		}
+		fmt.Printf("  %d. %s (%d) - Rating: %.1f\n", i+1, title, year, rating)
+	}

114-133: Fix: same hit decoding issue in advanced search loop

Repeat the assertion-based extraction here.

-	for i, hit := range searchResult.Hits {
-		// Decode hit data properly
-		var title string
-		var year float64
-		var rating float64
-
-		if err := json.Unmarshal(hit["title"], &title); err != nil {
-			log.Printf("Failed to unmarshal title: %v", err)
-			title = "unknown"
-		}
-		if err := json.Unmarshal(hit["year"], &year); err != nil {
-			log.Printf("Failed to unmarshal year: %v", err)
-			year = 0
-		}
-		if err := json.Unmarshal(hit["rating"], &rating); err != nil {
-			log.Printf("Failed to unmarshal rating: %v", err)
-			rating = 0.0
-		}
-
-		fmt.Printf("  %d. %s (%d) - Rating: %.1f\n", i+1, title, int(year), rating)
-	}
+	for i, hit := range searchResult.Hits {
+		title, _ := hit["title"].(string)
+		year := 0
+		if y, ok := hit["year"].(float64); ok {
+			year = int(y)
+		} else if yi, ok := hit["year"].(int); ok {
+			year = yi
+		}
+		rating := 0.0
+		if r, ok := hit["rating"].(float64); ok {
+			rating = r
+		}
+		fmt.Printf("  %d. %s (%d) - Rating: %.1f\n", i+1, title, year, rating)
+	}
examples/facet_search/main.go (1)

66-77: Fix filter syntax and demo label

String literals must be quoted; current filter 400s and likely yields 0 hits. Adjust filter and label.

-	searchResult, err = client.Index("books").Search("", &meilisearch.SearchRequest{
-		Filter: "genre = fantasy AND publish_year > 2000",
+	searchResult, err = client.Index("books").Search("", &meilisearch.SearchRequest{
+		Filter: `genre = "fantasy" AND publish_year >= 1930`,
 		Facets: []string{"language", "rating", "publisher"},
 		Sort:   []string{"rating:desc"},
 		Limit:  10,
 	})
@@
-	displaySearchResults("fantasy books after 2000", searchResult)
+	displaySearchResults("fantasy books after 1930", searchResult)
🧹 Nitpick comments (4)
examples/search/main.go (3)

100-107: Remove unknown highlight field or add it to Movie

overview isn’t in Movie; drop it or add the field. Simplest: keep only title.

-	searchResult, err = index.Search("drama", &meilisearch.SearchRequest{
+	searchResult, err = index.Search("drama", &meilisearch.SearchRequest{
 		Filter:                "year > 1990",
 		Facets:                []string{"genres", "year"},
-		AttributesToHighlight: []string{"title", "overview"},
+		AttributesToHighlight: []string{"title"},
 		Limit:                 10,
 	})

18-27: Close client and actually check cluster health

Free resources and fail fast if the node isn’t reachable.

-	client := meilisearch.New(host, meilisearch.WithAPIKey(apiKey))
+	client := meilisearch.New(host, meilisearch.WithAPIKey(apiKey))
+	defer client.Close()
@@
-	// Test connection to Meilisearch
-	fmt.Println("Testing connection to Meilisearch...")
+	// Test connection to Meilisearch
+	fmt.Println("Testing connection to Meilisearch...")
+	if !client.IsHealthy() {
+		log.Fatal("Meilisearch is not available")
+	}
+	fmt.Println("✅ Connected to Meilisearch")

137-139: Nit: use integer counts for facet distribution

Counts are integers; keep type consistent with other examples.

-		var facets map[string]map[string]float64
+		var facets map[string]map[string]int
examples/facet_search/main.go (1)

138-163: Don’t reuse the same context for multiple tasks

The 10s context for settings may be nearly exhausted before waiting on AddDocuments. Use a fresh context for the second wait.

-	_, err = client.WaitForTaskWithContext(ctx, settingsTask.TaskUID, 100*time.Millisecond)
+	_, err = client.WaitForTaskWithContext(ctx, settingsTask.TaskUID, 100*time.Millisecond)
@@
-	_, err = client.WaitForTaskWithContext(ctx, addTask.TaskUID, 100*time.Millisecond)
+	ctxAdd, cancelAdd := context.WithTimeout(context.Background(), 10*time.Second)
+	defer cancelAdd()
+	_, err = client.WaitForTaskWithContext(ctxAdd, addTask.TaskUID, 100*time.Millisecond)
📜 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 9c0ea23 and 0f77661.

📒 Files selected for processing (3)
  • examples/chat_stream/main.go (1 hunks)
  • examples/facet_search/main.go (1 hunks)
  • examples/search/main.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • examples/chat_stream/main.go
🧰 Additional context used
🧬 Code graph analysis (2)
examples/search/main.go (4)
meilisearch.go (1)
  • New (18-41)
options.go (1)
  • WithAPIKey (126-130)
types.go (2)
  • Settings (148-170)
  • SearchRequest (502-532)
hit.go (1)
  • Hits (12-12)
examples/facet_search/main.go (4)
meilisearch.go (1)
  • New (18-41)
options.go (1)
  • WithAPIKey (126-130)
types.go (6)
  • SearchRequest (502-532)
  • FacetSearchRequest (597-605)
  • FacetSearchResponse (607-611)
  • IndexConfig (104-109)
  • Settings (148-170)
  • SearchResponse (561-575)
meilisearch_interface.go (1)
  • ServiceManager (8-82)
🔇 Additional comments (2)
examples/search/main.go (1)

1-166: No issues detected in examples/search/main.go

All JSON unmarshalling and context usage are correct; no changes needed.

examples/facet_search/main.go (1)

54-61: LGTM: basic faceted search request uses correct fields

Using Facets on SearchRequest and handling errors properly looks good.

@RISHABH4SAHNI
Copy link
Author

RISHABH4SAHNI commented Sep 4, 2025

@ja7ad check lint issues locally before push, there was no issue , all issues are resolved now

@ja7ad ja7ad enabled auto-merge September 4, 2025 19:13
@ja7ad ja7ad added this pull request to the merge queue Sep 4, 2025
Merged via the queue into meilisearch:main with commit 4ebf4bf Sep 4, 2025
4 of 6 checks passed
@RISHABH4SAHNI RISHABH4SAHNI deleted the add-examples-usage branch September 4, 2025 19:18
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
documentation Improvements or additions to documentation
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants