2

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.

2

1 Answer 1

2

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).

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.