Skip to content

Commit e01a287

Browse files
authored
Merge pull request #22 from oramasearch/feat/sort-groups
Allow sorting for groups by score
2 parents 2f2d271 + a3b1af2 commit e01a287

File tree

2 files changed

+20
-2
lines changed

2 files changed

+20
-2
lines changed

src/collection.ts

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -174,14 +174,21 @@ export class CollectionManager {
174174

175175
public async search<R = AnyObject>(query: SearchParams, init?: ClientRequestInit): Promise<SearchResult<R>> {
176176
const start = Date.now()
177-
const { datasourceIDs, indexes, ...restQuery } = query
177+
const { datasourceIDs, indexes, groupBy, ...restQuery } = query
178+
179+
// Extract sortBy from groupBy (client-side only, not sent to backend)
180+
const groupsSortBy = groupBy?.sortBy
181+
const groupByForApi = groupBy
182+
? { properties: groupBy.properties, max_results: groupBy.max_results }
183+
: undefined
178184

179185
const result = await this.client.request<Omit<SearchResult<R>, 'elapsed'>>({
180186
path: `/v1/collections/${this.collectionID}/search`,
181187
body: {
182188
userID: this.profile?.getUserId() || undefined,
183189
...restQuery, // restQuery can override `userID`
184190
indexes: datasourceIDs || indexes,
191+
groupBy: groupByForApi,
185192
},
186193
method: 'POST',
187194
params: undefined,
@@ -190,6 +197,15 @@ export class CollectionManager {
190197
target: 'reader',
191198
})
192199

200+
// Sort groups by score of first element if requested
201+
if (groupsSortBy === 'score' && result.groups) {
202+
result.groups.sort((a, b) => {
203+
const scoreA = a.result[0]?.score ?? 0
204+
const scoreB = b.result[0]?.score ?? 0
205+
return scoreB - scoreA // Descending order
206+
})
207+
}
208+
193209
const elapsed = Date.now() - start
194210

195211
return {

src/lib/types.ts

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,8 @@ export type Hook = 'BeforeAnswer' | 'BeforeRetrieval'
6363

6464
export type SearchMode = 'fulltext' | 'vector' | 'hybrid' | 'auto'
6565

66+
export type GroupsSortBy = 'default' | 'score'
67+
6668
export type SearchParams = {
6769
term: string
6870
mode?: SearchMode
@@ -79,7 +81,7 @@ export type SearchParams = {
7981
similarity?: number
8082
tolerance?: number
8183
userID?: string
82-
groupBy?: { properties: string[]; max_results?: number }
84+
groupBy?: { properties: string[]; max_results?: number; sortBy?: GroupsSortBy }
8385
}
8486

8587
export type CloudSearchParams = Omit<SearchParams, 'indexes'> & { datasourceIDs?: string[] }

0 commit comments

Comments
 (0)