Petteri H
Petteri H

Reputation: 12232

Elasticsearch sorting by matching array item

I have a following structure in indexed documents:

document1: "customLists":[{"id":8,"position":8},{"id":26,"position":2}]
document2: "customLists":[{"id":26,"position":1}]
document3: "customLists":[{"id":8,"position":1},{"id":26,"position":3}]

I am able to search matching documents that belong to a given list with match query "customLists.id = 26". But I need to sort the documents based on the position value within that list and ignore positions of the other lists.

So the expected results would be in order of document2, document1, document3

Is the data structure suitable for this kind of sorting and how to handle this?

Upvotes: 4

Views: 3066

Answers (1)

keety
keety

Reputation: 17441

One way to achieve this would be to set mapping type of customLists as nested and then use sorting by nested fields

Example :

1) Create Index & Mapping

put test
put test/test/_mapping
{
   "properties": {
      "customLists": {
         "type": "nested",
         "properties": {
            "id": {
               "type": "integer"
            },
            "position": {
               "type": "integer"
            }
         }
      }
   }
}

2) Index Documents :

    put test/test/1 
    {
     "customLists":[{"id":8,"position":8},{"id":26,"position":2}]
    }
    put test/test/2
    {
    "customLists":[{"id":26,"position":1}] 
    }

   put test/test/3
   {
      "customLists":[{"id":8,"position":1},{"id":26,"position":3}]
   }

3) Query to sort by positon for given id

post test/_search
    {
       "filter": {
          "nested": {
             "path": "customLists",
             "query": {
                "term": {
                   "customLists.id": {
                      "value": "26"
                   }
                }
             }
          }
       },
       "sort": [
          {
             "customLists.position": {
                "order": "asc",
                "mode": "min",
                "nested_filter": {
                   "term": {
                      "customLists.id": {
                         "value": "26"
                      }
                   }
                }
             }
          }
       ]
    }

Upvotes: 4

Related Questions