Skip to main content

ElasticSearch queries cheat sheet

Every time I need to write a query for ElasticSearch, I turn to Google. My brain just refuses to remember the structure of these queries. I decided it’s time to stop this and create a cheat sheet post. First, all the information will be on one page, reducing search time online. Second, writing the post might help me remember more. I hope this cheat sheet will be useful to others.

Filtering

Filtering by the presence of the diff field in the document:

{
    "query": {
        "exists": {
            "field": "diff"
        }
    }
}

Filtering by the range of the created_at field:

{
    "query": {
        "range": {
            "created_at": {
                "gt": 1632749040000,
                "lt": 1632749050000
            }
        }
    }
}

Filtering by multiple conditions via logical AND:

{
    "query": {
        "bool": {
            "must": [
                {
                    "exists": {
                        "field": "diff"
                    }
                },
                {
                    "range": {
                        "created_at": {
                            "gt": 1632749040000,
                            "lt": 1632749050000
                        }
                    }
                }
            ]
        }
    }
}

Filtering by multiple conditions via logical OR:

{
    "query": {
        "bool": {
            "should": [
                {
                    "exists": {
                        "field": "diff"
                    }
                },
                {
                    "range": {
                        "created_at": {
                            "gt": 1632749040000,
                            "lt": 1632749050000
                        }
                    }
                }
            ]
        }
    }
}





Aggregations

Maximum value of the id field:

{
    "size": 0,
    "aggs": {
        "<aggregation_result_name>": {
            "max": {
                "field": "id"
            }
        }
    }
}

Statistics of the numeric field diff:

{
    "size": 0,
    "aggs": {
        "<aggregation_result_name>": {
            "stats": {
                "field": "diff"
            }
        }
    }
}

Percentiles of the numeric field diff:

{
    "size": 0,
    "aggs": {
        "<aggregation_result_name>": {
            "percentiles": {
                "field": "diff"
            }
        }
    }
}
comments powered by Disqus