Client Elasticsearch pour Kotlin : intégration, exemples et fonctionnalités

Formateur Python en ligne pour débutants

Apprenez Python facilement sans surcharge théorique. Résolvez des tâches pratiques avec vérification automatique et écrivez du code directement dans le navigateur.

Start Course

Client Elasticsearch pour Kotlin : guide complet

\n\n

Elasticsearch est un puissant moteur de recherche distribué basé sur Lucene. Pour l'utiliser depuis des applications Kotlin, on utilise le client officiel Elasticsearch Java Client, qui est entièrement compatible avec Kotlin grâce à sa proximité avec la JVM. Dans cet article, nous allons voir comment configurer le client, effectuer les opérations de base (indexation, recherche, suppression) et utiliser des fonctionnalités avancées telles que les agrégations et le filtrage.

\n\n

Connexion et configuration

\n\n

Pour commencer, ajoutez la dépendance dans build.gradle.kts (ou build.gradle) :

\n\n
// build.gradle.kts\ndependencies {\n    implementation("co.elastic.clients:elasticsearch-java:8.15.0")\n    implementation("com.fasterxml.jackson.core:jackson-databind:2.17.0")\n    implementation("com.fasterxml.jackson.module:jackson-module-kotlin:2.17.0")\n}
\n\n

Ensuite, créez le client :

\n\n
import co.elastic.clients.elasticsearch.ElasticsearchClient\nimport co.elastic.clients.json.jackson.JacksonJsonpMapper\nimport co.elastic.clients.transport.rest_client.RestClientTransport\nimport org.apache.http.HttpHost\nimport org.elasticsearch.client.RestClient\n\nfun createClient(): ElasticsearchClient {\n    val restClient = RestClient.builder(\n        HttpHost("localhost", 9200, "http")\n    ).build()\n\n    val transport = RestClientTransport(restClient, JacksonJsonpMapper())\n    return ElasticsearchClient(transport)\n}\n\nval client = createClient()
\n\n

Opérations de base

\n\n

Indexation d'un document

\n\n

Créez une data class pour représenter les données :

\n\n
data class Product(\n    val id: String,\n    val name: String,\n    val price: Double,\n    val category: String\n)
\n\n

L'indexation s'effectue ainsi :

\n\n
suspend fun indexProduct(product: Product) {\n    client.index { i ->\n        i.index("products")\n            .id(product.id)\n            .document(product)\n    }\n}\n\n// Exemple d'appel\nval product = Product("1", "Ordinateur portable", 999.99, "Électronique")\nrunBlocking { indexProduct(product) }
\n\n

Recherche par champs

\n\n
suspend fun searchByName(name: String): List<Product> {\n    val response = client.search<Product>({ s ->\n        s.index("products")\n            .query { q ->\n                q.match { m ->\n                    m.field("name")\n                        .query(name)\n                }\n            }\n    }, Product::class.java)\n\n    return response.hits().hits().map { it.source()!! }\n}
\n\n

Suppression d'un document

\n\n
suspend fun deleteProduct(id: String) {\n    client.delete { d ->\n        d.index("products")\n            .id(id)\n    }\n}
\n\n

Filtrage et agrégations

\n\n

Elasticsearch prend en charge les requêtes complexes. Par exemple, rechercher des produits dans une fourchette de prix avec agrégation par catégories :

\n\n
suspend fun searchWithAggregation(minPrice: Double, maxPrice: Double) {\n    val response = client.search<Product>({ s ->\n        s.index("products")\n            .query { q ->\n                q.range { r ->\n                    r.field("price")\n                        .gte(minPrice.toString())\n                        .lte(maxPrice.toString())\n                }\n            }\n            .aggregations("by_category") { a ->\n                a.terms { t ->\n                    t.field("category")\n                }\n            }\n    }, Product::class.java)\n\n    // Récupération des résultats d'agrégation\n    val categories = response.aggregations()\n        ?.get("by_category")\n        ?.sterms()\n        ?.buckets()\n        ?.map { "${it.key()}: ${it.docCount()}" }\n        ?: emptyList()\n\n    println("Catégories : $categories")\n}
\n\n

Traitement par lots (API Bulk)

\n\n

Pour l'indexation en masse, utilisez bulk

Recommendations