4

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?

3
  • What does ignore positions of the other lists. mean in your question? Commented Mar 2, 2016 at 12:08
  • if I search with customLists.id=26 I am only interested in position value in that item {"id":26,"position":5} Commented Mar 2, 2016 at 12:11
  • Not able to understand you .Please share the sample output which you want? Commented Mar 2, 2016 at 12:16

1 Answer 1

4

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"
                      }
                   }
                }
             }
          }
       ]
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.