How to calculate weighted score depending on order of an array field

I would like to search by an array field, and give weight depending on where the value appears in the arrays.

For example, I have 3 documents like this:

{ "foo": [1, 2, 3] }
{ "foo": [2, 3, 4] }
{ "foo": [3, 4, 5] }

and I send a query like:

{ "query": { "term": { "foo": 3 } } }

Then, I want the response to be sorted like this:

{ "foo": [3, 4, 5] }
{ "foo": [2, 3, 4] }
{ "foo": [1, 2, 3] }

I mean, the earlier 3 appears in the arrays, the higher the _score gets.
Is there any efficient ways to do this?

I don't think you can do that.
Unless you defined another data structure, using nested documents like:

{ "foo": [
 {
  "value": 3,
  "position": 1 
 },
 {
  "value": 4,
  "position": 2 
 },
 {
  "value": 5,
  "position": 3 
 }
] }

And then try to increase the score by taking into account the foo.position nested field using a function score may be...

May be you can do that with a script score but this might be super slow if you have to read all the documents to compute that score.

My 2 cents.

1 Like

Thank you! I think you are right.

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