When you need to interact with an Elasticsearch cluster to perform complex full-text search or data analysis, the domain-specific language (DSL) is your best choice. As a JSON-based query language native to Elasticsearch, DSL enables you to express sophisticated query logic with clarity and precision while giving you fine-grained control over how your queries are executed.
The Elasticsearch Query DSL is a JSON-based query language that defines the structure and semantics of search and data retrieval requests. It contains two contexts:
DSL queries are usually executed in Dev Tools of Kibana. Both the request body and returned information are in JSON.
This topic lists some of the most commonly used DSL query clauses. For more, see Query DSL.
Use match_all to match all documents in the index. It is equivalent to SELECT * FROM table in SQL. Use it when you want to search all documents.
For example, run the following command to match all documents in the test index:
123456GET /test/_search{"query": {"match_all": {}}}
Use a bool query with clauses such as must and filter to construct compound query conditions. This is similar to the where clause in SQL. Use this query when you need to apply multiple conditions to filter documents.
For example, run the following command to retrieve all documents whose status is published and whose publish_date is later than 2015-01-01 (filter condition), and whose title or content contains Search (search condition).
GET /_search{"query": {"bool": {"must": [{"match": {"title": "Search"}},{"match": {"content": "search"}}],"filter": [{"term": {"status": "published"}},{"range": {"publish_date": {"gte": "2015-01-01"}}}]}}}
The differences between must and filter are as follows:
For conditions that do not require relevance scoring (such as status, time range, and category), use filter to improve query performance.
The aggs (such as the terms aggregation) structure is used to perform aggregation queries. It is similar to the Group by clause in SQL. Use it when you want to group documents to calculate metrics.
For example, run the following command to count how many times different titles appear in the test index:
GET /test/_search{"aggs": {"titles": {"terms": {"field": "title.keyword"}}}}
The reason for using title.keyword is as follows:
By default, the cluster automatically creates multi-fields for strings. That means title is used for search, and title.keyword for aggregations.