user2904696
user2904696

Reputation: 33

Sort elastic search query based on a nested key value array

I have a json

{
    "uniqueKey": "918084",
    "dataValue": {
        "metadata": {
            "timestamps": [{
                "key": "startTime",
                "value": "2017-02-07T18:00:00-06:00"
            }, {
                "key": "processedTime",
                "value": "2017-02-07T18:05:00-06:00"
            }]
        }
    }
}

I have to write a query to sort on startTime. Does anyone how I can write a query for this in elastic search. dataValue is a nested field.

Upvotes: 2

Views: 994

Answers (1)

Hosar
Hosar

Reputation: 5292

You can use sort with nested_path.
Suppose you have the following mapping:

{
  "test-so": {
    "mappings": {
      "with-dates": {
        "properties": {
          "datavalue": {
            "type": "nested",
            "properties": {
              "metadata": {
                "type": "nested",
                "properties": {
                  "timestamps": {
                    "type": "nested",
                    "properties": {
                      "key": {
                        "type": "keyword"
                      },
                      "value": {
                        "type": "date",
                        "format": "date_optional_time"
                      }
                    }
                  }
                }
              }
            }
          },
          "uniquekey": {
            "type": "keyword"
          }
        }
      }
    }
  }
}

You can use sort as follow:

GET /test-so/with-dates/_search
{
  "query": {
    "nested": {
      "path": "datavalue.metadata.timestamps",
      "query": {
        "term": {
          "datavalue.metadata.timestamps.key": {
            "value": "startTime"
          }
        }
      }
    }
  },
  "sort": [
    {
      "datavalue.metadata.timestamps.value": {
        "order": "desc",
        "nested_path": "datavalue.metadata.timestamps"
      }
    }
  ]
}

That will return the documents ordered by the date on startTime.
Hope this help, maybe the mapping is not exactly the same. (note: tested on Elastic 5.1).

Upvotes: 2

Related Questions