Prerequisites
This guide walks you through setting up Meilisearch with Swift for iOS, macOS, and server-side Swift applications.
Prerequisites
- Swift 5.5 or higher
- Xcode 13+ (for iOS/macOS development)
- A Meilisearch instance (Cloud or self-hosted)
1. Install the SDK
- Swift Package Manager
- CocoaPods
Add the dependency to your Package.swift:
dependencies: [
.package(url: "https://github.com/meilisearch/meilisearch-swift.git", from: "0.17.0")
]
Or in Xcode: File → Add Packages → Enter the repository URL.
Add to your Podfile:
pod 'MeiliSearch'
Then run pod install.
2. Connect to Meilisearch
import MeiliSearch
let client = try! MeiliSearch(
host: ProcessInfo.processInfo.environment["MEILISEARCH_URL"]!,
apiKey: ProcessInfo.processInfo.environment["MEILISEARCH_KEY"]
)
Set your environment variables:
export MEILISEARCH_URL="https://your-instance.meilisearch.io" # or http://localhost:7700
export MEILISEARCH_KEY="your_api_key"
3. Add documents
// Define your document struct
struct Movie: Codable, Equatable {
let id: Int
let title: String
let genres: [String]
let year: Int
}
// Add documents
let movies = [
Movie(id: 1, title: "The Matrix", genres: ["Action", "Sci-Fi"], year: 1999),
Movie(id: 2, title: "Inception", genres: ["Action", "Thriller"], year: 2010),
Movie(id: 3, title: "Interstellar", genres: ["Drama", "Sci-Fi"], year: 2014)
]
let index = client.index("movies")
// Using async/await
let task = try await index.addDocuments(documents: movies)
try await client.waitForTask(taskUid: task.taskUid)
4. Search
let searchResult: Searchable<Movie> = try await index.search("matrix")
for hit in searchResult.hits {
print("\(hit.title) (\(hit.year))")
}
// The Matrix (1999)
5. Search with filters
First, configure filterable attributes:
try await index.updateFilterableAttributes(["genres", "year"])
Then search with filters:
let searchParams = SearchParameters(
query: "",
filter: "genres = \"Sci-Fi\" AND year > 2000"
)
let results: Searchable<Movie> = try await index.search(searchParams)
Full example
import MeiliSearch
// Connect
let client = try! MeiliSearch(
host: ProcessInfo.processInfo.environment["MEILISEARCH_URL"]!,
apiKey: ProcessInfo.processInfo.environment["MEILISEARCH_KEY"]
)
struct Movie: Codable, Equatable {
let id: Int
let title: String
let year: Int
}
Task {
// Add documents
let movies = [
Movie(id: 1, title: "The Matrix", year: 1999),
Movie(id: 2, title: "Inception", year: 2010),
Movie(id: 3, title: "Interstellar", year: 2014)
]
let index = client.index("movies")
let task = try await index.addDocuments(documents: movies)
try await client.waitForTask(taskUid: task.taskUid)
// Search
let results: Searchable<Movie> = try await index.search("inter")
for hit in results.hits {
print(hit.title)
}
}
Next steps
Full-text search
Configure ranking and relevancy
Filtering
Add filters and facets
AI-powered search
Add semantic search
API reference
Explore all search parameters
