1

I have documents which look like this:

[{
"id": 1,
"title": "the title",
"body": "the body",
},{
"id": 3,
"title": "the title",
"body": "the body",
},{
"id": 2,
"title": "the title",
"body": "the body",
}]

var sortArray = [1,2,3]

I am wondering if it is possible to sort documents from "sortArray", what I mean is in the output the result should be sorted on the basis of the array "sortArray". Can anyone please help me here.

I have tried the below sort with elastic but it's not working.

 .Sort(z => sortArray.Count() > 0 ? z.Ascending(q => sortArray.IndexOf(q.id)) : z)
Rob
  • 9,664
  • 3
  • 41
  • 43
SoftwareNerd
  • 1,875
  • 8
  • 29
  • 58
  • 3
    Does this answer your question? [Sort a list from another list IDs](https://stackoverflow.com/questions/15275269/sort-a-list-from-another-list-ids) – Jawad Jan 16 '20 at 14:12

3 Answers3

0

I'm not familiar with elasticsearch but with Json you can do it this way

var documents = JArray.Parse(json).Cast<dynamic>();
var sortArray = new List<int> { 1, 2, 3 };
var ordered = documents.OrderBy(x => sortArray.IndexOf((int)x.id));

Perhaps you are missing the cast to (int) in q.id

Innat3
  • 3,561
  • 2
  • 11
  • 29
0

@Innat3 his code is fine but includes a little mistake with Index. This works fine:

var sorted = documents.OrderBy(x => sortArray[x - 1]).ToList();

Keskin
  • 1
0

If the sort array size is not large, you can make use of the boost field present in query options, note:- you have to use it in a bool should with minimum_should_match = 1 instead of bool filter query because it alters the score of documents which skipped for filter query, i.e. create multiple term clauses with the array elements and give the boost value in decreasing order of you array elements.Something like this-

GET index/_search
{
  "query": {
    "bool": {
      "should": [
        {
          "term": {
            "field_name": {
              "value": 1,
              "boost": 100
            }
          }
        },
        {
          "term": {
            "field_name": {
              "value": 2,
              "boost": 90
            }
          }
        },
        {
          "term": {
            "field_name": {
              "value": 3,
              "boost": 80
            }
          }
        }
      ],"minimum_should_match": 1
    }
  }
}

Otherwise there is not specific support in elasticsearch to achieve this.

krishan
  • 49
  • 3