16
16
package org .springframework .data .mongodb .core .query ;
17
17
18
18
import java .util .Locale ;
19
+ import java .util .Map .Entry ;
19
20
20
21
import org .bson .Document ;
21
-
22
22
import org .springframework .data .mongodb .util .BsonUtils ;
23
23
import org .springframework .lang .Nullable ;
24
24
@@ -37,6 +37,7 @@ public class TextQuery extends Query {
37
37
private String scoreFieldName = DEFAULT_SCORE_FIELD_FIELDNAME ;
38
38
private boolean includeScore = false ;
39
39
private boolean sortByScore = false ;
40
+ private int sortByScoreIndex = 0 ;
40
41
41
42
/**
42
43
* Creates new {@link TextQuery} using the the given {@code wordsAndPhrases} with {@link TextCriteria}
@@ -101,6 +102,7 @@ public static TextQuery queryText(TextCriteria criteria) {
101
102
*/
102
103
public TextQuery sortByScore () {
103
104
105
+ this .sortByScoreIndex = getSortObject ().size ();
104
106
this .includeScore ();
105
107
this .sortByScore = true ;
106
108
return this ;
@@ -173,15 +175,35 @@ public Document getFieldsObject() {
173
175
public Document getSortObject () {
174
176
175
177
if (this .sortByScore ) {
176
- Document sort = new Document ();
177
- sort .put (getScoreFieldName (), META_TEXT_SCORE );
178
- sort .putAll (super .getSortObject ());
179
- return sort ;
178
+ if (sortByScoreIndex == 0 ) {
179
+ Document sort = new Document ();
180
+ sort .put (getScoreFieldName (), META_TEXT_SCORE );
181
+ sort .putAll (super .getSortObject ());
182
+ return sort ;
183
+ }
184
+ return fitInSortByScoreAtPosition (super .getSortObject ());
180
185
}
181
186
182
187
return super .getSortObject ();
183
188
}
184
189
190
+ private Document fitInSortByScoreAtPosition (Document source ) {
191
+
192
+ Document target = new Document ();
193
+ int i = 0 ;
194
+ for (Entry <String , Object > entry : source .entrySet ()) {
195
+ if (i == sortByScoreIndex ) {
196
+ target .put (getScoreFieldName (), META_TEXT_SCORE );
197
+ }
198
+ target .put (entry .getKey (), entry .getValue ());
199
+ i ++;
200
+ }
201
+ if (i == sortByScoreIndex ) {
202
+ target .put (getScoreFieldName (), META_TEXT_SCORE );
203
+ }
204
+ return target ;
205
+ }
206
+
185
207
/*
186
208
* (non-Javadoc)
187
209
* @see org.springframework.data.mongodb.core.query.Query#isSorted()
0 commit comments