如何在Kotlin中用Java API向Elasticsearch 8.x发送带JSON的POST请求
在Kotlin中使用Elasticsearch 8.x Java API发送JSON文档
基于你已完成的客户端配置,以下是使用IndexRequest类发送完整JSON文档的几种实现示例:
方式1:直接传入JSON字符串
适合已有现成JSON内容的场景:
import org.elasticsearch.action.index.IndexRequest import org.elasticsearch.xcontent.XContentType // 待发送的JSON文档内容 val jsonDocument = """ { "title": "Elasticsearch 8.x Kotlin实践", "content": "通过Java API向ES提交JSON文档", "tags": ["elasticsearch", "kotlin", "java-api"], "publish_time": "2024-05-20T14:30:00Z" } """.trimIndent() // 构建IndexRequest,指定目标索引名,可选指定文档ID(不指定则ES自动生成) val indexRequest = IndexRequest("your_target_index") .id("custom_doc_id") // 可选,删除此行则由ES自动生成文档ID .source(jsonDocument, XContentType.JSON) // 执行索引请求 val indexResponse = client.index(indexRequest) // 输出结果 println("文档索引成功,ID: ${indexResponse.id},版本号: ${indexResponse.version}")
方式2:通过Jackson JsonNode动态构建JSON
适合需要动态组装JSON结构的场景:
import com.fasterxml.jackson.databind.JsonNode import com.fasterxml.jackson.databind.ObjectMapper import org.elasticsearch.action.index.IndexRequest import org.elasticsearch.xcontent.XContentType val objectMapper = ObjectMapper() // 动态构建JSON节点 val jsonNode: JsonNode = objectMapper.createObjectNode() .put("title", "Elasticsearch 8.x Kotlin实践") .put("content", "通过Java API向ES提交JSON文档") .set("tags", objectMapper.createArrayNode().add("elasticsearch").add("kotlin").add("java-api")) .put("publish_time", "2024-05-20T14:30:00Z") val indexRequest = IndexRequest("your_target_index") .source(objectMapper.writeValueAsString(jsonNode), XContentType.JSON) val indexResponse = client.index(indexRequest) println("文档索引成功,ID: ${indexResponse.id},版本号: ${indexResponse.version}")
方式3:通过实体类转换为JSON
适合结构化数据场景,先定义实体类再序列化:
import com.fasterxml.jackson.databind.ObjectMapper import org.elasticsearch.action.index.IndexRequest import org.elasticsearch.xcontent.XContentType // 定义实体类 data class Article( val title: String, val content: String, val tags: List<String>, val publishTime: String ) // 实例化实体对象 val article = Article( title = "Elasticsearch 8.x Kotlin实践", content = "通过Java API向ES提交JSON文档", tags = listOf("elasticsearch", "kotlin", "java-api"), publishTime = "2024-05-20T14:30:00Z" ) val objectMapper = ObjectMapper() val jsonString = objectMapper.writeValueAsString(article) val indexRequest = IndexRequest("your_target_index") .source(jsonString, XContentType.JSON) val indexResponse = client.index(indexRequest) println("文档索引成功,ID: ${indexResponse.id},版本号: ${indexResponse.version}")
补充说明
- 替换代码中的
your_target_index为实际的ES索引名称,若索引不存在,ES默认会自动创建(需确保集群开启自动创建索引配置,或提前手动创建索引) - 实际业务中建议添加异常处理,避免IO异常导致程序崩溃:
try { val indexResponse = client.index(indexRequest) println("文档索引成功,ID: ${indexResponse.id},版本号: ${indexResponse.version}") } catch (e: IOException) { println("索引文档失败:${e.message}") e.printStackTrace() }
内容的提问来源于stack exchange,提问作者SCORPIOGA3T
相关产品推荐
相关产品推荐

