Cliente Elasticsearch para Swift (iOS/macOS): integração e exemplos

Treinador Online de Python para Iniciantes

Aprenda Python facilmente sem sobrecarga teórica. Resolva tarefas práticas com verificação automática e escreva código diretamente no navegador.

Start Course

Cliente Elasticsearch para Swift (iOS/macOS)

Elasticsearch é um poderoso sistema de busca distribuído, construído sobre o Apache Lucene. Para desenvolvedores iOS e macOS, está disponível o cliente oficial elasticsearch-swift, que fornece uma interface conveniente para trabalhar com Elasticsearch a partir de aplicativos em Swift. A biblioteca suporta totalmente a REST API do Elasticsearch, incluindo indexação, busca, agregações e gerenciamento de cluster.



Instalação e configuração

O cliente é distribuído via Swift Package Manager (SPM). Para adicionar ao projeto:

// Em Package.swiftdependencies: [    .package(url: "https://github.com/elastic/elasticsearch-swift.git", from: "8.10.0")]

Ou através do Xcode: File → Add Packages → insira a URL do repositório. Após a instalação, importe a biblioteca:

import Elasticsearch


Principais funcionalidades

  • Indexação de documentos — adicionar, atualizar e excluir registros em índices.
  • Busca — texto completo, por campos, com filtros e ordenação.
  • Agregações — cálculos estatísticos, agrupamentos, histogramas.
  • Gerenciamento de cluster — criar/excluir índices, configurar shards e réplicas.
  • Suporte a async/await — requisições assíncronas usando o modelo moderno de Swift Concurrency.


Exemplo de uso: conexão e indexação

Vamos criar um cliente e indexar alguns 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)")}


Busca usando Query DSL

Elasticsearch suporta uma poderosa linguagem de consulta. Exemplo de busca 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)") } }}


Agregações para análise

Exemplo de contagem de livros por ano:

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") }}


Gerenciamento de índices

Criação e exclusão de índice com configurações:

let settings: [String: Any] = [    "settings": [        "number_of_shards": 2,        "number_of_replicas": 1    ],    "mappings": [        "pro                    

Recommendations