- Elasticsearch Guide: other versions:
- Elasticsearch introduction
- Getting started with Elasticsearch
- Set up Elasticsearch
- Installing Elasticsearch
- Configuring Elasticsearch
- Important Elasticsearch configuration
- Important System Configuration
- Bootstrap Checks
- Heap size check
- File descriptor check
- Memory lock check
- Maximum number of threads check
- Max file size check
- Maximum size virtual memory check
- Maximum map count check
- Client JVM check
- Use serial collector check
- System call filter check
- OnError and OnOutOfMemoryError checks
- Early-access check
- G1GC check
- All permission check
- Starting Elasticsearch
- Stopping Elasticsearch
- Adding nodes to your cluster
- Installing X-Pack
- Set up X-Pack
- Configuring X-Pack Java Clients
- X-Pack Settings
- Bootstrap Checks for X-Pack
- Upgrade Elasticsearch
- API Conventions
- Document APIs
- Search APIs
- Aggregations
- Metrics Aggregations
- Avg Aggregation
- Weighted Avg Aggregation
- Cardinality Aggregation
- Extended Stats Aggregation
- Geo Bounds Aggregation
- Geo Centroid Aggregation
- Max Aggregation
- Min Aggregation
- Percentiles Aggregation
- Percentile Ranks Aggregation
- Scripted Metric Aggregation
- Stats Aggregation
- Sum Aggregation
- Top Hits Aggregation
- Value Count Aggregation
- Median Absolute Deviation Aggregation
- Bucket Aggregations
- Adjacency Matrix Aggregation
- Auto-interval Date Histogram Aggregation
- Children Aggregation
- Composite Aggregation
- Date Histogram Aggregation
- Date Range Aggregation
- Diversified Sampler Aggregation
- Filter Aggregation
- Filters Aggregation
- Geo Distance Aggregation
- GeoHash grid Aggregation
- Global Aggregation
- Histogram Aggregation
- IP Range Aggregation
- Missing Aggregation
- Nested Aggregation
- Parent Aggregation
- Range Aggregation
- Reverse nested Aggregation
- Sampler Aggregation
- Significant Terms Aggregation
- Significant Text Aggregation
- Terms Aggregation
- Pipeline Aggregations
- Avg Bucket Aggregation
- Derivative Aggregation
- Max Bucket Aggregation
- Min Bucket Aggregation
- Sum Bucket Aggregation
- Stats Bucket Aggregation
- Extended Stats Bucket Aggregation
- Percentiles Bucket Aggregation
- Moving Average Aggregation
- Moving Function Aggregation
- Cumulative Sum Aggregation
- Bucket Script Aggregation
- Bucket Selector Aggregation
- Bucket Sort Aggregation
- Serial Differencing Aggregation
- Matrix Aggregations
- Caching heavy aggregations
- Returning only aggregation results
- Aggregation Metadata
- Returning the type of the aggregation
- Metrics Aggregations
- Indices APIs
- Create Index
- Delete Index
- Get Index
- Indices Exists
- Open / Close Index API
- Shrink Index
- Split Index
- Rollover Index
- Put Mapping
- Get Mapping
- Get Field Mapping
- Types Exists
- Index Aliases
- Update Indices Settings
- Get Settings
- Analyze
- Index Templates
- Indices Stats
- Indices Segments
- Indices Recovery
- Indices Shard Stores
- Clear Cache
- Flush
- Refresh
- Force Merge
- cat APIs
- Cluster APIs
- Query DSL
- Scripting
- Mapping
- Analysis
- Anatomy of an analyzer
- Testing analyzers
- Analyzers
- Normalizers
- Tokenizers
- Standard Tokenizer
- Letter Tokenizer
- Lowercase Tokenizer
- Whitespace Tokenizer
- UAX URL Email Tokenizer
- Classic Tokenizer
- Thai Tokenizer
- NGram Tokenizer
- Edge NGram Tokenizer
- Keyword Tokenizer
- Pattern Tokenizer
- Char Group Tokenizer
- Simple Pattern Tokenizer
- Simple Pattern Split Tokenizer
- Path Hierarchy Tokenizer
- Path Hierarchy Tokenizer Examples
- Token Filters
- Standard Token Filter
- ASCII Folding Token Filter
- Flatten Graph Token Filter
- Length Token Filter
- Lowercase Token Filter
- Uppercase Token Filter
- NGram Token Filter
- Edge NGram Token Filter
- Porter Stem Token Filter
- Shingle Token Filter
- Stop Token Filter
- Word Delimiter Token Filter
- Word Delimiter Graph Token Filter
- Multiplexer Token Filter
- Conditional Token Filter
- Predicate Token Filter Script
- Stemmer Token Filter
- Stemmer Override Token Filter
- Keyword Marker Token Filter
- Keyword Repeat Token Filter
- KStem Token Filter
- Snowball Token Filter
- Phonetic Token Filter
- Synonym Token Filter
- Parsing synonym files
- Synonym Graph Token Filter
- Compound Word Token Filters
- Reverse Token Filter
- Elision Token Filter
- Truncate Token Filter
- Unique Token Filter
- Pattern Capture Token Filter
- Pattern Replace Token Filter
- Trim Token Filter
- Limit Token Count Token Filter
- Hunspell Token Filter
- Common Grams Token Filter
- Normalization Token Filter
- CJK Width Token Filter
- CJK Bigram Token Filter
- Delimited Payload Token Filter
- Keep Words Token Filter
- Keep Types Token Filter
- Exclude mode settings example
- Classic Token Filter
- Apostrophe Token Filter
- Decimal Digit Token Filter
- Fingerprint Token Filter
- MinHash Token Filter
- Remove Duplicates Token Filter
- Character Filters
- Modules
- Index Modules
- Ingest Node
- Pipeline Definition
- Ingest APIs
- Accessing Data in Pipelines
- Conditional Execution in Pipelines
- Handling Failures in Pipelines
- Processors
- Append Processor
- Bytes Processor
- Convert Processor
- Date Processor
- Date Index Name Processor
- Dissect Processor
- Dot Expander Processor
- Drop Processor
- Fail Processor
- Foreach Processor
- GeoIP Processor
- Grok Processor
- Gsub Processor
- Join Processor
- JSON Processor
- KV Processor
- Lowercase Processor
- Pipeline Processor
- Remove Processor
- Rename Processor
- Script Processor
- Set Processor
- Set Security User Processor
- Split Processor
- Sort Processor
- Trim Processor
- Uppercase Processor
- URL Decode Processor
- User Agent processor
- Managing the index lifecycle
- SQL Access
- Monitor a cluster
- Rolling up historical data
- Frozen indices
- Set up a cluster for high availability
- Secure a cluster
- Overview
- Configuring security
- Encrypting communications in Elasticsearch
- Encrypting communications in an Elasticsearch Docker Container
- Enabling cipher suites for stronger encryption
- Separating node-to-node and client traffic
- Configuring an Active Directory realm
- Configuring a file realm
- Configuring an LDAP realm
- Configuring a native realm
- Configuring a PKI realm
- Configuring a SAML realm
- Configuring a Kerberos realm
- FIPS 140-2
- Security settings
- Security files
- Auditing Settings
- How security works
- User authentication
- Built-in users
- Internal users
- Token-based authentication services
- Realms
- Realm chains
- Active Directory user authentication
- File-based user authentication
- LDAP user authentication
- Native user authentication
- PKI user authentication
- SAML authentication
- Kerberos authentication
- Integrating with other authentication systems
- Enabling anonymous access
- Controlling the user cache
- Configuring SAML single-sign-on on the Elastic Stack
- User authorization
- Auditing security events
- Encrypting communications
- Restricting connections with IP filtering
- Cross cluster search, tribe, clients, and integrations
- Tutorial: Getting started with security
- Tutorial: Encrypting communications
- Troubleshooting
- Can’t log in after upgrading to 6.8.23
- Some settings are not returned via the nodes settings API
- Authorization exceptions
- Users command fails due to extra arguments
- Users are frequently locked out of Active Directory
- Certificate verification fails for curl on Mac
- SSLHandshakeException causes connections to fail
- Common SSL/TLS exceptions
- Common Kerberos exceptions
- Common SAML issues
- Internal Server Error in Kibana
- Setup-passwords command fails due to connection failure
- Failures due to relocation of the configuration files
- Limitations
- Alerting on Cluster and Index Events
- Command line tools
- How To
- Glossary of terms
- X-Pack APIs
- Info API
- Cross-cluster replication APIs
- Explore API
- Freeze index
- Index lifecycle management API
- Licensing APIs
- Migration APIs
- Machine learning APIs
- Add events to calendar
- Add jobs to calendar
- Close jobs
- Create calendar
- Create datafeeds
- Create filter
- Create jobs
- Delete calendar
- Delete datafeeds
- Delete events from calendar
- Delete filter
- Delete forecast
- Delete jobs
- Delete jobs from calendar
- Delete model snapshots
- Delete expired data
- Find file structure
- Flush jobs
- Forecast jobs
- Get calendars
- Get buckets
- Get overall buckets
- Get categories
- Get datafeeds
- Get datafeed statistics
- Get influencers
- Get jobs
- Get job statistics
- Get machine learning info
- Get model snapshots
- Get scheduled events
- Get filters
- Get records
- Open jobs
- Post data to jobs
- Preview datafeeds
- Revert model snapshots
- Set upgrade mode
- Start datafeeds
- Stop datafeeds
- Update datafeeds
- Update filter
- Update jobs
- Update model snapshots
- Rollup APIs
- Security APIs
- Authenticate
- Change passwords
- Clear cache
- Clear roles cache
- Create API keys
- Create or update application privileges
- Create or update role mappings
- Create or update roles
- Create or update users
- Delete application privileges
- Delete role mappings
- Delete roles
- Delete users
- Disable users
- Enable users
- Get API key information
- Get application privileges
- Get role mappings
- Get roles
- Get token
- Get users
- Has privileges
- Invalidate API key
- Invalidate token
- SSL certificate
- Unfreeze index
- Watcher APIs
- Definitions
- Release Highlights
- Breaking changes
- Release Notes
- Elasticsearch version 6.8.23
- Elasticsearch version 6.8.22
- Elasticsearch version 6.8.21
- Elasticsearch version 6.8.20
- Elasticsearch version 6.8.19
- Elasticsearch version 6.8.18
- Elasticsearch version 6.8.17
- Elasticsearch version 6.8.16
- Elasticsearch version 6.8.15
- Elasticsearch version 6.8.14
- Elasticsearch version 6.8.13
- Elasticsearch version 6.8.12
- Elasticsearch version 6.8.11
- Elasticsearch version 6.8.10
- Elasticsearch version 6.8.9
- Elasticsearch version 6.8.8
- Elasticsearch version 6.8.7
- Elasticsearch version 6.8.6
- Elasticsearch version 6.8.5
- Elasticsearch version 6.8.4
- Elasticsearch version 6.8.3
- Elasticsearch version 6.8.2
- Elasticsearch version 6.8.1
- Elasticsearch version 6.8.0
- Elasticsearch version 6.7.2
- Elasticsearch version 6.7.1
- Elasticsearch version 6.7.0
- Elasticsearch version 6.6.2
- Elasticsearch version 6.6.1
- Elasticsearch version 6.6.0
- Elasticsearch version 6.5.4
- Elasticsearch version 6.5.3
- Elasticsearch version 6.5.2
- Elasticsearch version 6.5.1
- Elasticsearch version 6.5.0
- Elasticsearch version 6.4.3
- Elasticsearch version 6.4.2
- Elasticsearch version 6.4.1
- Elasticsearch version 6.4.0
- Elasticsearch version 6.3.2
- Elasticsearch version 6.3.1
- Elasticsearch version 6.3.0
- Elasticsearch version 6.2.4
- Elasticsearch version 6.2.3
- Elasticsearch version 6.2.2
- Elasticsearch version 6.2.1
- Elasticsearch version 6.2.0
- Elasticsearch version 6.1.4
- Elasticsearch version 6.1.3
- Elasticsearch version 6.1.2
- Elasticsearch version 6.1.1
- Elasticsearch version 6.1.0
- Elasticsearch version 6.0.1
- Elasticsearch version 6.0.0
- Elasticsearch version 6.0.0-rc2
- Elasticsearch version 6.0.0-rc1
- Elasticsearch version 6.0.0-beta2
- Elasticsearch version 6.0.0-beta1
- Elasticsearch version 6.0.0-alpha2
- Elasticsearch version 6.0.0-alpha1
- Elasticsearch version 6.0.0-alpha1 (Changes previously released in 5.x)
NOTE: You are looking at documentation for an older release. For the latest information, see the current release documentation.
Date/Time and Interval Functions and Operators
editDate/Time and Interval Functions and Operators
editElasticsearch SQL offers a wide range of facilities for performing date/time manipulations.
Intervals
editA common requirement when dealing with date/time in general revolves around
the notion of interval
, a topic that is worth exploring in the context of Elasticsearch and Elasticsearch SQL.
Elasticsearch has comprehensive support for date math both inside index names and queries.
Inside Elasticsearch SQL the former is supported as is by passing the expression in the table name, while the latter is supported through the standard SQL INTERVAL
.
The table below shows the mapping between Elasticsearch and Elasticsearch SQL:
Elasticsearch |
Elasticsearch SQL |
Index/Table datetime math |
|
|
|
Query date/time math |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
INTERVAL
allows either YEAR
and MONTH
to be mixed together or DAY
, HOUR
, MINUTE
and SECOND
.
Elasticsearch SQL accepts also the plural for each time unit (e.g. both YEAR
and YEARS
are valid).
Example of the possible combinations below:
Interval |
Description |
|
1 year and 2 months |
|
3 days and 4 hours |
|
5 days, 6 hours and 12 minutes |
|
3 days, 4 hours, 56 minutes and 1 second |
|
2 days, 3 hours, 45 minutes, 1 second and 234567890 nanoseconds |
|
123 hours and 45 minutes |
|
65 hours, 43 minutes, 21 seconds and 12300000 nanoseconds |
|
45 minutes, 1 second and 230000000 nanoseconds |
Operators
editBasic arithmetic operators (+
, -
, etc) support date/time parameters as indicated below:
SELECT INTERVAL 1 DAY + INTERVAL 53 MINUTES AS result; result --------------- +1 00:53:00.0
SELECT CAST('1969-05-13T12:34:56' AS DATETIME) + INTERVAL 49 YEARS AS result; result -------------------- 2018-05-13T12:34:56Z
SELECT - INTERVAL '49-1' YEAR TO MONTH result; result --------------- -49-1
SELECT INTERVAL '1' DAY - INTERVAL '2' HOURS AS result; result --------------- +0 22:00:00.0
SELECT CAST('2018-05-13T12:34:56' AS DATETIME) - INTERVAL '2-8' YEAR TO MONTH AS result; result -------------------- 2015-09-13T12:34:56Z
SELECT -2 * INTERVAL '3' YEARS AS result; result --------------- -6-0
Functions
editFunctions that target date/time.
CURRENT_DATE/CURDATE
editSynopsis:
CURRENT_DATE CURRENT_DATE() CURDATE()
Input: none
Output: date
Description:Returns the date (no time part) when the current query reached the server.
It can be used both as a keyword: CURRENT_DATE
or as a function with no arguments: CURRENT_DATE()
.
Unlike CURRENT_DATE, CURDATE()
can only be used as a function with no arguments and not as a keyword.
This method always returns the same value for its every occurrence within the same query.
SELECT CURRENT_DATE AS result; result ------------------------ 2018-12-12
SELECT CURRENT_DATE() AS result; result ------------------------ 2018-12-12
SELECT CURDATE() AS result; result ------------------------ 2018-12-12
Typically, this function (as well as its twin TODAY()) function is used for relative date filtering:
SELECT first_name FROM emp WHERE hire_date > TODAY() - INTERVAL 35 YEARS ORDER BY first_name ASC LIMIT 5; first_name ------------ Alejandro Amabile Anneke Anoosh Arumugam
CURRENT_TIMESTAMP
editSynopsis:
Input:
Output: date/time
Description:Returns the date/time when the current query reached the server.
As a function, CURRENT_TIMESTAMP()
accepts precision as an optional
parameter for rounding the second fractional digits (nanoseconds). The default precision is 3,
meaning a milliseconds precision current date/time will be returned.
This method always returns the same value for its every occurrence within the same query.
SELECT CURRENT_TIMESTAMP AS result; result ------------------------ 2018-12-12T14:48:52.448Z
SELECT CURRENT_TIMESTAMP() AS result; result ------------------------ 2018-12-12T14:48:52.448Z
SELECT CURRENT_TIMESTAMP(1) AS result; result ------------------------ 2018-12-12T14:48:52.4Z
Typically, this function (as well as its twin NOW()) function is used for relative date/time filtering:
SELECT first_name FROM emp WHERE hire_date > NOW() - INTERVAL 100 YEARS ORDER BY first_name ASC LIMIT 5; first_name --------------- Alejandro Amabile Anneke Anoosh Arumugam
Currently, using a precision greater than 3 doesn’t make any difference to the output of the function as the maximum number of second fractional digits returned is 3 (milliseconds).
DAY_OF_MONTH/DOM/DAY
editSynopsis:
Input:
Output: integer
Description:Extract the day of the month from a date/datetime.
SELECT DAY_OF_MONTH(CAST('2018-02-19T10:23:27Z' AS TIMESTAMP)) AS day; day --------------- 19
DAY_OF_WEEK/DAYOFWEEK/DOW
editSynopsis:
Input:
Output: integer
Description:Extract the day of the week from a date/datetime. Sunday is 1
, Monday is 2
, etc.
SELECT DAY_OF_WEEK(CAST('2018-02-19T10:23:27Z' AS TIMESTAMP)) AS day; day --------------- 2
DAY_OF_YEAR/DOY
editSynopsis:
Input:
Output: integer
Description:Extract the day of the year from a date/datetime.
SELECT DAY_OF_YEAR(CAST('2018-02-19T10:23:27Z' AS TIMESTAMP)) AS day; day --------------- 50
DAY_NAME/DAYNAME
editSynopsis:
Input:
Output: string
Description:Extract the day of the week from a date/datetime in text format (Monday
, Tuesday
…).
SELECT DAY_NAME(CAST('2018-02-19T10:23:27Z' AS TIMESTAMP)) AS day; day --------------- Monday
HOUR_OF_DAY/HOUR
editSynopsis:
Input:
Output: integer
Description:Extract the hour of the day from a date/datetime.
SELECT HOUR_OF_DAY(CAST('2018-02-19T10:23:27Z' AS TIMESTAMP)) AS hour; hour --------------- 10
ISO_DAY_OF_WEEK/ISODAYOFWEEK/ISODOW/IDOW
editSynopsis:
Input:
Output: integer
Description:Extract the day of the week from a date/datetime, following the ISO 8601 standard.
Monday is 1
, Tuesday is 2
, etc.
SELECT ISO_DAY_OF_WEEK(CAST('2018-02-19T10:23:27Z' AS TIMESTAMP)) AS day; day --------------- 1
ISO_WEEK_OF_YEAR/ISOWEEKOFYEAR/ISOWEEK/IWOY/IW
editSynopsis:
Input:
Output: integer
Description:Extract the week of the year from a date/datetime, following ISO 8601 standard. The first week of a year is the first week with a majority (4 or more) of its days in January.
SELECT ISO_WEEK_OF_YEAR(CAST('2018-02-19T10:23:27Z' AS TIMESTAMP)) AS week; week --------------- 8
MINUTE_OF_DAY
editSynopsis:
Input:
Output: integer
Description:Extract the minute of the day from a date/datetime.
SELECT MINUTE_OF_DAY(CAST('2018-02-19T10:23:27Z' AS TIMESTAMP)) AS minute; minute --------------- 623
MINUTE_OF_HOUR/MINUTE
editSynopsis:
Input:
Output: integer
Description:Extract the minute of the hour from a date/datetime.
SELECT MINUTE_OF_HOUR(CAST('2018-02-19T10:23:27Z' AS TIMESTAMP)) AS minute; minute --------------- 23
MONTH_OF_YEAR/MONTH
editSynopsis:
Input:
Output: integer
Description:Extract the month of the year from a date/datetime.
SELECT MONTH_OF_YEAR(CAST('2018-02-19T10:23:27Z' AS TIMESTAMP)) AS month; month --------------- 2
MONTH_NAME/MONTHNAME
editSynopsis:
Input:
Output: string
Description:Extract the month from a date/datetime in text format (January
, February
…).
SELECT MONTH_NAME(CAST('2018-02-19T10:23:27Z' AS TIMESTAMP)) AS month; month --------------- February
NOW
editSynopsis:
NOW()
Input: none
Output: datetime
Description:This function offers the same functionality as CURRENT_TIMESTAMP() function: returns the datetime when the current query reached the server. This method always returns the same value for its every occurrence within the same query.
SELECT NOW() AS result; result ------------------------ 2018-12-12T14:48:52.448Z
Typically, this function (as well as its twin CURRENT_TIMESTAMP()) function is used for relative date/time filtering:
SELECT first_name FROM emp WHERE hire_date > NOW() - INTERVAL 100 YEARS ORDER BY first_name ASC LIMIT 5; first_name --------------- Alejandro Amabile Anneke Anoosh Arumugam
SECOND_OF_MINUTE/SECOND
editSynopsis:
Input:
Output: integer
Description:Extract the second of the minute from a date/datetime.
SELECT SECOND_OF_MINUTE(CAST('2018-02-19T10:23:27Z' AS TIMESTAMP)) AS second; second --------------- 27
QUARTER
editSynopsis:
Input:
Output: integer
Description:Extract the year quarter the date/datetime falls in.
SELECT QUARTER(CAST('2018-02-19T10:23:27Z' AS TIMESTAMP)) AS quarter; quarter --------------- 1
TODAY
editSynopsis:
TODAY()
Input: none
Output: date
Description:This function offers the same functionality as CURRENT_DATE() function: returns the date when the current query reached the server. This method always returns the same value for its every occurrence within the same query.
SELECT TODAY() AS result; result ------------------------ 2018-12-12
Typically, this function (as well as its twin CURRENT_TIMESTAMP()) function is used for relative date filtering:
SELECT first_name FROM emp WHERE hire_date > TODAY() - INTERVAL 35 YEARS ORDER BY first_name ASC LIMIT 5; first_name ------------ Alejandro Amabile Anneke Anoosh Arumugam
WEEK_OF_YEAR/WEEK
editSynopsis:
Input:
Output: integer
Description:Extract the week of the year from a date/datetime.
SELECT WEEK(CAST('1988-01-05T09:22:10Z' AS TIMESTAMP)) AS week, ISOWEEK(CAST('1988-01-05T09:22:10Z' AS TIMESTAMP)) AS isoweek; week | isoweek ---------------+--------------- 2 |1
YEAR
editSynopsis:
Input:
Output: integer
Description:Extract the year from a date/datetime.
SELECT YEAR(CAST('2018-02-19T10:23:27Z' AS TIMESTAMP)) AS year; year --------------- 2018
EXTRACT
editSynopsis:
Input:
Output: integer
Description:Extract fields from a date/datetime by specifying the name of a datetime function. The following
SELECT EXTRACT(DAY_OF_YEAR FROM CAST('2018-02-19T10:23:27Z' AS TIMESTAMP)) AS day; day --------------- 50
is the equivalent to
SELECT DAY_OF_YEAR(CAST('2018-02-19T10:23:27Z' AS TIMESTAMP)) AS day; day --------------- 50
On this page
- Intervals
- Operators
- Functions
CURRENT_DATE/CURDATE
CURRENT_TIMESTAMP
DAY_OF_MONTH/DOM/DAY
DAY_OF_WEEK/DAYOFWEEK/DOW
DAY_OF_YEAR/DOY
DAY_NAME/DAYNAME
HOUR_OF_DAY/HOUR
ISO_DAY_OF_WEEK/ISODAYOFWEEK/ISODOW/IDOW
ISO_WEEK_OF_YEAR/ISOWEEKOFYEAR/ISOWEEK/IWOY/IW
MINUTE_OF_DAY
MINUTE_OF_HOUR/MINUTE
MONTH_OF_YEAR/MONTH
MONTH_NAME/MONTHNAME
NOW
SECOND_OF_MINUTE/SECOND
QUARTER
TODAY
WEEK_OF_YEAR/WEEK
YEAR
EXTRACT
ElasticON events are back!
Learn about the Elastic Search AI Platform from the experts at our live events.
Register now