Elasticsearch JSON Querying: Reference and Examples

Last updated:

WIP ALERT THIS IS A WORK IN PROGRESS

URL-QUERIES VS BODY QUERIES

If you query your server using an url like http://my-server:9200/_search?q=foobar, this is exactly the same as doing the following body query:

{
  "query": {
    "query_string": {
      "query": "foobar"
    }
  }
}

Queries with filters

Say you want to return all documents whose startDate attribute are between two given dates:

{
  "query": {
    "query_string": {
      "query": "*"
    }
  },
  "filter": {
    "range": {
      "startDate": {
        "gte": "2014-09-22T00:56:00",
        "lte": "2014-09-22T01:56:26"
      }
    }
  }
}

Queries with aggregations

Aggregations are a relatively new functionality provided by ES. They allow you to group stuff together (much like you would with GROUP BY in SQL).

For example, if you have many documents of different types, you would need to do the following to know how many documents of each type there are:

{
  "query": {
    "query_string": {
      "query": "*"
    }
  },
  "aggs": {
    "types_agg": {
      "terms": {
        "field": "type"
      }
    }
  },
  "size": 0
}

Resources

Dialogue & Discussion