Kotlin 的 Elasticsearch 客户端:强大的搜索与分析工具
Elasticsearch 是一个基于 Apache Lucene 的分布式搜索和分析系统,能够快速执行全文搜索、聚合以及大量数据分析。要从 Kotlin 应用程序中使用 Elasticsearch,有多个客户端可供选择,但最现代且推荐使用的是 Elasticsearch Java Client(从 7.16 版本开始),它完全支持 Kotlin。在本文中,我们将介绍其安装、配置和基本操作。
安装与连接
首先,将依赖项添加到您的 build.gradle.kts 中:
dependencies { implementation("co.elastic.clients:elasticsearch-java:8.15.0") implementation("com.fasterxml.jackson.module:jackson-module-kotlin:2.17.0") implementation("jakarta.json:jakarta.json-api:2.1.3")}对于 Maven (pom.xml):
<dependency> <groupId>co.elastic.clients</groupId> <artifactId>elasticsearch-java</artifactId> <version>8.15.0</version></dependency><dependency> <groupId>com.fasterxml.jackson.module</groupId> <artifactId>jackson-module-kotlin</artifactId> <version>2.17.0</version></dependency>创建客户端
该库使用 Builder 模式进行配置。以下是一个创建客户端并连接到本地 Elasticsearch 实例的示例:
import co.elastic.clients.elasticsearch.ElasticsearchClientimport co.elastic.clients.json.jackson.JacksonJsonpMapperimport co.elastic.clients.transport.ElasticsearchTransportimport co.elastic.clients.transport.rest_client.RestClientTransportimport org.apache.http.HttpHostimport org.elasticsearch.client.RestClient
fun createElasticsearchClient(): ElasticsearchClient { // 创建 HTTP 客户端(无认证) val restClient = RestClient.builder( HttpHost("localhost", 9200, "http") ).build()
// 使用 Jackson JSON 映射器创建传输层 val transport: ElasticsearchTransport = RestClientTransport( restClient, JacksonJsonpMapper() )
// 返回准备好的客户端 return ElasticsearchClient(transport)}对于生产环境,建议使用认证和 HTTPS:
val credentialsProvider = BasicCredentialsProvider()credentialsProvider.setCredentials( AuthScope.ANY, UsernamePasswordCredentials("elastic", "your_password"))
val restClient = RestClient.builder( HttpHost("your-cluster.com", 9243, "https")).setHttpClientConfigCallback { httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider)}.build()索引管理
在对文档执行操作之前,需要创建索引(如果不存在)。以下是创建带有映射的索引示例:
suspend fun createIndex(client: ElasticsearchClient, indexName: String) { val response = client.indices().create { createBuilder -> createBuilder .index(indexName) .mappings { mappings -> mappings .properties("title") { prop -> prop.text { it } } .properties("content") { prop -> prop.text { it } } .properties("timestamp") { prop -> prop.date { it } } } } println("索引已创建:${response.acknowledged}")}文档的 CRUD 操作
创建/更新文档(Index API)
data class Article( val title: String, val content: String, val timestamp: String = java.time.Instant.now().toString())
suspend fun indexDocument(client: E