Elasticsearch Client for Swift (iOS/macOS)
Elasticsearch is a powerful distributed search and analytics engine built on Apache Lucene. For integration with mobile and desktop applications in Swift (iOS/macOS), there is a specialized client Elasticsearch Swift. This library provides a convenient API for executing search queries, indexing data, aggregations, and cluster management directly from Apple applications.
Key Features of the Library
- Full-text search — support for all Elasticsearch query types (match, term, bool, fuzzy, etc.)
- CRUD operations — create, read, update, and delete documents in indices
- Aggregations — building complex analytical reports (terms, range, date_histogram, etc.)
- Batch processing — bulk operations for mass data loading
- Asynchronous support — working with async/await and Combine
- SSL/TLS and authentication — secure connection to the cluster
Installation
Add the library via Swift Package Manager. In Xcode, select File → Add Packages and enter the repository URL:
https://github.com/elastic/elasticsearch-swift.gitOr add the dependency in Package.swift:
dependencies: [ .package(url: "https://github.com/elastic/elasticsearch-swift.git", from: "1.0.0")]Client Initialization
Create an instance of ElasticsearchClient specifying the Elasticsearch host and port:
import Elasticsearch
let client = ElasticsearchClient( host: "http://localhost:9200", username: "elastic", password: "changeme")To connect to Elastic Cloud, use the constructor with a URL and API key:
let client = ElasticsearchClient( cloudID: "my-cluster:dXM...", apiKey: "base64EncodedApiKey")Indexing Documents
Let's create a simple user model and index it:
struct User: Codable { let name: String let email: String let age: Int}
let user = User(name: "Alexey", email: "alex@example.com", age: 30)
Task { let response = try await client.index( index: "users", id: "1", body: user ) print("Document created: \\(response.result)")}Searching Documents
Search for users by name using a match query:
let searchQuery: [String: Any] = [ "query": [ "match": [ "name": "Alexey" ] ]]
Task { let response = try await client.search( index: "users", body: searchQuery ) if let hits = response.hits?.hits { for hit in hits { if let source = hit.source as? [String: Any] { print("Found: \\(source["name"] ?? "")") } } }}Aggregations
Build a histogram by user age:
let aggregationQuery: [String: Any] = [ "size": 0, "aggs": [ "age_ranges": [ "range": [ "field": "age", "ranges": [ ["to": 20], ["from": 20, "to": 40], ["from": 40] ] ] ] ]]
Task { let response = try await client.search( index: "users", body: aggregationQuery ) if let buckets = response.aggregations?["age_ranges"] as? [String: Any] { print("Aggregation results: \\(buckets)") }}Update and Delete
Updating the age field