Question regarding Sorts

Hello guys!

I have a question regarding to sorts, the scenario i have is following:
I m creating a list of sort on one field with different custom sorting scripts, so eventually it looks like:
sorts: [
script: {}, # sort 1 (Strict match)
script: {}, # sort 2 (prefix match)
script: {} # sort 3 (more loose condition match)
]

The goal i want to achieve is that 1 should be used if could be, otherwise fall back to sort2, sort3.

But what i seeing is that even the we have the exact match docs based on user's query, the order does not working as I expect, am i not doing it correctly/how should i achieve my goal?

Thanks

Anyone has insights regarding this question?

I'm assuming the 3 scripts get's used as 3 fields. Did you try having all the logic into 1 script ?

Hello!

Thanks for your response.

I haven't tried merging those 3 into one sort yet. Just wondering what's the recommend way to achieve what i described there.

What do you mean by get's used as 3 fields?

Paste exact query that you send, what you wrote isn't valid.

sorts: [
_script: {
type: string,
script: {
lang: painless,
source: if (doc[params.fieldName] != null) { def strValue = doc[params.fieldName].value; def lc =
strValue.toLowerCase(); if (lc.equals(params.prefix)) { return 0; }}return 1;
params: {
fieldName: "a"
},
}
order: asc
},
_script: {
type: string,
script: {
lang: painless,
source: if (doc[params.fieldName] != null) { def strValue = doc[params.fieldName].value; def lc =
strValue.toLowerCase(); if (lc.startsWith(params.prefix)) { return 0; }}return 1;
params: {
fieldName: "a"
}
},
order: asc
},
_script: {
type: string,
script: {
lang: painless,
source:def value = '';for (String fieldName : params.fieldNames) { if (doc[fieldName] != null) { if
(!value.isEmpty()) { value += ' '; } value += String.valueOf(doc[fieldName].value); }}return value;
params: {
fieldName: "a"
}
},
order: asc
}
]

@ddorian43 Please take a look, the sorting i want to achieve here is that based on doc's field 'a',
try exact match first, if not, fall back to prefix, if still not, back to last one

Please put it inside `` tags.
Try to change it into 1 big script that does conditional return.

Could you explain why this one doesn't work? is it because the later sort override the previous one?

And apologies for not formatting, trying to get use to this

read how sort works on documentation. See nulls first/last and missing. Basically it sorts by 3 values together. So they are always sorted by script then script2 then script3.

@ddorian43 I see, so it behaves in an overriding fashion now. I will try to merge those 3 scripts into one and give it a shot. Thanks!

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.