mbuhot / eskotlin

Elasticsearch Query DSL for Kotlin
MIT License
136 stars 28 forks source link

Use Kotlin range operator #27

Closed janheinrichmerker closed 5 years ago

janheinrichmerker commented 5 years ago

Instead of constructing simple range queries like this:

range {
    "age" {
        from = 10
        to = 20
    }
}

we should leverage the Kotlin range operator (..) and overload the in-operator operator to construct the same query like this:

"age" in 10..20

We then need to override the following function:

fun ClosedRange<Int>.contains(name: String): RangeQueryBuilder = 
        RangeQueryBuilder(name).from(start).to(endInclusive)

Similar methods could be added for other number types.

Additional consideration has to be done about non-inclusive floating point ranges, to support include_lower/include_upper. Same goes for the other optional parameters of RangeQueryBuilder.

janheinrichmerker commented 5 years ago

After some quick testing I found out, returning a RangeQueryBuilder in the contains is not allowed, as it must return Boolean.

However, we can still use the range operators and define an infix function:

infix fun String.inRange(range: ClosedRange<Int>): RangeQueryBuilder =
        RangeQueryBuilder(this).from(range.start).to(range.endInclusive)

Then we can instead use:

"age" inRange  10..20
janheinrichmerker commented 5 years ago

Regarding optional parameters of RangeQueryBuilder, we might as well offer configuration like this:

"objj" inRange  (5..78) {
    includeLower = true
    includeUpper = false
}

(Of course this might be a separate issue then.)