Cliente Elasticsearch para Swift (iOS/macOS)
Elasticsearch es un potente sistema de búsqueda distribuido construido sobre Apache Lucene. Para desarrolladores de iOS y macOS, está disponible el cliente oficial elasticsearch-swift, que proporciona una interfaz conveniente para trabajar con Elasticsearch desde aplicaciones Swift. La biblioteca es compatible con toda la REST API de Elasticsearch, incluyendo indexación, búsqueda, agregaciones y gestión de clústeres.
Instalación y configuración
El cliente se distribuye a través de Swift Package Manager (SPM). Para agregarlo a un proyecto:
// En Package.swiftdependencies: [ .package(url: "https://github.com/elastic/elasticsearch-swift.git", from: "8.10.0")]O a través de Xcode: File → Add Packages → ingrese la URL del repositorio. Después de la instalación, importe la biblioteca:
import ElasticsearchFuncionalidades principales
- Indexación de documentos — agregar, actualizar y eliminar registros en índices.
- Búsqueda — texto completo, por campos, con filtros y ordenación.
- Agregaciones — cálculos estadísticos, agrupaciones, histogramas.
- Gestión de clústeres — creación/eliminación de índices, configuración de shards y réplicas.
- Soporte para async/await — solicitudes asíncronas utilizando el modelo moderno de Swift Concurrency.
Ejemplo de uso: conexión e indexación
Creemos un cliente e indexemos varios documentos:
import Elasticsearch
let client = ElasticsearchClient( host: "https://your-cluster-url:9200", apiKey: "your-api-key")
struct Book: Codable { let id: String let title: String let author: String let year: Int}
let books = [ Book(id: "1", title: "Swift Programming", author: "John Doe", year: 2023), Book(id: "2", title: "iOS Development", author: "Jane Smith", year: 2024)]
for book in books { let response = try await client.index( index: "books", id: book.id, body: book ) print("Indexed: \\(response.result)")}Búsqueda usando Query DSL
Elasticsearch admite un potente lenguaje de consultas. Ejemplo de búsqueda de texto completo:
import Elasticsearch
let query: [String: Any] = [ "query": [ "bool": [ "must": [ ["match": ["title": "Swift"]] ], "filter": [ ["range": ["year": ["gte": 2023]]] ] ] ]]
let searchResponse = try await client.search( index: "books", body: query)
if let hits = searchResponse.hits?.hits { for hit in hits { if let source = hit.source { let book = try JSONDecoder().decode(Book.self, from: source) print("Found: \\(book.title) by \\(book.author)") } }}Agregaciones para análisis
Ejemplo de conteo de libros por año:
let aggregationQuery: [String: Any] = [ "size": 0, "aggs": [ "by_year": [ "terms": ["field": "year", "size": 10] ] ]]
let aggResponse = try await client.search( index: "books", body: aggregationQuery)
if let buckets = aggResponse.aggregations?["by_year"] as? [String: Any], let bucketList = buckets["buckets"] as? [[String: Any]] { for bucket in bucketList { let year = bucket["key"] as? Int ?? 0 let count = bucket["doc_count"] as? Int ?? 0 print("\\(year): \\(count) books") }}Gestión de índices
Creación y eliminación de un índice con configuraciones:
let settings: [String: Any] = [ "settings": [ "number_of_shards": 2, "number_of_replicas": 1 ], "mappings": [ "pro