在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
开源软件名称(OpenSource Name):jillesvangurp/es-kotlin-client开源软件地址(OpenSource Url):https://github.com/jillesvangurp/es-kotlin-client开源编程语言(OpenSource Language):Kotlin 98.1%开源软件介绍(OpenSource Introduction):Elasticsearch Kotlin Client29 May 2022 es-kotlin-client becomes kt-search I've moved the work on the 2.0 version of this client to a new repository. Kt-search better reflects that this client will work with both Opensearch and Elasticsearch. As of now, es-kotlin-client is deprecated and no longer maintained. However, it lives on as the Why? Elasticsearch was forked by Amazon as Opensearch and there are now two products that implement almost identical REST APIs that require separate Java clients. Additionally, Elastic deprecated their client and wrote a completely new one. And finally they also released a major new version with many changes. As of now, es-kotlin-client is only compatible with Elasticsearch v7. The Elastic RestHighLevel client does not work with Opensearch anymore and the Opensearch fork of this client has renamed packages. And because it never was very usable and now deprecated on the Elastic side, an extensive rewrite of this library cannot be avoided. Relative to es-kotlin-client, kt-search is a complete rewrite that preserves the best features:
Additionally:
Development work is ongoing but the client is already usable. I'll update this page with more info once a 2.0 stabilizes and we can freeze the APIs. 16 May 2022 I'm working on a version 2.0 of this library. A lot of things happened recently:
As a consequence, version 2.0 of this project will try to preserve the essential and popular features of this project (DSL support, co-routine support, repositories, bulk indexing, etc.) but it will rebuild them on top of a kotlin multiplatform basis. Specifically:
Work for this is ongoing on the Barring any emergencies, I won't provide new releases of the 1.x branch. The latest 1.x version should be fine with most recent versions of Elasticsearch. If people want to fork and fix, that's fine with me but I'm not looking to merge pull requests for 1.x related fixes. As soon as the 2.0 branch stabilizes, I will merge it to master. 1.x has already been branched to its own branch. Version 1.x READMEThe Es Kotlin Client provides a friendly Kotlin API on top of the official Elastic Java client.
Elastic's The Es Kotlin Client takes away none of that power but adds a lot of power and convenience. The underlying java functionality is always there should you need it. But, for most commonly used things, this client provides more Kotlin appropriate ways to access the functionality. The new Java API Client introduced in 7.15In Elasticsearch 7.15, a new Java API client was added to replace the Java REST High Level Client on which the kotlin library is based. Given that and the recent fork with Amazon's Opensearch, and the coming Elasticsearch 8.0 release. For now, the kotlin client will continue to use the deprecated java RestHighLevel client. I'm currently considering several options for the future of this Kotlin client. I was in any case considering to start work on a major release of this library to rebuild it on top of ktor client and kotlinx serialization and gradually cut loose from the Java client. With Opensearch and Elasticsearch 8 clearly diverging in terms of API compatibility, features, and indeed compatibility with the Java client, compatibility breaking changes are inevitable. So, cutting loose from the Java client seems like it could be the right strategy and would also enable using this kotlin client on kotlin native, kotlin js, or soon kotlin WASM. Obviously this is going to be a bit of work and I need to find time to be able to commit to this. Features
Get ItAs JFrog is shutting down JCenter, the latest releases are once more available via Jitpack. Add this to your implementation("com.github.jillesvangurp:es-kotlin-client:<version>") You will also need to add the Jitpack repository: repositories {
mavenCentral()
maven { url = uri("https://jitpack.io") }
} See release notes with each github release tag for an overview what changed. Elasticsearch Java client versionThis library is always built with and tested against specific versions of the Elasticsearch Java client (see release notes). Since they sometimes change their Java internal APIs, even between minor versions, it is important to match the version you are using with what the es-kotlin-client was built against. Especially with frameworks like Spring, you may end up with older versions of the java client on your classpath. If you see class not found or method not found related exceptions, that is probably what is happening. If, so, double check your dependencies and transitive dependencies and add excludes. Also, be careful using e.g. the spring-dependency-management plugin for this reason. Documentation
ExampleThis example is a bit more complicated than a typical hello world but more instructive than just putting some objects in a schema less index. Which of course is something you should not do. The idea here is to touch on most topics a software engineer would need to deal with when creating a new project using Elasticsearch:
// given some model class with two fields
data class Thing(
val name: String,
val amount: Long = 42
) // create a Repository
// with the default jackson model reader and writer
// (you can use something else by overriding default values of the args)
val thingRepository = esClient.indexRepository<Thing>(
index = "things",
// you have to opt in to refreshes, bad idea to refresh in production code
refreshAllowed = true
)
// let the Repository create the index with the specified mappings & settings
thingRepository.createIndex {
// we use our settings DSL here
// you can also choose to use a source block with e.g. multiline strings
// containing json
configure {
settings {
replicas = 0
shards = 2
}
mappings {
// mappings DSL, most common field types are supported
text("name")
// floats, longs, doubles, etc. should just work
number<Int>("amount")
}
}
}
// lets create a few Things
thingRepository.index("1", Thing("foo", 42))
thingRepository.index("2", Thing("bar", 42))
thingRepository.index("3", Thing("foobar", 42))
// make sure ES commits the changes so we can search
thingRepository.refresh()
val results = thingRepository.search {
configure {
// added names to the args for clarity here, but optional of course
query = match(field = Thing::name, query = "bar")
}
}
// results know hot deserialize Things
results.mappedHits.forEach {
println(it.name)
}
// but you can also access the raw hits of course
results.searchHits.forEach {
println("hit with id ${it.id} and score ${it.score}")
}
// putting things into an index 1 by 1 is not scalable
// lets do some bulk inserts with the Bulk DSL
thingRepository.bulk {
// we are passed a BulkIndexingSession<Thing> in the block as 'this'
// we will bulk re-index the objects we already added with
// a scrolling search. Scrolling searches work just
// like normal searches (except they are not ranked)
// all you do is set scrolling to true and you can
// scroll through billions of results.
val sequence = thingRepository.search(scrolling = true) {
configure {
from = 0
// when scrolling, this is the scroll page size
resultSize = 10
query = bool {
should(
// you can use strings
match("name", "foo"),
// or property references
match(Thing::name, "bar"),
match(Thing::name, "foobar")
)
}
}
}.hits
// hits is a Sequence<Pair<SearchHit,Thing?>> so we get both the hit and
// the deserialized value. Sequences are of course lazy and we fetch
// more results as you process them.
// Thing is nullable because Elasticsearch allows source to be
// disabled on indices.
sequence.forEach { (esResult, deserialized) ->
if (deserialized != null) {
// Use the BulkIndexingSession to index a transformed version
// of the original thing
index(
esResult.id, deserialized.copy(amount = deserialized.amount + 1),
// allow updates of existing things
create = false
)
}
}
} Co-routinesUsing co-routines is easy in Kotlin. Mostly things work almost the same way. Except everything is non blocking and asynchronous, which is nice. In other languages this creates all sorts of complications that Kotlin largely avoids. The Java client in Elasticsearch has support for non blocking IO. We leverage this to add our own suspending calls using extension functions via our gradle code generation plugin. This runs as part of the build process for this library so there should be no need for you to use this plugin. The added functions have the same signatures as their blocking variants. Except of course they have the word async in their names and the suspend keyword in front of them. We added suspending versions of the // we reuse the index we created already to create an ayncy index repo
val repo = esClient.asyncIndexRepository<Thing>(
index = "things",
refreshAllowed = true
)
// co routines require a CoroutineScope, so let use one
runBlocking {
// lets create some more things; this works the same as before
repo.bulk {
// but we now get an AsyncBulkIndexingSession<Thing>
(1..1000).forEach {
index(
"$it",
Thing("thing #$it", it.toLong())
)
}
}
// refresh so we can search
repo.refresh()
// if you are wondering, yes this is almost identical
// to the synchronous version above.
// However, we now get an AsyncSearchResults back
val results = repo.search {
configure {
query = term("name.keyword", "thing #666")
}
}
// However, mappedHits is now a Flow instead of a Sequence
results.mappedHits.collect {
// collect is part of the kotlin Flow API
// this is one of the few parts where the API is different
println("we've found a thing with: ${it.amount}")
}
} Captured Output:
For more examples, check the manual or look in the examples source directory. Code GenerationThis library makes use of code generated by our code generation gradle plugin. This is mainly used to generate co-routine friendly suspendable extension functions for all asynchronous methods in the RestHighLevelClient. We may add more features in the future. Platform Support & CompatibilityThis client requires Java 8 or higher (same JVM requirements as Elasticsearch). Some of the Kotlin functionality is also usable by Java developers (with some restrictions). However, you will probably want to use this from Kotlin. Android is currently not supported as the minimum requirements for Elastic's highlevel client are Java 8. Besides, embedding a fat library like that on Android is probably a bad idea, and you should probably not be talking to Elasticsearch directly from a mobile phone in any case. Usually we update to the latest version within days after Elasticsearch releases. Barring REST API changes, most of this client should work with any recent 7.x releases, any future releases and probably also 6.x. For version 6.x, check the es-6.7.x branch. Building & DevelopmentYou need java >= 8 and docker + docker compose to run elasticsearch and the tests. Simply use the gradle wrapper to build things: ./gradlew build Look inside the build file for comments and documentation. If you create a pull request, please also regenerate the documentation with Gradle will spin up Elasticsearch using the docker compose plugin for gradle and then run the tests against that. If you want to run the tests from your IDE, just use DevelopmentThis library should be perfectly fine for general use at this point. We released 1.0 beginning of 2021 and I provide regular updates as new versions of Elasticsearch are published. If you want to contribute, please file tickets, create PRs, etc. For bigger work, please communicate before hand before committing a lot of your time. I'm just inventing this as I go. Let me know what you think. LicenseThis project is licensed under the MIT license. This maximizes everybody's freedom to do what needs doing. Please exercise your rights under this license in any way you feel is appropriate. I do appreciate attribution and pull requests ... Note, as of version 7.11.0, the Elastic Rest High Level Client that this library depends on has moved to a non OSS license. Before that, it was licensed under a mix of Apache 2.0 and Elastic's proprietary licensing. As far as I understand it, that should not change anything for using this library. Which will always be licensed under the MIT license. But if that matters to you, you may want to stick with version 1.0.12 of this library. Version 1.1.0 and onwards are going to continue to track the main line Elasticsearch. Support and ConsultingWithin reason, I'm always happy to support users with issues. Feel free to approach me via the issue tracker, the discussion section, twitter (jillesvangurp), or email (jilles AT jillesvangurp.com). I generally respond to all questions, issues, and pull requests. But, please respect that I'm doing this in my spare time. I'm also available for consulting/advice on Elasticsearch projects and am happy to help you with architecture reviews, query & indexing strategy, etc. I can do trainings, deep dives and have a lot of experience delivering great search. Check my homepage for more details. |
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论