Maxim Suponya
Maxim Suponya

Reputation: 1514

query by time difference beetween dates in elasticsearch

Say I have index like this:

{"id": "12345678", "start": 1541999620214, "end": 1541999620222 }

How do I query for documents with end-start > 10? and now-start < 60000

Upvotes: 0

Views: 27

Answers (1)

Val
Val

Reputation: 217334

Simply like this:

{
  "query": {
    "script": {
      "script": {
        "source": "doc.end.value - doc.start.value < 10"
      }
    }
  }
}

and

{
  "query": {
    "script": {
      "script": {
        "source": "System.currentTimeMillis() - doc.start.value < 60000"
      }
    }
  }
}

As a performance optimization, though, you could store the end - start information inside your document at indexing time so you don't have to resort to scripting and your query would simply become:

{
  "query": {
    "range": {
      "diff": {
        "lt": 10
      }
    }
  }
}

Upvotes: 1

Related Questions