Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 47 additions & 0 deletions examples/add_documents/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
# Document Management Example

This example demonstrates comprehensive document management using the Meilisearch Go SDK:

- **Adding documents** (single and batch operations)
- **Updating documents** with new data
- **Retrieving documents** by ID and in batches
- **Deleting documents** (single and multiple)
- **Task monitoring** for all operations

## Features Demonstrated

1. **Batch Operations**: Add multiple documents efficiently
2. **Single Document Operations**: Add, update, delete individual documents
3. **Document Retrieval**: Get documents by ID or fetch in batches
4. **Update Operations**: Modify existing documents
5. **Delete Operations**: Remove documents by ID or in batches
6. **Task Management**: Monitor async operations completion
7. **Error Handling**: Robust error handling for all operations

## Operations Covered

- `AddDocuments()` - Add documents to index
- `UpdateDocuments()` - Update existing documents
- `GetDocument()` - Retrieve single document by ID
- `GetDocuments()` - Retrieve multiple documents with pagination
- `DeleteDocument()` - Delete single document
- `DeleteDocuments()` - Delete multiple documents
- `WaitForTask()` - Monitor task completion

## Configuration

```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"
```

## Running the Example

```bash
go run ./examples/add_documents
```

The example will create a "users" index and demonstrate all document management operations with detailed logging of each step and task completion.
191 changes: 191 additions & 0 deletions examples/add_documents/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,191 @@
package main

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

"github.com/meilisearch/meilisearch-go"
)

// User represents a user document
type User struct {
ID int `json:"id"`
Name string `json:"name"`
Email string `json:"email"`
Role string `json:"role"`
Active bool `json:"active"`
JoinDate string `json:"join_date"`
}

func main() {
// Initialize the Meilisearch client
host := getenv("MEILI_HOST", "http://localhost:7700")
apiKey := os.Getenv("MEILI_API_KEY")
client := meilisearch.New(host, meilisearch.WithAPIKey(apiKey))
defer client.Close()

// Test connection
fmt.Println("Testing connection to Meilisearch...")
if !client.IsHealthy() {
log.Fatal("Meilisearch is not available")
}
fmt.Println("✅ Connected to Meilisearch")

// Create index for document operations
indexUID := "users"
if err := createIndex(client, indexUID); err != nil {
log.Fatalf("Failed to create index: %v", err)
}

index := client.Index(indexUID)

fmt.Println("\n📄 Document Management Examples")
fmt.Println("===============================")

// 1. Add documents (batch)
fmt.Println("1. Adding documents in batch:")
users := []User{
{ID: 1, Name: "Alice Johnson", Email: "[email protected]", Role: "admin", Active: true, JoinDate: "2023-01-15"},
{ID: 2, Name: "Bob Smith", Email: "[email protected]", Role: "user", Active: true, JoinDate: "2023-02-20"},
{ID: 3, Name: "Charlie Brown", Email: "[email protected]", Role: "moderator", Active: false, JoinDate: "2023-03-10"},
}

task, err := index.AddDocuments(users)
if err != nil {
log.Fatalf("Failed to add documents: %v", err)
}

if err := waitForTask(client, task.TaskUID); err != nil {
log.Fatalf("Failed to wait for add task: %v", err)
}
fmt.Printf("✅ Added %d documents (Task ID: %d)\n", len(users), task.TaskUID)

// 2. Add single document
fmt.Println("\n2. Adding single document:")
newUser := User{
ID: 4,
Name: "Diana Prince",
Email: "[email protected]",
Role: "user",
Active: true,
JoinDate: "2023-04-05",
}

task, err = index.AddDocuments([]User{newUser})
if err != nil {
log.Fatalf("Failed to add single document: %v", err)
}

if err := waitForTask(client, task.TaskUID); err != nil {
log.Fatalf("Failed to wait for add task: %v", err)
}
fmt.Printf("✅ Added single document (Task ID: %d)\n", task.TaskUID)

// 3. Update documents
fmt.Println("\n3. Updating documents:")
updatedUsers := []User{
{ID: 2, Name: "Bob Smith Jr.", Email: "[email protected]", Role: "admin", Active: true, JoinDate: "2023-02-20"},
{ID: 3, Name: "Charlie Brown", Email: "[email protected]", Role: "moderator", Active: true, JoinDate: "2023-03-10"}, // Activating user
}

task, err = index.UpdateDocuments(updatedUsers)
if err != nil {
log.Fatalf("Failed to update documents: %v", err)
}

if err := waitForTask(client, task.TaskUID); err != nil {
log.Fatalf("Failed to wait for update task: %v", err)
}
fmt.Printf("✅ Updated %d documents (Task ID: %d)\n", len(updatedUsers), task.TaskUID)

// 4. Get document by ID
fmt.Println("\n4. Getting document by ID:")
doc, err := index.GetDocument("2", nil)
if err != nil {
log.Fatalf("Failed to get document: %v", err)
}
fmt.Printf("Retrieved document: %v\n", doc)

// 5. Get multiple documents
fmt.Println("\n5. Getting multiple documents:")
docs, err := index.GetDocuments(&meilisearch.DocumentsQuery{
Limit: 10,
Offset: 0,
})
if err != nil {
log.Fatalf("Failed to get documents: %v", err)
}
fmt.Printf("Retrieved %d documents:\n", len(docs.Results))
for i, doc := range docs.Results {
fmt.Printf(" %d. %v\n", i+1, doc)
}

// 6. Delete documents
fmt.Println("\n6. Deleting documents:")
task, err = index.DeleteDocument("4")
if err != nil {
log.Fatalf("Failed to delete document: %v", err)
}

if err := waitForTask(client, task.TaskUID); err != nil {
log.Fatalf("Failed to wait for delete task: %v", err)
}
fmt.Printf("✅ Deleted document with ID 4 (Task ID: %d)\n", task.TaskUID)

// 7. Delete multiple documents
fmt.Println("\n7. Deleting multiple documents:")
task, err = index.DeleteDocuments([]string{"1", "3"})
if err != nil {
log.Fatalf("Failed to delete documents: %v", err)
}

if err := waitForTask(client, task.TaskUID); err != nil {
log.Fatalf("Failed to wait for delete task: %v", err)
}
fmt.Printf("✅ Deleted multiple documents (Task ID: %d)\n", task.TaskUID)

// 8. Final document count
fmt.Println("\n8. Final document count:")
docs, err = index.GetDocuments(&meilisearch.DocumentsQuery{Limit: 100})
if err != nil {
log.Fatalf("Failed to get final documents: %v", err)
}
fmt.Printf("Remaining documents: %d\n", len(docs.Results))

fmt.Println("\nDocument management examples completed successfully! 🎉")
}

