Skip to content

Commit 181f8e5

Browse files
committed
PI-2876 Sort results manually in Kotlin
Due to bug in current OpenSearch version
1 parent 5843c84 commit 181f8e5

File tree

1 file changed

+15
-11
lines changed

1 file changed

+15
-11
lines changed

src/main/kotlin/uk/gov/justice/hmpps/probationsearch/contactsearch/ContactSearchService.kt

+15-11
Original file line numberDiff line numberDiff line change
@@ -33,8 +33,7 @@ import org.springframework.data.elasticsearch.core.query.IndexQuery
3333
import org.springframework.security.core.context.SecurityContextHolder
3434
import org.springframework.stereotype.Service
3535
import uk.gov.justice.hmpps.probationsearch.contactsearch.ContactSearchService.SortType
36-
import uk.gov.justice.hmpps.probationsearch.contactsearch.ContactSearchService.SortType.LAST_UPDATED_DATETIME
37-
import uk.gov.justice.hmpps.probationsearch.contactsearch.ContactSearchService.SortType.SCORE
36+
import uk.gov.justice.hmpps.probationsearch.contactsearch.ContactSearchService.SortType.*
3837
import uk.gov.justice.hmpps.probationsearch.services.DeliusService
3938
import uk.gov.justice.hmpps.sqs.audit.HmppsAuditService
4039
import java.time.Instant
@@ -111,14 +110,9 @@ class ContactSearchService(
111110
.trackTotalHits(TrackHits.of { it.count(5000) })
112111
.size(pageable.pageSize)
113112
.from(pageable.offset.toInt())
114-
.sort { sort ->
115-
// Note: Hybrid query does not allow sorting by multiple fields including score
116-
val order = pageable.sort.singleOrNull() ?: Sort.Order.desc(SCORE.searchField)
117-
sort.field {
118-
it.field(order.property)
119-
.order(if (order.isDescending) JavaClientSortOrder.Desc else JavaClientSortOrder.Asc)
120-
}
121-
}
113+
// Note: We're currently unable to reliably sort hybrid results until OpenSearch 2.19, so we re-sort the results later
114+
// See https://github.com/opensearch-project/neural-search/issues/1067
115+
.sort { sort -> sort.field { it.field(SCORE.searchField).order(JavaClientSortOrder.Desc) } }
122116
.highlight { highlight ->
123117
highlight
124118
.encoder(HighlighterEncoder.Html)
@@ -143,7 +137,17 @@ class ContactSearchService(
143137
response.pageable.pageNumber,
144138
response.totalElements,
145139
response.totalPages,
146-
results,
140+
results.sortedWith(
141+
SortType.entries
142+
.flatMap { type -> type.aliases.mapNotNull { alias -> pageable.sort.getOrderFor(alias)?.let { type to it } } }
143+
.fold(Comparator { _, _ -> 0 }) { comparator, (type, order) ->
144+
val selector = when (type) {
145+
DATE -> { contact: ContactSearchResult -> contact.date }
146+
else -> { contact: ContactSearchResult -> contact.score }
147+
}
148+
if (order.isDescending) comparator.thenByDescending(selector) else comparator.thenBy(selector)
149+
},
150+
),
147151
)
148152
}
149153

0 commit comments

Comments
 (0)