func createIndex(client meilisearch.ServiceManager, indexUID string) error {
fmt.Printf("Creating index '%s'...\n", indexUID)

task, err := client.CreateIndex(&meilisearch.IndexConfig{
Uid: indexUID,
PrimaryKey: "id",
})
if err != nil {
log.Printf("Index might already exist: %v", err)
return nil // Continue if index exists
}

return waitForTask(client, task.TaskUID)
}

func waitForTask(client meilisearch.ServiceManager, taskUID int64) error {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()

_, err := client.WaitForTaskWithContext(ctx, taskUID, 100*time.Millisecond)
return err
}

// getenv returns the value of the environment variable named by the key,
// or def if the variable is not present or empty.
func getenv(key, def string) string {
if v := os.Getenv(key); v != "" {
return v
}
return def
}
57 changes: 57 additions & 0 deletions examples/chat_stream/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
# Chat Streaming Example

This example demonstrates interactive chat streaming using the Meilisearch Go SDK with enterprise chat capabilities:

- **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

## Available Examples

### 📝 [Basic Search](../search)
Basic search functionality with index creation, document management, and various search operations.

### 💬 Chat Streaming
Interactive chat experience with streaming responses and knowledge base integration.

## Prerequisites

1. **Meilisearch Enterprise**: Chat functionality requires Meilisearch Enterprise
2. **LLM Integration**: Configure Meilisearch with LLM integration
3. **Chat Workspaces**: Set up appropriate chat workspaces

## 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"
```

## Features Demonstrated

1. **Environment Configuration**: Uses `MEILI_HOST` and `MEILI_API_KEY`
2. **Workspace Discovery**: Automatically lists and selects available workspaces
3. **Interactive Loop**: Simple REPL interface for chat interaction
4. **Streaming Chat**: Real-time streaming responses with proper EOF handling
5. **Resource Management**: Proper client and stream cleanup
6. **Error Handling**: Graceful error handling with informative messages

## 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/chat_stream
```

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.
Loading